1001f2a75SMemoryShore use std::{ 2001f2a75SMemoryShore fs::File, 3001f2a75SMemoryShore io::{Read, Write}, 4001f2a75SMemoryShore path::Path, 5001f2a75SMemoryShore }; 6001f2a75SMemoryShore 7001f2a75SMemoryShore pub const ROOT_PATH: &str = "/"; 8*7bb802adSMemoryShore 9*7bb802adSMemoryShore pub struct EnvManager; 10*7bb802adSMemoryShore 11*7bb802adSMemoryShore impl EnvManager { 12001f2a75SMemoryShore pub const ENV_FILE_PATH: &str = "/etc/profile"; 13001f2a75SMemoryShore 14*7bb802adSMemoryShore /// 初始化环境变量相关信息 init()155b859941SMemoryShore pub fn init() { 165b859941SMemoryShore Self::read_env(); 175b859941SMemoryShore } 185b859941SMemoryShore 19001f2a75SMemoryShore /// 初始化环境变量文件 init_envfile()20001f2a75SMemoryShore pub fn init_envfile() { 21*7bb802adSMemoryShore let mut file = File::create(Self::ENV_FILE_PATH).unwrap(); 22001f2a75SMemoryShore file.write_all("PATH=/bin:/usr/bin:/usr/local/bin\n".as_bytes()) 23001f2a75SMemoryShore .unwrap(); 24001f2a75SMemoryShore file.write_all("PWD=/\n".as_bytes()).unwrap(); 25001f2a75SMemoryShore } 26001f2a75SMemoryShore 27001f2a75SMemoryShore /// 读取环境变量文件 28001f2a75SMemoryShore /// 如果文件不存在则创建 read_env()29001f2a75SMemoryShore pub fn read_env() { 30*7bb802adSMemoryShore if !Path::new(Self::ENV_FILE_PATH).exists() { 31*7bb802adSMemoryShore Self::init_envfile(); 32001f2a75SMemoryShore } 33*7bb802adSMemoryShore 34*7bb802adSMemoryShore let mut file = File::open(Self::ENV_FILE_PATH).unwrap(); 35001f2a75SMemoryShore let mut buf: Vec<u8> = Vec::new(); 36001f2a75SMemoryShore file.read_to_end(&mut buf).unwrap(); 375b859941SMemoryShore 385b859941SMemoryShore for str in String::from_utf8(buf).unwrap().split('\n') { 39*7bb802adSMemoryShore if let Some(index) = str.find('=') { 40*7bb802adSMemoryShore std::env::set_var(&str[..index], &str[index + 1..]); 41001f2a75SMemoryShore } 42001f2a75SMemoryShore } 43001f2a75SMemoryShore } 44001f2a75SMemoryShore current_dir() -> String455b859941SMemoryShore pub fn current_dir() -> String { 465b859941SMemoryShore std::env::current_dir() 475b859941SMemoryShore .expect("Error getting current directory") 485b859941SMemoryShore .to_str() 495b859941SMemoryShore .unwrap() 505b859941SMemoryShore .to_string() 515b859941SMemoryShore } 52001f2a75SMemoryShore } 53