Files
topgrade/src/utils.rs

71 lines
1.6 KiB
Rust
Raw Normal View History

2018-12-11 16:43:26 +02:00
use super::error::{Error, ErrorKind};
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-12-09 10:30:41 +02:00
use which_crate;
2018-06-17 11:43:25 +03:00
pub trait Check {
fn check(self) -> Result<(), Error>;
}
impl Check for ExitStatus {
fn check(self) -> Result<(), Error> {
if self.success() {
Ok(())
} else {
2018-12-11 16:43:26 +02:00
Err(ErrorKind::ProcessFailed(self))?
2018-06-17 11:43:25 +03:00
}
}
}
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> {
2018-12-09 10:30:41 +02:00
match which_crate::which(&binary_name) {
2018-06-17 14:17:36 +03:00
Ok(path) => {
debug!("Detected {:?} as {:?}", &path, &binary_name);
Some(path)
}
Err(e) => {
match e.kind() {
2018-12-09 10:30:41 +02:00
which_crate::ErrorKind::CannotFindBinaryPath => {
2018-06-17 14:17:36 +03:00
debug!("Cannot find {:?}", &binary_name);
}
_ => {
error!("Detecting {:?} failed: {}", &binary_name, e);
}
}
None
}
}
}