vce-shell 0.1.1

VCE Shell layer: command language, builtins, execution coordination
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! The Zsh shell implementation.
//!
//! Zsh is a peer of Bash, not a flavor of it: it owns its builtin table
//! (`where`, `whence`, `which`, `print`, and zsh-flavored `echo`, `alias`,
//! `export`, `type`), its dialect (messages and prompt), and its grammar.
//! The grammar today is the shared sh-family grammar ([`brush_parser`]),
//! which is the honest state of affairs for a first zsh: zsh syntax was
//! never formally specified and no maintained zsh grammar crate exists, so
//! zsh-specific constructs (glob qualifiers, extended globbing,
//! `=command` expansion, prompt escapes) are future work owned by this
//! implementation on top of the shared [`ShellCore`](crate::core::ShellCore).
//!
//! What already differs from Bash, verified against a real zsh:
//! - `echo` interprets backslash escapes by default (BSD behavior);
//! - `alias` lists as `name='expansion'` without a prefix;
//! - `export` lists as `export NAME=value`;
//! - `type` says `name is an alias for ...`;
//! - the `where`/`whence`/`which`/`print` builtins;
//! - the prompt (`user@host:~/path% ` with the home directory abbreviated
//!   to `~`).

use engine::{Input, Output, Terminal, VirtualPath};
use os::{Credentials, ExitStatus, UnixOs};

use crate::core::{ShellCore, ShellDialect};

/// The Zsh-flavored shell.
pub struct Zsh<'os> {
    /// The shared execution core in the Zsh dialect.
    core: ShellCore<'os>,
}

impl<'os> Zsh<'os> {
    /// Creates a Zsh shell for a session.
    pub fn new(os: &'os UnixOs, credentials: Credentials) -> Result<Self, os::OsError> {
        let mut core = ShellCore::new(os, credentials, zsh_dialect())?;
        // Scripts run through this shell, not a separate interpreter.
        core.install_shell_bindings();
        // Startup files define the session's aliases and functions.
        core.source_startup_files();
        Ok(Self { core })
    }
}

/// The behavior of `/bin/zsh`: the Zsh dialect as a program
/// (`#!/bin/zsh` is interpreted by Zsh). Scripts and `zsh -c` invocations
/// run through the same implementation as interactive commands.
pub struct ZshInterpreter;

impl os::runtime::Command for ZshInterpreter {
    fn name(&self) -> &'static str {
        "zsh"
    }

    fn execute(
        &self,
        context: &mut os::runtime::CommandContext<'_, '_, '_, '_>,
    ) -> Result<os::runtime::ExitStatus, os::OsError> {
        crate::core::run_interpreter_invocation(
            context.os,
            context.credentials.clone(),
            zsh_dialect(),
            context.cwd,
            context.argv,
            &mut *context.stdin,
            &mut *context.stdout,
            &mut *context.stderr,
        )
    }
}

/// The Zsh dialect: identity, messages, and the builtin table.
fn zsh_dialect() -> ShellDialect {
    ShellDialect {
        name: "zsh",
        command_not_found: |name| format!("zsh: command not found: {name}\n"),
        run_builtin: zsh_run_builtin,
        system_rc: "/etc/zshrc",
        user_rc: ".zshrc",
        echo_escapes_default: true,
        export_prefix: "export ",
        alias_prefix: "",
    }
}

/// Whether a name is a Zsh builtin.
fn zsh_is_builtin(name: &str) -> bool {
    matches!(
        name,
        "cd" | "pwd"
            | "export"
            | "history"
            | "alias"
            | "unalias"
            | "jobs"
            | "fg"
            | "bg"
            | "wait"
            | "hash"
            | "echo"
            | "print"
            | "clear"
            | ":"
            | "dirs"
            | "pushd"
            | "popd"
            | "unset"
            | "source"
            | "."
            | "whence"
            | "which"
            | "where"
            | "type"
            | "exit"
    )
}

