use crate::Error;
use crate::Result;
use std::env::var;
use std::path::PathBuf;
use std::{env, path::Path};
pub static ORIGINAL_DIR: &'static str = "ORIGINAL_DIR";
pub fn add_system_path<P>(directory: P) -> Result<()>
where
P: AsRef<Path>,
{
let path_separator = if cfg!(windows) { ';' } else { ':' };
let mut path = match env::var("PATH") {
Ok(path) => path,
Err(_) => String::new(),
};
let directory_str = directory
.as_ref()
.to_str()
.ok_or(Error::Option("add_system_path 解析路径出错".into()))?
.to_string();
if directory_str.is_empty() || path.is_empty() {
return Err(Error::Empty);
}
let new_path = format!("{}{}", &directory_str, path_separator);
if path.contains(&new_path) {
return Err(Error::Exists(new_path.into()));
}
path.push_str(&new_path);
env::set_var("PATH", path);
Ok(())
}
pub fn env_path_join(variable: &str, add: &str) -> Result<PathBuf> {
let var_path = Path::new(&var(variable)?).to_path_buf();
if var_path.exists() {
let target = var_path.join(add);
if target.exists() {
Ok(target)
} else {
Err(Error::NotFound(target.to_string_lossy().to_string().into()))
}
} else {
Err(Error::NotFound(
var_path.to_string_lossy().to_string().into(),
))
}
}
pub fn init_original_dir() -> Result<PathBuf> {
let current_dir = env::current_dir()?;
env::set_var(ORIGINAL_DIR, current_dir.clone());
Ok(current_dir)
}
pub fn reset_original_dir() -> Result<PathBuf> {
let res = get_original_dir()?;
env::set_current_dir(res.clone())?;
Ok(res)
}
pub fn get_original_dir() -> Result<PathBuf> {
env::var_os(ORIGINAL_DIR)
.and_then(|x| Some(Path::new(&x).to_path_buf()))
.ok_or("无法读取ORIGINAL_DIR变量".into())
}