rush-sh 0.8.0

A POSIX sh-compatible shell written in Rust
Documentation
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use std::io::{self, Write};
use std::os::unix::io::FromRawFd;

use crate::parser::ShellCommand;
use crate::state::ShellState;

/// A writer wrapper for output handling
pub struct ColoredWriter<W: Write> {
    inner: W,
}

impl<W: Write> ColoredWriter<W> {
    pub fn new(inner: W) -> Self {
        Self { inner }
    }
}

impl<W: Write> Write for ColoredWriter<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.inner.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

/// A writer that always returns EBADF
pub struct BadFdWriter;

impl Write for BadFdWriter {
    fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
        Err(io::Error::from_raw_os_error(libc::EBADF))
    }

    fn flush(&mut self) -> io::Result<()> {
        Err(io::Error::from_raw_os_error(libc::EBADF))
    }
}

mod builtin_alias;
mod builtin_bg;
mod builtin_break;
mod builtin_cd;
mod builtin_colon;
mod builtin_continue;
mod builtin_declare;
mod builtin_dirs;
mod builtin_env;
mod builtin_exit;
mod builtin_export;
mod builtin_fg;
mod builtin_help;
mod builtin_jobs;
mod builtin_kill;
mod builtin_popd;
mod builtin_pushd;
mod builtin_pwd;
mod builtin_return;
mod builtin_set;
mod builtin_set_color_scheme;
mod builtin_set_colors;
mod builtin_set_condensed;
mod builtin_shift;
mod builtin_source;
mod builtin_test;
mod builtin_times;
mod builtin_trap;
mod builtin_type;
mod builtin_unalias;
mod builtin_unset;
mod builtin_wait;

pub trait Builtin {
    fn name(&self) -> &'static str;
    fn names(&self) -> Vec<&'static str>;
    fn description(&self) -> &'static str;
    fn run(
        &self,
        cmd: &ShellCommand,
        shell_state: &mut ShellState,
        output_writer: &mut dyn Write,
    ) -> i32;
}

/// Provides a vector of all builtin command implementations in registration order.
///
/// Each element is a boxed implementation of `Builtin` representing one builtin command
/// available to the shell.
///
/// # Examples
///
/// ```
/// // Note: get_builtins is a private function
/// // Use is_builtin() or get_builtin_commands() instead for public API
/// use rush_sh::builtins::is_builtin;
/// assert!(is_builtin("cd"));
/// assert!(is_builtin("pwd"));
/// ```
fn get_builtins() -> Vec<Box<dyn Builtin>> {
    vec![
        Box::new(builtin_cd::CdBuiltin),
        Box::new(builtin_pwd::PwdBuiltin),
        Box::new(builtin_env::EnvBuiltin),
        Box::new(builtin_exit::ExitBuiltin),
        Box::new(builtin_help::HelpBuiltin),
        Box::new(builtin_source::SourceBuiltin),
        Box::new(builtin_export::ExportBuiltin),
        Box::new(builtin_unset::UnsetBuiltin),
        Box::new(builtin_pushd::PushdBuiltin),
        Box::new(builtin_popd::PopdBuiltin),
        Box::new(builtin_dirs::DirsBuiltin),
        Box::new(builtin_alias::AliasBuiltin),
        Box::new(builtin_unalias::UnaliasBuiltin),
        Box::new(builtin_test::TestBuiltin),
        Box::new(builtin_set::SetBuiltin),
        Box::new(builtin_set_colors::SetColorsBuiltin),
        Box::new(builtin_set_color_scheme::SetColorSchemeBuiltin),
        Box::new(builtin_set_condensed::SetCondensedBuiltin),
        Box::new(builtin_shift::ShiftBuiltin),
        Box::new(builtin_declare::DeclareBuiltin),
        Box::new(builtin_times::TimesBuiltin),
        Box::new(builtin_trap::TrapBuiltin),
        Box::new(builtin_type::TypeBuiltin),
        Box::new(builtin_return::ReturnBuiltin),
        Box::new(builtin_break::BreakBuiltin),
        Box::new(builtin_continue::ContinueBuiltin),
        Box::new(builtin_colon::ColonBuiltin),
        Box::new(builtin_jobs::JobsBuiltin),
        Box::new(builtin_fg::FgBuiltin),
        Box::new(builtin_bg::BgBuiltin),
        Box::new(builtin_kill::KillBuiltin),
        Box::new(builtin_wait::WaitBuiltin),
    ]
}

