You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
1.5 KiB
80 lines
1.5 KiB
4 years ago
|
use std::{
|
||
|
fmt,
|
||
|
borrow::Cow,
|
||
|
path::{
|
||
|
Path,
|
||
|
PathBuf,
|
||
|
},
|
||
|
};
|
||
|
|
||
|
const DEFAULT_BINARY_NAME: &'static str = "leanify";
|
||
|
|
||
|
#[derive(Debug)]
|
||
|
pub enum Error
|
||
|
{
|
||
|
FileFailed(PathBuf),
|
||
|
PathFailed(PathBuf),
|
||
|
}
|
||
|
|
||
|
impl std::error::Error for Error{}
|
||
|
impl std::fmt::Display for Error
|
||
|
{
|
||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
|
||
|
{
|
||
|
match self {
|
||
|
Self::FileFailed(path) => write!(f, "file {:?} does not exist.", path),
|
||
|
Self::PathFailed(path) => write!(f, "no directory in `$PATH` contained file {:?}", path),
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fn binary_name() -> Cow<'static, str>
|
||
|
{
|
||
|
if let Ok(bin_name) = std::env::var("LEANIFY") {
|
||
|
if bin_name.len() > 0 {
|
||
|
return Cow::Owned(bin_name);
|
||
|
}
|
||
|
}
|
||
|
return Cow::Borrowed(DEFAULT_BINARY_NAME);
|
||
|
}
|
||
|
|
||
|
fn get_path() -> Vec<PathBuf>
|
||
|
{
|
||
|
if let Ok(path) = std::env::var("PATH")
|
||
|
{
|
||
|
path.split(":").filter_map(|x| {
|
||
|
let path = Path::new(x);
|
||
|
if path.is_dir() {
|
||
|
Some(path.to_owned())
|
||
|
} else {
|
||
|
None
|
||
|
}
|
||
|
}).collect()
|
||
|
} else {
|
||
|
Vec::default()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/// Find the path to leanify binary
|
||
|
pub fn find_binary() -> Result<PathBuf, Error>
|
||
|
{
|
||
|
let path = binary_name();
|
||
|
let path = Path::new(path.as_ref());
|
||
|
|
||
|
if path.is_file() {
|
||
|
Ok(path.to_owned())
|
||
|
}
|
||
|
else if !path.is_absolute() {
|
||
|
//Lookup in $PATH
|
||
|
for spath in get_path().into_iter() {
|
||
|
let spath = spath.join(path);
|
||
|
if spath.is_file() {
|
||
|
return Ok(spath);
|
||
|
}
|
||
|
}
|
||
|
Err(Error::PathFailed(path.to_owned()))
|
||
|
} else {
|
||
|
Err(Error::FileFailed(path.to_owned()))
|
||
|
}
|
||
|
}
|