use engine::{Input, Output, Terminal, VirtualPath};
use os::{Credentials, ExitStatus, UnixOs};
use crate::core::{ShellCore, ShellDialect};
pub struct Zsh<'os> {
core: ShellCore<'os>,
}
impl<'os> Zsh<'os> {
pub fn new(os: &'os UnixOs, credentials: Credentials) -> Result<Self, os::OsError> {
let mut core = ShellCore::new(os, credentials, zsh_dialect())?;
core.install_shell_bindings();
core.source_startup_files();
Ok(Self { core })
}
}
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,
)
}
}
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: "",
}
}
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"
)
}
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 {
"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(),
"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)
}
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
}
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
}
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
}
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
}
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 {
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"));
}
}