move device related functions & add doc

This commit is contained in:
qwjyh 2023-12-05 03:58:19 +09:00
parent 9706e8d41e
commit 83233740aa
4 changed files with 67 additions and 58 deletions

View file

@ -1,6 +1,10 @@
//! Manipulates each client device. //! Manipulates each client device.
use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter};
use std::path::Path;
use sysinfo::{System, SystemExt}; use sysinfo::{System, SystemExt};
/// YAML file to store known devices. /// YAML file to store known devices.
@ -54,3 +58,49 @@ mod tests {
assert_eq!("test".to_string(), device.name()); assert_eq!("test".to_string(), device.name());
} }
} }
/// Get devname of the device from file `devname`.
fn get_devname(config_dir: &Path) -> Result<String> {
let f = File::open(config_dir.join("devname")).context("Failed to open devname file")?;
let bufreader = BufReader::new(f);
let devname = bufreader
.lines()
.next()
.context("Couldn't get devname.")??;
trace!("devname: {}", devname);
Ok(devname)
}
/// Get current device.
pub fn get_device(config_dir: &Path) -> Result<Device> {
let devname = get_devname(config_dir)?;
let devices = get_devices(config_dir)?;
trace!("devname: {}", devname);
trace!("devices: {:?}", devices);
devices
.into_iter()
.filter(|dev| dev.name() == devname)
.next()
.context("Couldn't find Device in devices.yml")
}
/// Get `Vec<Device>` from yaml file in `config_dir`.
pub fn get_devices(config_dir: &Path) -> Result<Vec<Device>> {
trace!("get_devices");
let f = File::open(config_dir.join(DEVICESFILE))?;
let reader = BufReader::new(f);
let yaml: Vec<Device> =
serde_yaml::from_reader(reader).context("Failed to parse devices.yml")?;
return Ok(yaml);
}
/// Write `devices` to yaml file in `config_dir`.
pub fn write_devices(config_dir: &Path, devices: Vec<Device>) -> Result<()> {
trace!("write_devices");
let f = OpenOptions::new()
.create(true)
.write(true)
.open(config_dir.join(DEVICESFILE))?;
let writer = BufWriter::new(f);
serde_yaml::to_writer(writer, &devices).map_err(|e| anyhow!(e))
}

View file

@ -1,7 +1,9 @@
//! # Main variables //! # Main types
//! * [Device]: represents PC. //! * [Device]: represents PC.
//! * [Storage]: all storages //! * [Storage]: all storages. module [storages]
//! * [PhysicalDrivePartition]: partition on a physical disk. //! * [PhysicalDrivePartition]: partition on a physical disk. [storages::physical_drive_partition]
//! * [Directory]: sub-directory of other storages. [storages::directory]
//! * [storages::local_info::LocalInfo]: stores [Device] specific common data for [Storage]s.
//! //!
#[macro_use] #[macro_use]
@ -26,18 +28,15 @@ use std::{
ffi::OsString, ffi::OsString,
io::{self, BufWriter}, io::{self, BufWriter},
}; };
use std::{ use std::{fmt::Debug, fs::File};
fmt::Debug,
fs::{File, OpenOptions},
};
use std::{fs, io::prelude::*}; use std::{fs, io::prelude::*};
use sysinfo::{Disk, DiskExt, SystemExt}; use sysinfo::{Disk, DiskExt, SystemExt};
use crate::storages::{ use crate::storages::{
get_storages, local_info, physical_drive_partition::*, write_storages, Storage, StorageExt, directory::Directory, get_storages, local_info, physical_drive_partition::*, write_storages,
StorageType, STORAGESFILE, Storage, StorageExt, StorageType, STORAGESFILE,
}; };
use devices::{Device, DEVICESFILE}; use devices::{Device, DEVICESFILE, *};
#[derive(Parser)] #[derive(Parser)]
#[command(author, version, about, long_about = None)] #[command(author, version, about, long_about = None)]
@ -319,31 +318,6 @@ fn main() -> Result<()> {
Ok(()) Ok(())
} }
/// Get devname of the device from file `devname`.
fn get_devname(config_dir: &Path) -> Result<String> {
let f = File::open(config_dir.join("devname")).context("Failed to open devname file")?;
let bufreader = BufReader::new(f);
let devname = bufreader
.lines()
.next()
.context("Couldn't get devname.")??;
trace!("devname: {}", devname);
Ok(devname)
}
/// Get current device.
fn get_device(config_dir: &Path) -> Result<Device> {
let devname = get_devname(config_dir)?;
let devices = get_devices(config_dir)?;
trace!("devname: {}", devname);
trace!("devices: {:?}", devices);
devices
.into_iter()
.filter(|dev| dev.name() == devname)
.next()
.context("Couldn't find Device in devices.yml")
}
/// Set device name interactively. /// Set device name interactively.
fn set_device_name() -> Result<Device> { fn set_device_name() -> Result<Device> {
let validator = |input: &str| { let validator = |input: &str| {
@ -376,27 +350,6 @@ fn set_device_name() -> Result<Device> {
return Ok(device); return Ok(device);
} }
/// Get `Vec<Device>` from yaml file in `config_dir`.
fn get_devices(config_dir: &Path) -> Result<Vec<Device>> {
trace!("get_devices");
let f = File::open(config_dir.join(DEVICESFILE))?;
let reader = BufReader::new(f);
let yaml: Vec<Device> =
serde_yaml::from_reader(reader).context("Failed to parse devices.yml")?;
return Ok(yaml);
}
/// Write `devices` to yaml file in `config_dir`.
fn write_devices(config_dir: &Path, devices: Vec<Device>) -> Result<()> {
trace!("write_devices");
let f = OpenOptions::new()
.create(true)
.write(true)
.open(config_dir.join(DEVICESFILE))?;
let writer = BufWriter::new(f);
serde_yaml::to_writer(writer, &devices).map_err(|e| anyhow!(e))
}
fn ask_unique_name(storages: &HashMap<String, Storage>, target: String) -> Result<String> { fn ask_unique_name(storages: &HashMap<String, Storage>, target: String) -> Result<String> {
let mut disk_name = String::new(); let mut disk_name = String::new();
loop { loop {

View file

@ -1,3 +1,5 @@
//! Device specific common data for storages.
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::path; use std::path;

View file

@ -91,7 +91,11 @@ impl StorageExt for PhysicalDrivePartition {
self.local_info.get(&device.name()).is_some() self.local_info.get(&device.name()).is_some()
} }
fn mount_path(&self, device: &devices::Device, _: &HashMap<String, Storage>) -> Result<path::PathBuf> { fn mount_path(
&self,
device: &devices::Device,
_: &HashMap<String, Storage>,
) -> Result<path::PathBuf> {
Ok(self Ok(self
.local_info .local_info
.get(&device.name()) .get(&device.name())