1 use std::{ 2 fs::File, 3 io::{Read, Write}, 4 path::Path, 5 }; 6 7 pub const ROOT_PATH: &str = "/"; 8 9 pub struct EnvManager; 10 11 impl EnvManager { 12 pub const ENV_FILE_PATH: &str = "/etc/profile"; 13 14 /// 初始化环境变量相关信息 init()15 pub fn init() { 16 Self::read_env(); 17 } 18 19 /// 初始化环境变量文件 init_envfile()20 pub fn init_envfile() { 21 let mut file = File::create(Self::ENV_FILE_PATH).unwrap(); 22 file.write_all("PATH=/bin:/usr/bin:/usr/local/bin\n".as_bytes()) 23 .unwrap(); 24 file.write_all("PWD=/\n".as_bytes()).unwrap(); 25 } 26 27 /// 读取环境变量文件 28 /// 如果文件不存在则创建 read_env()29 pub fn read_env() { 30 if !Path::new(Self::ENV_FILE_PATH).exists() { 31 Self::init_envfile(); 32 } 33 34 let mut file = File::open(Self::ENV_FILE_PATH).unwrap(); 35 let mut buf: Vec<u8> = Vec::new(); 36 file.read_to_end(&mut buf).unwrap(); 37 38 for str in String::from_utf8(buf).unwrap().split('\n') { 39 if let Some(index) = str.find('=') { 40 std::env::set_var(&str[..index], &str[index + 1..]); 41 } 42 } 43 } 44 current_dir() -> String45 pub fn current_dir() -> String { 46 std::env::current_dir() 47 .expect("Error getting current directory") 48 .to_str() 49 .unwrap() 50 .to_string() 51 } 52 } 53