alma/src/storage/loop_device.rs
James McMurray 490ab30f4c Refactor main.rs and fix clippy lints
Status: WIP

Completed:
* Fixed flagged clippy lints
* Moved qemu(), main.rs::mount() and chroot() to the tools module.
* Moved constants in main.rs to constants.rs (including base packages
  array)
* Renamed Presets struct to PresetsCollection to avoid confusion with
  Preset struct
* Moved main() to the top of main.rs to highlight general logic path
* Added comments and docstrings to some functions
* Removed some uses of `use foo::*` to make the source of imported functions
  and structs clearer

TODO:
* Move remaining code in main.rs to modules (except main())
* Break up create() function in to separate steps
* Log every command run (with arguments) to debug! when verbose flag is used
* Add docstrings for remaining functions and document constants (e.g.
  why noatime is used)
* Remove remaining uses of `use foo::*`
* Consider renaming/moving tools module to address tool:: vs. Tool::
  confusion
2020-03-06 23:11:56 +01:00

51 lines
1.2 KiB
Rust

use crate::error::{Error, ErrorKind};
use crate::tool::Tool;
use failure::ResultExt;
use log::info;
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct LoopDevice {
path: PathBuf,
losetup: Tool,
}
impl LoopDevice {
pub fn create(file: &Path) -> Result<Self, Error> {
let losetup = Tool::find("losetup")?;
let output = losetup
.execute()
.args(&["--find", "-P", "--show"])
.arg(file)
.output()
.context(ErrorKind::Image)?;
if !output.status.success() {
return Err(ErrorKind::Losetup(String::from_utf8(output.stderr).unwrap()).into());
}
let path = PathBuf::from(String::from_utf8(output.stdout).unwrap().trim());
info!("Mounted {} to {}", file.display(), path.display());
Ok(LoopDevice { path, losetup })
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for LoopDevice {
fn drop(&mut self) {
info!("Detaching loop device {}", self.path.display());
self.losetup
.execute()
.arg("-d")
.arg(&self.path)
.spawn()
.unwrap()
.wait()
.ok();
}
}