forked from corrode/rustlab2024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock2.rs
More file actions
244 lines (221 loc) · 6.18 KB
/
Copy pathblock2.rs
File metadata and controls
244 lines (221 loc) · 6.18 KB
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
use std::{
io,
io::IsTerminal,
io::Write,
process::{Command, Output},
};
/// Alias for our `Result` type. You could also use `anyhow` instead.
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() {
loop {
show_prompt();
let line = read_line();
let chains = chains_from_line(line);
for chain in chains {
if let Err(e) = chain.run() {
eprintln!("error: {e}");
}
}
}
}
/// If `stdout` is printed to a terminal, print a prompt.
/// Otherwise, do nothing. This allows to redirect the shell `stdout`
/// to a file or another process, without the prompt being printed.
fn show_prompt() {
let mut stdout = std::io::stdout();
if stdout.is_terminal() {
write!(stdout, "> ").unwrap();
// Flush stdout to ensure the prompt is displayed.
stdout.flush().expect("can't flush stdout");
}
}
fn read_line() -> String {
let mut line = String::new();
io::stdin()
.read_line(&mut line)
.expect("failed to read line from stdin");
line
}
fn chains_from_line(line: String) -> Vec<Chain> {
// For simplicity's sake, this workshop uses the split function.
// This is inefficient because it parses the whole line.
// If you feel adventurous, try to parse the line character by character instead. 🤠
line.split(';')
.filter_map(|s| Parser::new(s).parse())
.collect()
}
// This struct doesn't use lifetimes to keep the code simple.
// You can try to use `&str` instead of `String`
// to avoid unnecessary allocations. 👍
#[derive(PartialEq, Debug)]
struct Cmd {
binary: String,
args: Vec<String>,
}
#[derive(PartialEq, Debug)]
enum Element {
/// `&&`
And,
/// `||`
Or,
/// Command.
Cmd(Cmd),
}
/// Parse `[Element]`s from a string.
struct Parser {
current: usize,
tokens: Vec<String>,
}
impl Parser {
fn new(chain: &str) -> Self {
Self {
tokens: chain.split_whitespace().map(String::from).collect(),
current: 0,
}
}
fn parse(&mut self) -> Option<Chain> {
let mut elements = vec![];
while let Some(e) = self.parse_next() {
elements.push(e);
}
if elements.is_empty() {
None
} else {
Some(Chain { elements })
}
}
fn parse_next(&mut self) -> Option<Element> {
let next = self.tokens.get(self.current).map(|s| s.to_string());
next.and_then(|next| {
self.current += 1;
Element::parse_operator(&next).or_else(|| self.parse_cmd(next).map(Element::Cmd))
})
}
fn parse_cmd(&mut self, binary: String) -> Option<Cmd> {
let mut args: Vec<String> = vec![];
loop {
let next = self.tokens.get(self.current);
match next {
Some(token) if Element::is_operator(token) => {
// found operator, so I already parsed all cmd
break;
}
Some(token) => {
args.push(token.to_string());
}
None => break,
}
self.current += 1;
}
Some(Cmd { binary, args })
}
}
#[derive(PartialEq, Debug)]
struct Chain {
elements: Vec<Element>,
}
impl Chain {
fn run(self) -> Result<()> {
let mut prev_output: Option<Output> = None;
for e in self.elements {
match e {
Element::Cmd(cmd) => {
prev_output = cmd.run();
}
Element::And => {
let status = prev_output.ok_or("no command before &&")?.status;
if !status.success() {
break;
}
prev_output = None;
}
Element::Or => {
let status = prev_output.ok_or("no command before ||")?.status;
if status.success() {
break;
}
prev_output = None;
}
}
}
Ok(())
}
}
impl Element {
fn parse_operator(token: &str) -> Option<Self> {
match token {
"&&" => Some(Self::And),
"||" => Some(Self::Or),
_ => None,
}
}
fn is_operator(token: &str) -> bool {
Self::parse_operator(token).is_some()
}
}
impl Cmd {
fn run(self) -> Option<Output> {
let child = Command::new(self.binary)
.args(self.args)
.spawn()
.map_err(|e| eprintln!("{:?}", e))
.ok()?;
let output = child.wait_with_output().expect("command wasn't running");
Some(output)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_chains(line: &str) -> Vec<Chain> {
chains_from_line(line.to_string())
}
#[test]
fn no_cmd_is_parsed_from_empty_line() {
assert_eq!(parse_chains(""), vec![]);
}
#[test]
fn cmd_with_no_args_is_parsed() {
assert_eq!(
parse_chains("ls"),
vec![Chain {
elements: vec![Element::Cmd(Cmd {
binary: "ls".to_string(),
args: vec![]
}),]
},]
);
}
#[test]
fn cmd_with_args_is_parsed() {
assert_eq!(
parse_chains("ls -l"),
vec![Chain {
elements: vec![Element::Cmd(Cmd {
binary: "ls".to_string(),
args: vec!["-l".to_string()]
})]
}]
);
}
#[test]
fn cmds_are_parsed() {
assert_eq!(
parse_chains("ls; echo hello"),
vec![
Chain {
elements: vec![Element::Cmd(Cmd {
binary: "ls".to_string(),
args: vec![]
}),]
},
Chain {
elements: vec![Element::Cmd(Cmd {
binary: "echo".to_string(),
args: vec!["hello".to_string()]
}),]
},
]
);
}
}