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
|
mod alias;
mod cd;
mod exit;
mod export;
mod source;
mod which;
use crate::compose::Environment;
use std::io;
use std::process::{Output, Stdio};
/// A static list of all the built-in commands
static INDEX: [&str; 8] = [
"alias", "cd", "exit", "export", "source", "unalias", "unset", "which",
];
/// Lookup the index of a built-in command
///
/// Looks up the index of a built-in command in [INDEX], accounting for
/// aliases.
///
/// # Aliases
/// * quit -> exit
/// * set -> export
pub fn lookup(verb: &str) -> Option<usize> {
let verb = match verb {
"quit" => "exit", // Alias 'quit' to 'exit'
"set" => "export", // Alias 'set' to 'export'
_ => verb,
};
INDEX.iter().position(|v| v.to_string() == verb)
}
/// Dummy interface for STDIN
///
/// A helper struct for dealing with STDIN in built-in commands.
/// Currently, there are no built-in commands that actually use this,
/// but it needs to exist for the `incant!()` macro to function
/// properly. See [Anthology] for more details.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct AnthologyStdin {
/// Bytes
data: Vec<u8>,
}
impl AnthologyStdin {
/// Create a new instance of AnthologyStdin
pub fn new() -> Self {
AnthologyStdin { data: Vec::new() }
}
/// Return a mutable version of self
pub fn as_mut(&mut self) -> Option<&mut Self> {
Some(self)
}
/// Write bytes specified by data into STDIN
pub fn write_all(&mut self, data: &[u8]) -> Result<(), io::Error> {
self.data.append(&mut data.to_vec());
Ok(())
}
}
/// Interface for built-in commands
///
/// The implementation of [Anthology] is designed to mimic
/// [std::process::Command], in order to avoid code redundancy. The
/// internal structure of [Anthology] is fairly irrelevant to this
/// `impl`, with the exception of the `stdin`, and `output` fields. In
/// addition to the documentation below, it may also be helpful to read
/// through the `incant!()` macro, so see how processes are actually
/// forked.
#[derive(Debug, Clone)]
pub struct Anthology {
/// Name of the built-in command (see [lookup()] and/or [INDEX])
verb: String,
/// Arguments to pass to the built-in command
clause: Option<Vec<String>>,
/// Indicates STDIN should be read in (but no built-ins use STDIN)
uin: bool,
/// Indicates STDOUT should be captured
uout: bool,
/// Indicates STDERR should be captured
uerr: bool,
/// Compatability with [std::process::Command]
pub stdin: AnthologyStdin,
/// Stores the built-in output (return code, STDOUT, STDERR), also
/// needed for compatability with [std::process::Command]
output: Option<Output>,
}
impl Anthology {
/// Create a new instance of a built-in command
///
/// Sets up a built-in command with default values.
///
/// # Examples
/// ```
/// let mut command = Anthology::new("alias");
/// ```
pub fn new(i: usize) -> Self {
Anthology {
verb: INDEX[i].to_string(),
clause: None,
uin: false,
uout: false,
uerr: false,
stdin: AnthologyStdin::new(),
output: None,
}
}
/// Setup arguments to the built-in command
///
/// Sets the 'clause' field of the [Anthology] struct, which are arguments
/// to be passed to the built-in command.
pub fn args(&mut self, clause: Vec<String>) {
self.clause = match clause.is_empty() {
true => None,
false => Some(clause.clone()),
};
}
/// Read to STDIN
///
/// None of the built-in commands will currently read from STDIN for any
/// reason, so this is just a dummy function.
pub fn stdin(&mut self, _stdin: Stdio) {
self.uin = true;
}
/// Capture STDOUT
pub fn stdout(&mut self, _stdout: Stdio) {
self.uout = true;
}
/// Capture STDERR
pub fn stderr(&mut self, _stderr: Stdio) {
self.uerr = true;
}
/// Set the process group
///
/// This is only needed if a process is forked into the background.
/// Technically this is possible with the built-ins, but not really
/// useful, so this function simply does nothing. As a result,
/// built-ins that get forked into the background always return
/// immediately.
pub fn process_group(&mut self, _id: usize) {}
/// Get the process id
///
/// This is only needed if a process is forked into the background.
/// Will always return `0` for built-in commands. Also see
/// [process_group()][Anthology::process_group].
pub fn id(&mut self) -> i32 {
0
}
/// Run a built-in command
///
/// Runs a built-in command based on the `verb`, appropriately
/// passing arguments and [Environment] fields as necessary.
pub fn spawn(&mut self, env: &mut Environment) -> Result<Self, io::Error> {
// Incant the built-in and set the output
self.output = Some(match self.verb.as_str() {
"alias" => alias::incant(&self.clause, self.uout, &mut env.aliases),
"cd" => cd::incant(&self.clause, self.uerr),
"exit" => exit::incant(),
"export" => export::incant(&self.clause, self.uout),
"source" => source::incant(&self.clause, self.uout, self.uerr, env),
"unalias" => alias::unincant(&self.clause, self.uerr, &mut env.aliases),
"unset" => export::unincant(&self.clause, self.uerr),
"which" => which::incant(&self.clause, self.uout, self.uerr, env),
_ => unreachable!(),
});
Ok(self.clone())
}
/// Get the output of a built-in
///
/// Return the [Output] of a built-in command. This function needed
/// for compatibility with [std::process::Command].
pub fn wait_with_output(&self) -> Result<Output, io::Error> {
match &self.output {
Some(output) => Ok(output.clone()),
None => Err(io::Error::new(io::ErrorKind::Other, "not spawned")),
}
}
}
|