summary refs log tree commit diff
path: root/src/main.rs
blob: 3b7d26dd6b7f3008d5542bb1f386a8e7767fbec5 (plain)
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use crate::prelude::*;
use std::collections::HashMap;
use std::collections::HashSet;
use std::io;
use std::io::prelude::*;
use std::os::unix::fs::PermissionsExt;

#[macro_use] extern crate lalrpop_util;

lalrpop_mod!(pub commandline);
pub mod error;
pub mod path;
pub mod prelude;
pub mod result;


pub enum Input {
  String(String),
  End,
}


fn main() -> Result<()> {
  std::process::exit(match repl() {
    Ok(()) => 0,
    Err(ref e) => {
      eprintln!("{}", e);
      1
    }
  })
}


fn repl() -> Result<()> {
  println!("Hello, terminal!");

  loop {
    prompt()?;

    let input = read()?;
    match input {
      Input::String(string) => execute(&string)?,
      Input::End => break,
    }
  }

  Ok(())
}


fn prompt() -> Result<()> {
  print!("$ ");
  io::stdout().flush()?;

  Ok(())
}


fn read() -> Result<Input> {
  let mut input = String::new();
  let n_bytes = io::stdin().read_line(&mut input)?;

  if n_bytes == 0 {
    Ok(Input::End)
  } else {
    Ok(Input::String(input))
  }
}


fn execute(input: &str) -> Result<()> {
  let invocation = commandline::InvocationParser::new().parse(input)?;

  println!("{}", input);

  match invocation.as_slice() {
    ["environment", ..] => {
      let environment = read_environment()?;
      println!("{:?}", environment);
    }
    ["which", command_name, ..] => {
      let file_name: path::FileName = command_name.parse()?;
      let search_paths = get_search_paths()?;
      let mut executable_path: Option<path::AbsoluteFilePath> = None;
      for search_path in &search_paths {
        let candidate_path = search_path.concat_file_name(&file_name);
        match candidate_path.to_sys_path().metadata() {
          Ok(metadata) => {
            if metadata.is_file()
              && metadata.permissions().mode() & 0o111 != 0
            {
              println!("{} {:?}", candidate_path, metadata);
              executable_path = Some(candidate_path);
              break;
            }
          },
          Err(_) => { },
        }

      }
    },
    _ => {
      println!("invocation '{:?}'", invocation);
    }
  }

  Ok(())
}


fn read_environment() -> Result<HashMap<String,String>> {
  Ok(std::env::vars().collect())
}


fn get_environment(variable_name: &str) -> Result<Option<String>> {
  Ok(std::env::vars()
     .find(|(key, _)| key == variable_name)
     .map(|(_, value)| value))
}


fn get_search_paths() -> Result<Vec<path::AbsoluteDirectoryPath>> {
  let paths = get_environment("PATH")?.unwrap_or_default();
  let paths = path::parse_path_list(&paths)?;

  let mut result = Vec::new();
  let mut seen = HashSet::new();
  for path in paths {
    if seen.contains(&path) {
      continue;
    }

    seen.insert(path.clone());
    result.push(path);
  }

  Ok(result)
}