refactoring: moved storage related functions to crate storage

This commit is contained in:
qwjyh 2023-08-30 03:05:26 +09:00
parent 78b2d956a7
commit 33e1a9aba7
3 changed files with 124 additions and 109 deletions

View file

@ -1,15 +1,16 @@
//! Manipulate partition of physical drive (both removable and unremovable).
use crate::{devices::Device, get_device};
use crate::storages::StorageExt;
use crate::storages::{Storage, StorageExt};
use anyhow::{anyhow, Context, Result};
use byte_unit::Byte;
use inquire::Text;
use serde::{Deserialize, Serialize};
use std::{
collections::{hash_map::RandomState, HashMap},
fmt,
};
use sysinfo::DiskExt;
use sysinfo::{Disk, DiskExt, SystemExt};
/// Partitoin of physical (on-premises) drive.
#[derive(Serialize, Deserialize, Debug)]
@ -89,3 +90,72 @@ impl fmt::Display for PhysicalDrivePartition {
)
}
}
/// Interactively select physical storage from available disks in sysinfo.
pub fn select_physical_storage(
device: Device,
storages: &Vec<Storage>,
) -> Result<PhysicalDrivePartition> {
trace!("select_physical_storage");
// get disk info fron sysinfo
let mut sys_disks = sysinfo::System::new_all();
sys_disks.refresh_disks();
trace!("Available disks");
for disk in sys_disks.disks() {
trace!("{:?}", disk)
}
let disk = select_sysinfo_disk(&sys_disks)?;
// name the disk
let mut disk_name = String::new();
trace!("{}", disk_name);
loop {
disk_name = Text::new("Name for the disk:").prompt()?;
if storages.iter().all(|s| s.name() != &disk_name) {
break;
}
println!("The name {} is already used.", disk_name);
}
trace!("selected name: {}", disk_name);
PhysicalDrivePartition::try_from_sysinfo_disk(&disk, disk_name, device)
}
pub fn select_sysinfo_disk(sysinfo: &sysinfo::System) -> Result<&Disk> {
let available_disks = sysinfo
.disks()
.iter()
.enumerate()
.map(|(i, disk)| {
let name = match disk.name().to_str() {
Some(s) => s,
None => "",
};
let fs: &str = std::str::from_utf8(disk.file_system()).unwrap_or("unknown");
let kind = format!("{:?}", disk.kind());
let mount_path = disk.mount_point();
let total_space = byte_unit::Byte::from_bytes(disk.total_space().into())
.get_appropriate_unit(true)
.to_string();
format!(
"{}: {} {} ({}, {}) {}",
i,
name,
total_space,
fs,
kind,
mount_path.display()
)
})
.collect();
// select from list
let disk = inquire::Select::new("Select drive:", available_disks).prompt()?;
let disk_num: usize = disk.split(':').next().unwrap().parse().unwrap();
trace!("disk_num: {}", disk_num);
let disk = sysinfo
.disks()
.iter()
.nth(disk_num)
.context("no disk matched with selected one.")?;
trace!("selected disk: {:?}", disk);
Ok(disk)
}