e_utils/system/
env.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use crate::Error;
use crate::Result;
use std::{env, path::Path};

/// 添加环境变量到系统目录
/// 兼容linux与windows
pub fn add_system_path<P>(directory: P) -> Result<()>
where
  P: AsRef<Path>,
{
  // Windows使用;,而Unix-like系统使用:
  let path_separator = if cfg!(windows) { ';' } else { ':' };
  // 获取当前的环境变量值
  let mut path = env::var("PATH").unwrap_or_default();
  // 路径确保不存在
  let directory_str = directory
    .as_ref()
    .to_str()
    .ok_or_else(|| 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);
  // 设置新的PATH环境变量
  env::set_var("PATH", path);

  Ok(())
}