pub fn is_builtin(cmd: &str) -> bool {
    get_builtins().iter().any(|b| b.names().contains(&cmd))
}

pub fn get_builtin_commands() -> Vec<String> {
    let builtins = get_builtins();
    let mut commands = Vec::new();
    for b in builtins {
        for &name in &b.names() {
            commands.push(name.to_string());
        }
    }
    commands
}

/// Execute a builtin command, applying redirections and selecting the appropriate output writer.
///
/// This function locates and runs the builtin named by `cmd.args[0]`, applying any redirections
/// from `cmd.redirections` in left-to-right order, expanding filenames using `shell_state`,
/// saving and restoring file descriptors around the builtin invocation, and selecting stdout
/// from the shell's file-descriptor table (or using a sink writer if stdout is closed).
/// If `output_override` is provided, it is used directly as the builtin's output writer and
/// redirections are not applied. Colored error messages are printed according to `shell_state`'s
/// color settings. On success it returns the builtin's exit code; on failure it returns `1`.
///
/// # Examples
///
/// ```no_run
/// use rush_sh::builtins::execute_builtin;
/// use rush_sh::parser::ShellCommand;
/// use rush_sh::ShellState;
/// // Construct a ShellCommand and ShellState appropriately in real code.
/// let cmd = ShellCommand { args: vec!["pwd".into()], redirections: vec![], compound: None };
/// let mut state = ShellState::new();
/// let exit_code = execute_builtin(&cmd, &mut state, None);
/// println!("exit code: {}", exit_code);
/// ```
pub fn execute_builtin(
    cmd: &ShellCommand,
    shell_state: &mut ShellState,
    output_override: Option<Box<dyn Write>>,
) -> i32 {
    // Helper function for colored error messages
    let colors_enabled = shell_state.colors_enabled;
    let error_color = shell_state.color_scheme.error.clone();
    let print_error = move |msg: &str| {
        if colors_enabled {
            eprintln!("{}{}\x1b[0m", error_color, msg);
        } else {
            eprintln!("{}", msg);
        }
    };

    // If output_override is provided, use the old simple path for command substitution
    if let Some(mut output_writer) = output_override {
        let builtins = get_builtins();
        if let Some(builtin) = builtins
            .into_iter()
            .find(|b| b.names().contains(&cmd.args[0].as_str()))
        {
            return builtin.run(cmd, shell_state, &mut *output_writer);
        } else {
            return 1;
        }
    }

    // Handle redirections using FileDescriptorTable for proper POSIX compliance
    use crate::parser::Redirection;

    // Clone redirections to avoid borrow checker issues
    let redirections = cmd.redirections.clone();

    // First, expand all filenames in redirections (needs mutable borrow of shell_state)
    // Collect all filenames that need expansion
    let mut files_to_expand: Vec<String> = Vec::new();
    for redir in &redirections {
        match redir {
            Redirection::Input(file)
            | Redirection::Output(file)
            | Redirection::OutputClobber(file)
            | Redirection::Append(file)
            | Redirection::FdInput(_, file)
            | Redirection::FdOutput(_, file)
            | Redirection::FdOutputClobber(_, file)
            | Redirection::FdAppend(_, file)
            | Redirection::FdInputOutput(_, file) => {
                files_to_expand.push(file.clone());
            }
            _ => {
                files_to_expand.push(String::new()); // Placeholder for non-file redirections
            }
        }
    }

    // Now expand all filenames (single mutable borrow)
    let mut expanded_files: Vec<String> = Vec::new();
    for f in &files_to_expand {
        if f.is_empty() {
            expanded_files.push(String::new());
        } else {
            expanded_files.push(crate::executor::expand_variables_in_string(f, shell_state));
        }
    }

    // Pair redirections with their expanded filenames
    let mut expanded_redirections: Vec<(Redirection, Option<String>)> = Vec::new();
    for (i, redir) in redirections.iter().enumerate() {
        let expanded_file = if expanded_files[i].is_empty() {
            None
        } else {
            Some(expanded_files[i].clone())
        };
        expanded_redirections.push((redir.clone(), expanded_file));
    }

    // Save all current file descriptors before applying redirections
    if let Err(e) = shell_state.fd_table.borrow_mut().save_all_fds() {
        print_error(&format!("Failed to save file descriptors: {}", e));
        return 1;
    }

    // Apply all redirections in left-to-right order (POSIX requirement)
    for (redir, expanded_file) in &expanded_redirections {
        let result = match redir {
            Redirection::Input(_) => {
                let file = expanded_file.as_ref().unwrap();
                shell_state.fd_table.borrow_mut().open_fd(
                    0, file, true,  // read
                    false, // write
                    false, // append
                    false, // truncate
                    false, // create_new
                )
            }
            Redirection::Output(_) | Redirection::OutputClobber(_) => {
                let file = expanded_file.as_ref().unwrap();
                shell_state.fd_table.borrow_mut().open_fd(
                    1, file, false, // read
                    true,  // write
                    false, // append
                    true,  // truncate
                    false, // create_new
                )
            }
            Redirection::Append(_) => {
                let file = expanded_file.as_ref().unwrap();
                shell_state.fd_table.borrow_mut().open_fd(
                    1, file, false, // read
                    true,  // write
                    true,  // append
                    false, // truncate
                    false, // create_new
                )
            }
            Redirection::FdInput(fd, _) => {
                let file = expanded_file.as_ref().unwrap();
                shell_state.fd_table.borrow_mut().open_fd(
                    *fd, file, true,  // read
                    false, // write
                    false, // append
                    false, // truncate
                    false, // create_new
                )
            }
            Redirection::FdOutput(fd, _) | Redirection::FdOutputClobber(fd, _) => {
                let file = expanded_file.as_ref().unwrap();
                shell_state.fd_table.borrow_mut().open_fd(
                    *fd, file, false, // read
                    true,  // write
                    false, // append
                    true,  // truncate
                    false, // create_new
                )
            }
            Redirection::FdAppend(fd, _) => {
                let file = expanded_file.as_ref().unwrap();
                shell_state.fd_table.borrow_mut().open_fd(
                    *fd, file, false, // read
                    true,  // write
                    true,  // append
                    false, // truncate
                    false, // create_new
                )
            }
            Redirection::FdDuplicate(target_fd, source_fd) => shell_state
                .fd_table
                .borrow_mut()
                .duplicate_fd(*source_fd, *target_fd),
            Redirection::FdClose(fd) => shell_state.fd_table.borrow_mut().close_fd(*fd),
            Redirection::FdInputOutput(fd, _) => {
                let file = expanded_file.as_ref().unwrap();
                shell_state.fd_table.borrow_mut().open_fd(
                    *fd, file, true,  // read
                    true,  // write
                    false, // append
                    false, // truncate
                    false, // create_new
                )
            }
            // Here-documents and here-strings are handled differently for builtins
            // They don't modify the fd table directly
            Redirection::HereDoc(_, _) | Redirection::HereString(_) => Ok(()),
        };

        if let Err(e) = result {
            print_error(&format!("Redirection error: {}", e));
            // Restore file descriptors before returning
            let _ = shell_state.fd_table.borrow_mut().restore_all_fds();
            return 1;
        }
    }

    // Get output writer - try to get FD 1 from fd_table to respect redirections
    let mut output_writer: Box<dyn Write> = {
        let raw_fd = shell_state.fd_table.borrow().get_raw_fd(1);
        match raw_fd {
            Some(fd) => {
                // Duplicate the fd so we can take ownership in a File
                // (using unsafe libc call similar to how state.rs handles it)
                let dup_fd = unsafe { libc::dup(fd) };
                if dup_fd >= 0 {
                    let file = unsafe { std::fs::File::from_raw_fd(dup_fd) };
                    Box::new(ColoredWriter::new(file))
                } else {
                    // Duplication failed
                    let err = io::Error::last_os_error();
                    if err.raw_os_error() == Some(libc::EBADF) {
                        // EBADF means the FD is closed/invalid (e.g. parent closed stdout).
                        // In this case, we just run without output.
                        Box::new(BadFdWriter)
                    } else {
                        // Other errors (e.g. EMFILE) are fatal
                        print_error(&format!("Failed to duplicate stdout: {}", err));
                        let _ = shell_state.fd_table.borrow_mut().restore_all_fds();
                        return 1;
                    }
                }
            }
            None => {
                // FD 1 is closed. Do NOT fall back to stdout.
                Box::new(BadFdWriter)
            }
        }
    };

    // Execute the builtin command
    let builtins = get_builtins();
    let exit_code = if let Some(builtin) = builtins
        .into_iter()
        .find(|b| b.names().contains(&cmd.args[0].as_str()))
    {
        builtin.run(cmd, shell_state, &mut *output_writer)
    } else {
        1
    };

    // Restore all file descriptors after builtin execution
    if let Err(e) = shell_state.fd_table.borrow_mut().restore_all_fds() {
        print_error(&format!("Failed to restore file descriptors: {}", e));
        return 1;
    }

    exit_code
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_builtin() {
        assert!(is_builtin("cd"));
        assert!(is_builtin("pwd"));
        assert!(is_builtin("env"));
        assert!(is_builtin("exit"));
        assert!(is_builtin("help"));
        assert!(is_builtin("alias"));
        assert!(is_builtin("unalias"));
        assert!(is_builtin("test"));
        assert!(is_builtin("["));
        assert!(is_builtin("."));
        assert!(!is_builtin("ls"));
        assert!(!is_builtin("grep"));
        assert!(!is_builtin("echo"));
    }

    #[test]
    fn test_execute_builtin_unknown() {
        let cmd = ShellCommand {
            args: vec!["unknown".to_string()],
            redirections: Vec::new(),
            compound: None,
        };
        let mut shell_state = ShellState::new();
        let exit_code = execute_builtin(&cmd, &mut shell_state, None);
        assert_eq!(exit_code, 1);
    }

    #[test]
    fn test_get_builtin_commands() {
        let commands = get_builtin_commands();
        assert!(commands.contains(&"cd".to_string()));
        assert!(commands.contains(&"pwd".to_string()));
        assert!(commands.contains(&"env".to_string()));
        assert!(commands.contains(&"exit".to_string()));
        assert!(commands.contains(&"help".to_string()));
        assert!(commands.contains(&"source".to_string()));
        assert!(commands.contains(&"export".to_string()));
        assert!(commands.contains(&"unset".to_string()));
        assert!(commands.contains(&"pushd".to_string()));
        assert!(commands.contains(&"popd".to_string()));
        assert!(commands.contains(&"dirs".to_string()));
        assert!(commands.contains(&"alias".to_string()));
        assert!(commands.contains(&"unalias".to_string()));
        assert!(commands.contains(&"test".to_string()));
        assert!(commands.contains(&"[".to_string()));
        assert!(commands.contains(&".".to_string()));
        assert!(commands.contains(&"set_colors".to_string()));
        assert!(commands.contains(&"set_color_scheme".to_string()));
        assert!(commands.contains(&"set_condensed".to_string()));
        assert!(commands.contains(&"return".to_string()));
        assert!(commands.contains(&"break".to_string()));
        assert!(commands.contains(&"continue".to_string()));
        assert!(commands.contains(&"set".to_string()));
        assert!(commands.contains(&":".to_string()));
        assert!(commands.contains(&"times".to_string()));
        assert!(commands.contains(&"jobs".to_string()));
        assert!(commands.contains(&"fg".to_string()));
        assert!(commands.contains(&"bg".to_string()));
        assert!(commands.contains(&"kill".to_string()));
        assert!(commands.contains(&"wait".to_string()));
        assert_eq!(commands.len(), 34);
    }
}