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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
|
use ctrlc;
use notify::RecursiveMode;
use notify::Watcher;
use signals2::*;
use std::fs;
use std::io;
use std::io::Write;
use std::path::Path;
use std::process::Command;
use std::sync::Arc;
use std::sync::RwLock;
fn prefresh(paths: &Vec<String>, bins: &mut Arc<RwLock<Vec<Vec<String>>>>, index: Option<i32>) {
let mut bins = bins.write().unwrap();
let index = index.unwrap_or(-1);
if index == -1 {
for (i, path) in paths.iter().enumerate() {
let files = fs::read_dir(path).expect("Unable to read files in your path");
bins.push(Vec::new());
for file in files {
bins[i].push(file.unwrap().path().display().to_string());
}
}
} else {
let index = index as usize;
let files = fs::read_dir(paths[index].as_str()).expect("Unable to read files in your path");
bins[index].clear();
for file in files {
bins[index].push(file.unwrap().path().display().to_string());
}
}
}
fn eval(paths: Vec<String>, prompt: &str) {
// Setup search for our paths
let mut bins = Arc::new(RwLock::new(Vec::new()));
prefresh(&paths, &mut bins, None);
// Handle file changes on paths
let sig: Signal<(i32,)> = Signal::new();
let arcbins = Arc::clone(&bins);
let p = paths.clone();
sig.connect(move |i| {
let mut arcbins = arcbins.clone();
prefresh(&paths, &mut arcbins, Some(i));
});
let mut watcher =
notify::recommended_watcher(move |res: Result<notify::event::Event, notify::Error>| {
match res {
Ok(event) => {
if event.kind.is_create() || event.kind.is_remove() {
sig.emit(0);
}
}
Err(_) => {}
}
})
.unwrap();
for path in p {
watcher
.watch(Path::new(path.as_str()), RecursiveMode::Recursive)
.unwrap();
}
// Main REPL
loop {
// Output the prompt
io::stdout().flush().unwrap();
print!("{}", prompt);
io::stdout().flush().unwrap();
// Wait for user input
let mut input = String::new();
let bytes = io::stdin()
.read_line(&mut input)
.expect("Unable to evaluate the input string");
// Check if we've reached EOF (i.e. <C-d>)
if bytes == 0 {
println!("");
break;
}
// Trim the input
let input = input.trim();
// Check if user wants to exit the shell
if input == "exit" || input == "quit" {
break;
}
// Parse command and arguments
let mut split = input.split(' ');
let cmd = match split.next() {
Some(str) if str.trim().is_empty() => continue,
Some(str) => str.trim(),
None => continue,
};
// Parse arguments
let mut args = vec![];
loop {
let next = split.next();
match next {
Some(str) => args.push(str),
None => break,
}
}
// Check if user wants to change directories
if cmd == "cd" {
let path = match args.first() {
Some(str) => str,
None => env!("HOME"),
};
match std::env::set_current_dir(path) {
Ok(_) => continue,
Err(_) => {
println!("cd: Unable to change into {}", path);
continue;
}
}
}
// Check if the file exists, if given a pull or relative path
// TODO: Check if file at the path is executable (i.e. +x)
let mut cmd = String::from(cmd);
if !Path::new(cmd.as_str()).exists() {
cmd = match bins
.read()
.unwrap()
.iter()
.flatten()
.map(|s| String::from(s))
.collect::<Vec<String>>()
.iter()
.find(|b| b.split("/").last().unwrap() == cmd)
{
Some(cmd) => String::from(cmd),
None => {
println!("dwvsh: error: command not found...");
continue;
}
};
}
// Run the command (and wait for it to finish)
let mut child = match Command::new(cmd).args(args).spawn() {
Ok(ch) => ch,
Err(_) => {
println!("Unable to fork");
continue;
}
};
child.wait().unwrap();
}
}
fn main() {
// Define paths
// TODO: Hardcoded path should only be the fallback
let paths = vec![
"/bin".to_string(),
"/sbin".to_string(),
"/usr/bin".to_string(),
"/usr/sbin".to_string(),
"/usr/local/bin".to_string(),
"/usr/local/sbin".to_string(),
];
// Set the prompt
let prompt = "|> ";
// Handle SIGINT
ctrlc::set_handler(move || {
print!("\n{}", prompt);
io::stdout().flush().unwrap();
})
.expect("Unable to set <C-c> handler");
// Begin evaluating commands
eval(paths, prompt);
}
|