main.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. extern crate libc;
  2. #[macro_use]
  3. extern crate lazy_static;
  4. use std::{
  5. collections::HashMap,
  6. fs::File,
  7. io::{Read, Write},
  8. path::Path,
  9. string::String,
  10. vec::Vec,
  11. };
  12. pub const ROOT_PATH: &str = "/";
  13. mod shell;
  14. pub mod special_keycode {
  15. pub const LF: u8 = b'\n';
  16. pub const CR: u8 = b'\r';
  17. pub const DL: u8 = b'\x7f';
  18. pub const BS: u8 = b'\x08';
  19. pub const SPACE: u8 = b' ';
  20. pub const TAB: u8 = b'\t';
  21. pub const UP: u8 = 72;
  22. pub const DOWN: u8 = 80;
  23. pub const LEFT: u8 = 75;
  24. pub const RIGHT: u8 = 77;
  25. }
  26. struct Env(std::collections::HashMap<String, String>);
  27. lazy_static! {
  28. static ref ENV: std::sync::Mutex<Env> = std::sync::Mutex::new(Env(HashMap::new()));
  29. }
  30. impl Env {
  31. fn init_env() {
  32. let mut file = File::create("/etc/profile").unwrap();
  33. file.write_all("PATH=/bin:/usr/bin:/usr/local/bin\n".as_bytes())
  34. .unwrap();
  35. file.write_all("PWD=/\n".as_bytes()).unwrap();
  36. }
  37. fn read_env() {
  38. let env = &mut ENV.lock().unwrap().0;
  39. let mut file = File::open("/etc/profile").unwrap();
  40. let mut buf: Vec<u8> = Vec::new();
  41. file.read_to_end(&mut buf).unwrap();
  42. for (name, value) in String::from_utf8(buf)
  43. .unwrap()
  44. .split('\n')
  45. .filter_map(|str| {
  46. let v = str.split('=').collect::<Vec<&str>>();
  47. if v.len() == 2 && !v.contains(&"") {
  48. Some((*v.get(0).unwrap(), *v.get(1).unwrap()))
  49. } else {
  50. None
  51. }
  52. })
  53. .collect::<Vec<(&str, &str)>>()
  54. {
  55. env.insert(String::from(name), String::from(value));
  56. }
  57. }
  58. fn get(key: &String) -> Option<String> {
  59. let env = &mut ENV.lock().unwrap().0;
  60. env.get(key).map(|value| value.clone())
  61. }
  62. fn insert(key: String, value: String) {
  63. ENV.lock().unwrap().0.insert(key, value);
  64. }
  65. fn path() -> Vec<String> {
  66. let env = &ENV.lock().unwrap().0;
  67. let paths = env.get("PATH").unwrap();
  68. paths
  69. .split(':')
  70. .filter_map(|str| {
  71. let path = String::from(str);
  72. if Path::new(&path).is_dir() {
  73. Some(path)
  74. } else {
  75. None
  76. }
  77. })
  78. .collect::<Vec<String>>()
  79. }
  80. }
  81. fn main() {
  82. Env::init_env();
  83. Env::read_env();
  84. let mut shell = shell::Shell::new();
  85. shell.exec();
  86. return;
  87. }