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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
|
use std::env;
use std::io::{self, Write};
use std::sync::{Arc, Mutex};
mod buffer;
mod path;
mod poem;
use poem::{read::Readable, recite::Reciteable, Poem};
mod compose;
use buffer::{getline, Key, STDIN};
use compose::Environment;
use termios::{tcsetattr, Termios, ECHO, ECHOE, ICANON, TCSANOW};
/// Starts the main shell loop
///
/// # Arguments
/// * `away` - A mutex, indicating whether or not user is at the prompt
/// * `env` - The global shell state
///
/// # Examples
/// ```
/// fn main() {
/// let mut env = compose::env();
/// let mut away = Arc::new(Mutex::new(false));
/// ...
/// repl(&mut away, &mut env);
/// }
/// ```
fn repl(
away: &mut Arc<Mutex<bool>>,
buffer: &mut Arc<Mutex<Vec<char>>>,
pos: &mut Arc<Mutex<usize>>,
comp_pos: &mut Arc<Mutex<usize>>,
comp_len: &mut Arc<Mutex<usize>>,
last_key: &mut Arc<Mutex<Key>>,
env: &mut Environment,
) {
// Setup termios flags
let mut termios = Termios::from_fd(STDIN).unwrap();
// Initial path refresh on startup
env.bins = path::refresh();
// Main shell loop
loop {
// Get the prompt
let prompt = match env::var("PS1") {
Ok(val) => val,
Err(_) => String::from("|> "),
};
// Output the prompt
print!("{}", prompt);
io::stdout().flush().unwrap();
// At the prompt
*away.lock().unwrap() = false;
// Unset ICANON and ECHO before the prompt
termios.c_lflag &= !(ICANON | ECHO);
tcsetattr(STDIN, TCSANOW, &mut termios).unwrap();
// Wait for user input
let bytes = getline(buffer, pos, comp_pos, comp_len, last_key);
// Check if we've reached EOF (i.e. <C-d>)
if bytes == 0 {
println!();
break;
}
// Convert buffer to a string and trim it
let poetry = buffer.lock().unwrap().iter().collect::<String>();
// Skip parsing if there is no poetry
if poetry.is_empty() {
continue;
}
// Set ICANON and ECHO for other programs after the prompt
termios.c_lflag |= ICANON | ECHO | ECHOE;
tcsetattr(STDIN, TCSANOW, &mut termios).unwrap();
// Not at the prompt
*away.lock().unwrap() = true;
// Parse the poem
let poem = Poem::read(poetry.to_string(), env);
let poem = match poem {
Ok(poem) => poem,
Err(e) => {
eprintln!("dwvsh: {}", e.to_string().to_lowercase());
continue;
}
};
// Recite the poem
match poem.recite(env) {
Ok(_) => {}
Err(e) => eprintln!("dwvsh: {}", e.to_string().to_lowercase()),
}
}
}
fn options(env: &mut Environment) {
let args: Vec<String> = env::args().collect();
for arg in args.iter() {
if arg.eq("--version") {
println!(
"dwvsh v{} ({})",
env!("CARGO_PKG_VERSION"),
env!("DWVSH_BUILD")
);
std::process::exit(0);
}
}
match args.last() {
Some(arg) => {
if args.len() > 1 && !arg.starts_with('-') {
let poetry = std::fs::read_to_string(arg)
.expect(format!("dwvsh: can't open input file: {}", arg).as_str());
let poem = Poem::read(poetry, env);
let poem = match poem {
Ok(poem) => poem,
Err(e) => {
eprintln!("dwvsh: {}", e.to_string().to_lowercase());
std::process::exit(1);
}
};
// Recite the poem
match poem.recite(env) {
Ok(_) => {}
Err(e) => eprintln!("dwvsh: {}", e.to_string().to_lowercase()),
}
// Quit
std::process::exit(0);
}
}
None => {}
}
}
/// Shell entry
///
/// Shell setup and entry
fn main() {
// Compose the environment for dwvsh
let mut env = compose::env();
// Set when we are not on the buffer
let mut away = Arc::new(Mutex::new(true));
// Any text in the current buffer
let mut buffer: Arc<Mutex<Vec<char>>> = Arc::new(Mutex::new(Vec::new()));
// Position in the buffer. Subject to change based on input from the user. Typing a character
// increments the position, while backspacing will decrement it. The user may also move it
// manually using the arrow keys to insert or delete at an arbitrary location in the buffer.
let mut pos: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));
// Position in the autocomplete list. This value gets reset if a new autocomplete list is
// generated (for instance, if the user preses '/' to start autocomplete in a new directory).
let mut comp_pos: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));
// Keep track of the length of the last buffer from [crate::buffer::comp].
let mut comp_len: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));
// Keep track of the last key for autocomplete, as we may need to add or sub additionally from
// [comp_pos] before calling [crate::buffer::comp] (i.e. swapping directions (tab vs. shift +
// tab)).
let mut last_key: Arc<Mutex<Key>> = Arc::new(Mutex::new(Key::Ignored));
// Handle signals
unsafe {
let away = Arc::clone(&away);
let buffer = Arc::clone(&buffer);
let pos = Arc::clone(&pos);
let comp_pos = Arc::clone(&comp_pos);
let comp_len = Arc::clone(&comp_len);
let last_key = Arc::clone(&last_key);
signal_hook::low_level::register(signal_hook::consts::SIGINT, move || {
buffer.lock().unwrap().clear();
*pos.lock().unwrap() = 0;
*comp_pos.lock().unwrap() = 0;
*comp_len.lock().unwrap() = 0;
*last_key.lock().unwrap() = Key::Ignored;
if *away.lock().unwrap() {
println!();
} else {
let prompt = match env::var("PS1") {
Ok(val) => val,
Err(_) => String::from("|> "),
};
print!("\n{}", prompt);
io::stdout().flush().unwrap();
}
})
.unwrap();
};
// Parse flags and other arguments
options(&mut env);
// Begin evaluating commands
repl(
&mut away,
&mut buffer,
&mut pos,
&mut comp_pos,
&mut comp_len,
&mut last_key,
&mut env,
);
}
|