alma/src/process.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

52 lines
1.5 KiB
Rust

use super::error::{Error, ErrorKind};
use failure::{Fail, ResultExt};
use log::error;
use std::process::{Command, ExitStatus};
use std::str;
#[derive(Debug, Fail)]
enum ProcessError {
#[fail(display = "{}", _0)]
BadExitCode(ExitStatus),
#[fail(display = "Process output isn't valid UTF-8")]
InvalidUtf8,
}
pub trait CommandExt {
fn run(&mut self, context: ErrorKind) -> Result<(), Error>;
fn run_text_output(&mut self, context: ErrorKind) -> Result<String, Error>;
}
impl CommandExt for Command {
fn run(&mut self, context: ErrorKind) -> Result<(), Error> {
let exit_status = self
.spawn()
.with_context(|_| context.clone())?
.wait()
.with_context(|_| context.clone())?;
if !exit_status.success() {
Err(ProcessError::BadExitCode(exit_status)).with_context(|_| context.clone())?;
}
Ok(())
}
fn run_text_output(&mut self, context: ErrorKind) -> Result<String, Error> {
let output = self.output().with_context(|_| context.clone())?;
if !output.status.success() {
let error = str::from_utf8(&output.stderr).unwrap_or("[INVALID UTF8]");
error!("{}", error);
Err(ProcessError::BadExitCode(output.status)).with_context(|_| context.clone())?;
}
Ok(String::from(
str::from_utf8(&output.stdout)
.map_err(|_| ProcessError::InvalidUtf8)
.with_context(|_| context.clone())?,
))
}
}