/// Dispatches a Zsh builtin (function → builtin → external).
fn zsh_run_builtin(
    core: &mut ShellCore,
    name: &str,
    argv: &[String],
    stdin: &mut dyn Input,
    stdout: &mut dyn Output,
    stderr: &mut dyn Output,
) -> Option<ExitStatus> {
    let status = match name {
        // Shared mechanisms, verified identical in Bash and Zsh.
        "cd" => core.cd_to(argv, stdout, stderr),
        "pwd" => core.pwd_of(stdout),
        "jobs" => core.list_jobs(stdout),
        "fg" => core.foreground_job(argv, stdout, stderr),
        "bg" => core.background_job(argv, stdout, stderr),
        "wait" => core.wait_for_jobs(argv, stderr),
        "hash" => core.hash_table(argv, stdout, stderr),
        "dirs" => core.print_dirs(stdout),
        "pushd" => core.push_directory(argv, stdout, stderr),
        "popd" => core.pop_directory(argv, stdout, stderr),
        "unset" => core.unset_names(argv, stderr),
        "source" | "." => core.source_file(argv, stdin, stdout, stderr),
        "clear" => core.clear_screen(stdout),
        ":" => core.null_command(),
        // Zsh-owned semantics on shared mechanisms (the dialect carries the
        // phrasing).
        "echo" => core.builtin_echo(argv, stdout),
        "print" => zsh_print(argv, stdout),
        "export" => core.builtin_export(argv, stdout, stderr),
        "history" => core.builtin_history(stdout),
        "alias" => core.builtin_alias(argv, stdout, stderr),
        "unalias" => core.builtin_unalias(argv, stderr),
        "whence" => zsh_whence(core, argv, stdout, stderr),
        "which" => zsh_which(core, argv, stdout, stderr),
        "where" => zsh_where(core, argv, stdout, stderr),
        "type" => zsh_type(core, argv, stdout, stderr),
        "exit" => core.request_exit(argv.get(1).map(String::as_str)),
        _ => return None,
    };
    Some(status)
}

/// The Zsh `print` builtin: like `echo`, with `-n` (no newline) and `-r`
/// (no escape processing).
fn zsh_print(argv: &[String], stdout: &mut dyn Output) -> ExitStatus {
    let mut output = String::new();
    let mut no_newline = false;
    let mut start = 1;
    while let Some(argument) = argv.get(start) {
        if argument == "-n" && !no_newline {
            no_newline = true;
            start += 1;
        } else if argument == "-r" {
            start += 1;
        } else {
            break;
        }
    }
    for (index, argument) in argv.iter().skip(start).enumerate() {
        if index > 0 {
            output.push(' ');
        }
        output.push_str(argument);
    }
    if !no_newline {
        output.push('\n');
    }
    let _ = stdout.write(output.as_bytes());
    ExitStatus::SUCCESS
}

/// The Zsh `whence` builtin: prints how the name resolves — the alias
/// expansion, the name for a builtin or function, or the first path.
fn zsh_whence(
    core: &mut ShellCore,
    argv: &[String],
    stdout: &mut dyn Output,
    stderr: &mut dyn Output,
) -> ExitStatus {
    let mut exit_status = ExitStatus::SUCCESS;
    for name in argv.iter().skip(1) {
        let resolution = core.resolve_name(name, zsh_is_builtin);
        if let Some(alias) = resolution.alias {
            let _ = stdout.write(format!("{alias}\n").as_bytes());
            continue;
        }
        if resolution.function || resolution.builtin || !resolution.paths.is_empty() {
            let _ = stdout.write(format!("{name}\n").as_bytes());
            continue;
        }
        let _ = stderr;
        exit_status = ExitStatus::FAILURE;
    }
    exit_status
}

/// The Zsh `which` builtin: reports the resolution like zsh — an alias as
/// `name: aliased to <expansion>`, a builtin as `name: shell built-in
/// command`, and the first filesystem hit from `PATH`.
fn zsh_which(
    core: &mut ShellCore,
    argv: &[String],
    stdout: &mut dyn Output,
    stderr: &mut dyn Output,
) -> ExitStatus {
    let mut exit_status = ExitStatus::SUCCESS;
    for name in argv.iter().skip(1) {
        let resolution = core.resolve_name(name, zsh_is_builtin);
        if let Some(alias) = resolution.alias {
            let _ = stdout.write(format!("{name}: aliased to {alias}\n").as_bytes());
            continue;
        }
        if resolution.function {
            let _ = stdout.write(format!("{name}: shell function\n").as_bytes());
            continue;
        }
        if resolution.builtin {
            let _ = stdout.write(format!("{name}: shell built-in command\n").as_bytes());
            continue;
        }
        if let Some(path) = resolution.paths.into_iter().next() {
            let _ = stdout.write(format!("{path}\n").as_bytes());
        } else {
            let _ = stderr.write(format!("{name} not found\n").as_bytes());
            exit_status = ExitStatus::FAILURE;
        }
    }
    exit_status
}

