Browse Source

支持不使用root在linux上跑 (#8)

* 支持不使用root在linux上跑
* fix: 存在`/etc/profile`就不再创建
裕依2439 5 months ago
parent
commit
ca2bc756f1
4 changed files with 19 additions and 14 deletions
  1. 2 1
      .gitignore
  2. 0 2
      .vscode/settings.json
  3. 15 9
      src/main.rs
  4. 2 2
      src/shell/command/mod.rs

+ 2 - 1
.gitignore

@@ -1,3 +1,4 @@
 /target
 Cargo.lock
-/install/
+/install/
+history_commands.txt

+ 0 - 2
.vscode/settings.json

@@ -1,8 +1,6 @@
 {
     "rust-analyzer.linkedProjects": [
         "./Cargo.toml",
-        "./Cargo.toml",
-        "./Cargo.toml"
     ],
     "rust-analyzer.checkOnSave": true
 }

+ 15 - 9
src/main.rs

@@ -7,6 +7,10 @@ extern crate lazy_static;
 #[macro_use]
 extern crate num_derive;
 
+mod shell;
+
+use num_enum::TryFromPrimitive;
+use shell::Shell;
 use std::{
     collections::HashMap,
     fs::File,
@@ -16,11 +20,8 @@ use std::{
     vec::Vec,
 };
 
-use num_enum::TryFromPrimitive;
-
 pub const ROOT_PATH: &str = "/";
-
-mod shell;
+pub const ENV_FILE_PATH: &str = "/etc/profile";
 
 #[repr(u8)]
 #[derive(Debug, FromPrimitive, TryFromPrimitive, ToPrimitive, PartialEq, Eq, Clone)]
@@ -57,16 +58,22 @@ lazy_static! {
 }
 
 impl Env {
-    fn init_env() {
-        let mut file = File::create("/etc/profile").unwrap();
+    /// 初始化环境变量文件
+    fn init_envfile() {
+        let mut file = File::create(ENV_FILE_PATH).unwrap();
         file.write_all("PATH=/bin:/usr/bin:/usr/local/bin\n".as_bytes())
             .unwrap();
         file.write_all("PWD=/\n".as_bytes()).unwrap();
     }
 
+    /// 读取环境变量文件
+    /// 如果文件不存在则创建
     fn read_env() {
         let mut env = ENV.lock().unwrap();
-        let mut file = File::open("/etc/profile").unwrap();
+        if !Path::new(ENV_FILE_PATH).exists() {
+            Env::init_envfile();
+        }
+        let mut file = File::open(ENV_FILE_PATH).unwrap();
         let mut buf: Vec<u8> = Vec::new();
         file.read_to_end(&mut buf).unwrap();
         for (name, value) in String::from_utf8(buf)
@@ -113,9 +120,8 @@ impl Env {
 }
 
 fn main() {
-    Env::init_env();
     Env::read_env();
-    let mut shell = shell::Shell::new();
+    let mut shell = Shell::new();
     shell.exec();
     return;
 }

+ 2 - 2
src/shell/command/mod.rs

@@ -13,8 +13,8 @@ use std::{
 };
 
 use crate::shell::Shell;
-use crate::Env;
 use crate::ROOT_PATH;
+use crate::{Env, ENV_FILE_PATH};
 
 mod help;
 
@@ -663,7 +663,7 @@ impl Shell {
 
     fn shell_cmd_env(&self, args: &Vec<String>) -> Result<(), CommandError> {
         if args.len() == 0 {
-            let mut file = File::open("/etc/profile").unwrap();
+            let mut file = File::open(ENV_FILE_PATH).unwrap();
             let mut buf: Vec<u8> = Vec::new();
             file.read_to_end(&mut buf).unwrap();
             println!("{}", String::from_utf8(buf).unwrap());