e_utils/system/
env.rs

1use crate::Error;
2use crate::Result;
3use std::{env, path::Path};
4
5/// 添加环境变量到系统目录
6/// 兼容linux与windows
7pub fn add_system_path<P>(directory: P) -> Result<()>
8where
9  P: AsRef<Path>,
10{
11  // Windows使用;,而Unix-like系统使用:
12  let path_separator = if cfg!(windows) { ';' } else { ':' };
13  // 获取当前的环境变量值
14  let mut path = env::var("PATH").unwrap_or_default();
15  // 路径确保不存在
16  let directory_str = directory
17    .as_ref()
18    .to_str()
19    .ok_or_else(|| Error::Option("add_system_path 解析路径出错".into()))?
20    .to_string();
21  // 不能为空
22  if directory_str.is_empty() || path.is_empty() {
23    return Err(Error::Empty);
24  }
25  let new_path = format!("{}{}", &directory_str, path_separator);
26  // 路径已经存在
27  if path.contains(&new_path) {
28    return Err(Error::Exists(new_path.into()));
29  }
30  path.push_str(&new_path);
31  // 设置新的PATH环境变量
32  env::set_var("PATH", path);
33
34  Ok(())
35}