/// The Zsh `where` builtin: prints every location of a command — an alias
/// as `name: aliased to <expansion>`, the builtin as `name: shell built-in
/// command`, and each filesystem hit from `PATH`, in order.
fn zsh_where(
    core: &mut ShellCore,
    argv: &[String],
    stdout: &mut dyn Output,
    stderr: &mut dyn Output,
) -> ExitStatus {
    let mut exit_status = ExitStatus::SUCCESS;
    for name in argv.iter().skip(1) {
        let resolution = core.resolve_name(name, zsh_is_builtin);
        let mut found = false;
        if let Some(alias) = &resolution.alias {
            let _ = stdout.write(format!("{name}: aliased to {alias}\n").as_bytes());
            found = true;
        }
        if resolution.function {
            let _ = stdout.write(format!("{name}: shell function\n").as_bytes());
            found = true;
        }
        if resolution.builtin {
            let _ = stdout.write(format!("{name}: shell built-in command\n").as_bytes());
            found = true;
        }
        for path in resolution.paths {
            let _ = stdout.write(format!("{path}\n").as_bytes());
            found = true;
        }
        if !found {
            let _ = stderr.write(format!("{name} not found\n").as_bytes());
            exit_status = ExitStatus::FAILURE;
        }
    }
    exit_status
}

/// The Zsh `type` builtin: reports how a name would be resolved, in zsh's
/// phrasing (`name is an alias for ...`).
fn zsh_type(
    core: &mut ShellCore,
    argv: &[String],
    stdout: &mut dyn Output,
    stderr: &mut dyn Output,
) -> ExitStatus {
    let mut exit_status = ExitStatus::SUCCESS;
    for name in argv.iter().skip(1) {
        let resolution = core.resolve_name(name, zsh_is_builtin);
        if let Some(alias) = resolution.alias {
            let _ = stdout.write(format!("{name} is an alias for {alias}\n").as_bytes());
            continue;
        }
        if resolution.function {
            let _ = stdout.write(format!("{name} is a shell function\n").as_bytes());
            continue;
        }
        if resolution.builtin {
            let _ = stdout.write(format!("{name} is a shell builtin\n").as_bytes());
            continue;
        }
        if let Some(path) = resolution.paths.into_iter().next() {
            let _ = stdout.write(format!("{name} is {path}\n").as_bytes());
        } else {
            let _ = stderr.write(format!("{name} not found\n").as_bytes());
            exit_status = ExitStatus::FAILURE;
        }
    }
    exit_status
}

