summary refs log tree commit diff
path: root/src/main.rs
blob: e94ce0c3821819f0a9709b3ae64fcef8fc87eacf (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
#![forbid(unsafe_code)]
use crate::result::Result;
use crate::terminal::{Input, Terminal};

use std::collections::HashMap;
use std::collections::HashSet;
use std::env;
use std::os::unix::fs::PermissionsExt;
use std::process::{self, Command};
use tokio::io::{self, AsyncWriteExt};

#[macro_use] extern crate lalrpop_util;

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


#[tokio::main]
async fn main() -> Result<()> {
  let result = repl().await;
  process::exit(match result {
    Ok(()) => 0,
    Err(ref e) => {
      eprintln!("{}", e);
      1
    }
  })
}


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

  let mut terminal = Terminal::init(io::stdin())?;

  loop {
    prompt().await?;

    let input = terminal.handle_input().await?;

    match input {
      Input::String(string) => {
        println!("{:?} {}", string, string.len());
        execute(&string).await?
      },
      Input::End => break,
    }

    break;
  }

  terminal.cleanup()?;

  Ok(())
}


async fn prompt() -> Result<()> {
  let mut stdout = io::stdout();
  stdout.write_all("\n$ ".as_bytes()).await?;
  stdout.flush().await?;

  Ok(())
}


async 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(env::vars().collect())
}


fn get_environment(variable_name: &str) -> Result<Option<String>> {
  Ok(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)
}