summary refs log tree commit diff
path: root/src/main.rs
blob: d7a2aff2dd9366e1eab656f2195c0b8b6db02e36 (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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use crate::prelude::*;
use std::collections::HashMap;
use std::collections::HashSet;
use std::io;
use std::io::prelude::*;
use std::os::unix::fs::PermissionsExt;
use std::process::Command;

#[macro_use] extern crate lalrpop_util;

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


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()?;

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

  Ok(())
}


fn prompt() -> Result<()> {
  print!("\n$ ");
  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)?;

  match invocation.as_slice() {
    ["environment", ..] => {
      let environment = read_environment()?;
      println!("{:?}", environment);
    }
    ["which", command_name, ..] => {
      match find_executable_path(command_name)? {
        Some(executable_path) => {
          println!("{}", executable_path);
        }
        None => {
          println!("Command not found: {}", command_name);
        }
      };
    },
    [command_name, ..] => {
      match find_executable_path(command_name)? {
        Some(executable_path) => {
          let mut command = Command::new(executable_path.to_sys_path());

          let arguments = &invocation[1..];
          command.args(arguments);

          let _status = command.status()?;
        }
        None => {
          println!("Command not found: {}", command_name);
        }
      };
    },
    _ => {
      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)
}


fn find_executable_path(command_name: &str)
  -> Result<Option<path::AbsoluteFilePath>>
{
  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
        {
          executable_path = Some(candidate_path);
          break;
        }
      },
      Err(_) => { },
    }
  }

  Ok(executable_path)
}