impl<'os> crate::Shell for Zsh<'os> {
    fn name(&self) -> &'static str {
        "zsh"
    }

    fn actor(&self) -> engine::ActorId {
        self.core.credentials().actor()
    }

    fn environment(&self) -> &os::Environment {
        self.core.environment()
    }

    fn engine(&self) -> &engine::Engine {
        self.core.os().engine()
    }

    fn boot_time(&self) -> engine::Timestamp {
        self.core.os().boot_time()
    }

    fn hostname(&self) -> String {
        crate::core::hostname_from_etc(self.core.os())
    }

    fn cwd(&self) -> &VirtualPath {
        self.core.cwd()
    }

    fn banner(&self) -> Option<String> {
        Some(format!(
            "Last login: {} on ttys000\n",
            crate::core::format_login_line(self.core.os().boot_time())
        ))
    }

    fn prompt(&self, hostname: &str) -> String {
        // Zsh abbreviates the home directory to `~` in the prompt.
        let home = self.core.credentials().user().home();
        let cwd = self.core.cwd();
        let display = if cwd.to_string() == home {
            "~".to_owned()
        } else if let Some(rest) = cwd.to_string().strip_prefix(&format!("{home}/")) {
            format!("~/{rest}")
        } else {
            cwd.to_string()
        };
        format!(
            "{}@{}:{}{} ",
            self.core.credentials().username(),
            hostname,
            display,
            '%'
        )
    }

    fn set_terminal_size(&mut self, rows: u16, cols: u16) {
        self.core.set_terminal_size(rows, cols);
    }

    fn execute(
        &mut self,
        line: &str,
        stdin: &mut dyn Input,
        stdout: &mut dyn Output,
        stderr: &mut dyn Output,
    ) -> ExitStatus {
        self.core.execute(line, stdin, stdout, stderr)
    }

    fn execute_with_terminal(
        &mut self,
        line: &str,
        stdin: &mut dyn Input,
        stdout: &mut dyn Output,
        stderr: &mut dyn Output,
        terminal: Option<&mut dyn Terminal>,
    ) -> ExitStatus {
        self.core
            .execute_with_terminal(line, stdin, stdout, stderr, terminal)
    }

    fn take_exit_status(&mut self) -> Option<ExitStatus> {
        self.core.take_exit_request()
    }

    fn history(&self) -> &[String] {
        self.core.history()
    }

    fn record_history(&mut self, line: &str) {
        self.core.record_history(line);
    }

    fn needs_continuation(&self, input: &str) -> bool {
        crate::core::needs_continuation(input)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Shell;
    use engine::{BytesInput, BytesOutput, Timestamp};
    use os::HostIdentity;
    use os::linux::Linux;

    fn test_shell() -> Zsh<'static> {
        let linux = Box::leak(Box::new(
            Linux::with_identity(
                &HostIdentity::new("demo", "demo-host"),
                Timestamp::from_nanos(1_000_000),
            )
            .unwrap(),
        ));
        let credentials = linux
            .unix()
            .users()
            .authenticate("demo", "demo", linux.unix().groups())
            .unwrap();
        Zsh::new(linux.unix(), credentials).unwrap()
    }

    fn run(shell: &mut Zsh<'static>, line: &str) -> (ExitStatus, Vec<u8>, Vec<u8>) {
        let mut stdin = BytesInput::new(b"");
        let mut stdout = BytesOutput::new();
        let mut stderr = BytesOutput::new();
        let status = shell.execute(line, &mut stdin, &mut stdout, &mut stderr);
        (status, stdout.into_bytes(), stderr.into_bytes())
    }

    #[test]
    fn zsh_prompt_abbreviates_home() {
        let mut shell = test_shell();
        assert_eq!(shell.prompt("demo-host"), "demo@demo-host:~% ");
        run(&mut shell, "cd /etc");
        assert_eq!(shell.prompt("demo-host"), "demo@demo-host:/etc% ");
    }

    #[test]
    fn zsh_echo_interpret_escapes_by_default() {
        let mut shell = test_shell();
        let (_, out, _) = run(&mut shell, "echo 'a\\tb'");
        assert_eq!(out, b"a\tb\n");
        let (_, out, _) = run(&mut shell, "echo -E 'a\\tb'");
        assert_eq!(out, b"a\\tb\n");
    }

    #[test]
    fn zsh_print_builtin() {
        let mut shell = test_shell();
        let (_, out, _) = run(&mut shell, "print hello world");
        assert_eq!(out, b"hello world\n");
        let (_, out, _) = run(&mut shell, "print -n no-newline");
        assert_eq!(out, b"no-newline");
    }

    #[test]
    fn zsh_alias_lists_without_prefix() {
        let mut shell = test_shell();
        run(&mut shell, "alias ll='ls -l'");
        let (_, out, _) = run(&mut shell, "alias");
        assert_eq!(out, b"ll='ls -l'\n");
    }

    #[test]
    fn zsh_where_reports_all_locations() {
        let mut shell = test_shell();
        run(&mut shell, "alias ll='ls -l'");
        let (status, out, _) = run(&mut shell, "where ll");
        assert_eq!(status, ExitStatus::SUCCESS);
        assert_eq!(out, b"ll: aliased to ls -l\n");
        let (_, out, _) = run(&mut shell, "where echo");
        assert_eq!(out, b"echo: shell built-in command\n/usr/bin/echo\n");
        let (status, _, err) = run(&mut shell, "where foobar");
        assert_eq!(status, ExitStatus::FAILURE);
        assert_eq!(err, b"foobar not found\n");
    }

    #[test]
    fn zsh_which_reports_like_zsh() {
        let mut shell = test_shell();
        let (_, out, _) = run(&mut shell, "which cd");
        assert_eq!(out, b"cd: shell built-in command\n");
        let (_, out, _) = run(&mut shell, "which ls");
        assert_eq!(out, b"/usr/bin/ls\n");
    }

    #[test]
    fn zsh_whence_prints_plain_resolution() {
        let mut shell = test_shell();
        run(&mut shell, "alias ll='ls -l'");
        let (_, out, _) = run(&mut shell, "whence ll");
        assert_eq!(out, b"ls -l\n");
        let (_, out, _) = run(&mut shell, "whence cd");
        assert_eq!(out, b"cd\n");
    }

    #[test]
    fn zsh_type_uses_zsh_phrasing() {
        let mut shell = test_shell();
        run(&mut shell, "alias ll='ls -l'");
        let (_, out, _) = run(&mut shell, "type ll");
        assert_eq!(out, b"ll is an alias for ls -l\n");
        let (_, out, _) = run(&mut shell, "type cd");
        assert_eq!(out, b"cd is a shell builtin\n");
    }

    #[test]
    fn zsh_export_lists_as_export() {
        let mut shell = test_shell();
        run(&mut shell, "export FOO=bar");
        let (_, out, _) = run(&mut shell, "export");
        let text = String::from_utf8(out).unwrap();
        assert!(text.lines().any(|line| line == "export FOO=bar"));
    }
}