Files
topgrade/src/utils.rs

76 lines
1.7 KiB
Rust
Raw Normal View History

2018-06-17 11:43:25 +03:00
use failure::Error;
2018-11-18 14:25:16 +02:00
use failure_derive::Fail;
use log::{debug, error};
2018-06-17 14:17:36 +03:00
use std::ffi::OsStr;
use std::fmt::Debug;
2018-06-17 11:43:25 +03:00
use std::path::{Path, PathBuf};
2018-08-22 22:18:48 +03:00
use std::process::{ExitStatus, Output};
2018-06-17 14:17:36 +03:00
use which as which_mod;
2018-06-17 11:43:25 +03:00
#[derive(Fail, Debug)]
#[fail(display = "Process failed")]
pub struct ProcessFailed;
pub trait Check {
fn check(self) -> Result<(), Error>;
}
impl Check for ExitStatus {
fn check(self) -> Result<(), Error> {
if self.success() {
Ok(())
} else {
Err(Error::from(ProcessFailed {}))
}
}
}
2018-08-22 22:18:48 +03:00
impl Check for Output {
fn check(self) -> Result<(), Error> {
self.status.check()
}
}
2018-07-07 09:18:53 +03:00
pub trait PathExt
where
Self: Sized,
{
fn if_exists(self) -> Option<Self>;
2018-08-22 10:43:32 +03:00
fn is_descendant_of(&self, ancestor: &Path) -> bool;
2018-07-07 09:18:53 +03:00
}
impl PathExt for PathBuf {
fn if_exists(self) -> Option<Self> {
if self.exists() {
Some(self)
} else {
None
}
2018-06-17 11:43:25 +03:00
}
2018-07-07 09:18:53 +03:00
fn is_descendant_of(&self, ancestor: &Path) -> bool {
self.iter().zip(ancestor.iter()).all(|(a, b)| a == b)
}
2018-06-17 11:43:25 +03:00
}
2018-06-17 14:17:36 +03:00
pub fn which<T: AsRef<OsStr> + Debug>(binary_name: T) -> Option<PathBuf> {
match which_mod::which(&binary_name) {
Ok(path) => {
debug!("Detected {:?} as {:?}", &path, &binary_name);
Some(path)
}
Err(e) => {
match e.kind() {
which_mod::ErrorKind::CannotFindBinaryPath => {
debug!("Cannot find {:?}", &binary_name);
}
_ => {
error!("Detecting {:?} failed: {}", &binary_name, e);
}
}
None
}
}
}