use std::io::Write; use std::collections::HashMap; use std::env; use std::process::{Child, Command, Stdio}; use std::fs::File; use std::os::unix::fs::PermissionsExt; use rustyline::error::ReadlineError; use rustyline::{Context, Editor, Helper}; use rustyline::completion::{Completer, Pair}; use rustyline::highlight::Highlighter; use rustyline::hint::Hinter; use rustyline::history::DefaultHistory; use rustyline::validate::Validator; enum BuiltinResult { NotBuiltin, Handled, Exit, } struct ParsedCommand<'a> { command: &'a str, args: Vec<&'a str>, input_file: Option<&'a str>, output_redirect: Option<(&'a str, &'a str)>, error_redirect: Option<(&'a str, &'a str)>, } struct Job { id: usize, child: Child, command: String, } struct ShellHelper { completions: HashMap, } impl Highlighter for ShellHelper {} impl Hinter for ShellHelper { type Hint = String; } impl Validator for ShellHelper {} impl Helper for ShellHelper {} impl Completer for ShellHelper { type Candidate = Pair; fn complete( &self, line: &str, pos: usize, _ctx: &Context<'_>) -> rustyline::Result<(usize, Vec)> { let before_cursor = &line[..pos]; if let Some(space_position) = before_cursor.rfind(' ') { let start = space_position + 1; let prefix = &before_cursor[start..]; if let Some(command) = before_cursor.split_whitespace().next() { if let Some(script) = self.completions.get(command) { let previous_word = before_cursor[..start] .split_whitespace() .last() .unwrap_or(""); let output = match Command::new(script) .arg(command) .arg(prefix) .arg(previous_word) .env("COMP_LINE", line) .env("COMP_POINT", pos.to_string()) .stdin(Stdio::null()) .output() { Ok(output) => output, Err(_) => return Ok((start, Vec::new())), }; let text = String::from_utf8_lossy(&output.stdout); let names: Vec<&str> = text .lines() .filter(|line| !line.is_empty()) .collect(); let single_match = names.len() == 1; let mut candidates = Vec::new(); for name in names { candidates.push(Pair { display: name.to_string(), replacement: if single_match { format!("{name} ") } else { name.to_string() }, }); } return Ok((start, candidates)) } } return complete_filename(prefix, start); } let prefix = before_cursor; if prefix.is_empty() { return Ok((0, Vec::new())); } let mut names = std::collections::BTreeSet::new(); for &builtin in BUILTINS { if builtin.starts_with(prefix) { names.insert(builtin.to_string()); } } if let Some(path) = env::var_os("PATH") { for directory in env::split_paths(&path) { let directory = if directory.as_os_str().is_empty() { std::path::PathBuf::from(".") } else { directory }; let entries = match std::fs::read_dir(directory) { Ok(entries) => entries, Err(_) => continue, }; for entry in entries { let entry = match entry { Ok(name) => name, Err(_) => continue, }; let name = match entry.file_name().into_string() { Ok(name) => name, Err(_) => continue, }; if !name.starts_with(prefix) { continue; } let metadata = match entry.path().metadata() { Ok(metadata) => metadata, Err(_) => continue, }; let is_executable = metadata.permissions().mode() &0o111 != 0; if metadata.is_file() && is_executable { names.insert(name); } } } } let single_match = names.len() == 1; let mut candidates = Vec::new(); for name in names { let replacement = if single_match { format!("{name} ") } else { name.clone() }; candidates.push(Pair { display: name, replacement, }); } Ok((0, candidates)) } } fn complete_filename( prefix: &str, start: usize, ) -> rustyline::Result<(usize, Vec)> { let (directory_prefix, filename_prefix) = match prefix.rfind('/') { Some(position) => prefix.split_at(position + 1), None => ("", prefix), }; let search_directory = if directory_prefix.is_empty() { "." } else { directory_prefix }; let entries = match std::fs::read_dir(search_directory) { Ok(entries) => entries, Err(_) => return Ok((start, Vec::new())), }; let mut names = Vec::new(); for entry in entries { let entry = match entry { Ok(entry) => entry, Err(_) => continue, }; let name = match entry.file_name().into_string() { Ok(name) => name, Err(_) => continue, }; if !name.starts_with(filename_prefix) { continue; } let path = entry.path(); if path.is_dir() { names.push(format!("{directory_prefix}{name}/")); } else if path.is_file() { names.push(format!("{directory_prefix}{name}")); } } names.sort(); let single_match = names.len() == 1; let mut candidates = Vec::new(); for name in names { let replacement = if single_match && !name.ends_with('/') { format!("{name} ") } else { name.clone() }; candidates.push(Pair { display: name, replacement, }); } Ok((start, candidates)) } #[derive(Debug)] enum Token { Word(String), Pipe, Input, Output, Append, ErrorOutput, ErrorAppend, Background, } fn tokenize( line: &str, variables: &HashMap, ) -> Result, String> { let mut tokens = Vec::new(); let mut current = String::new(); let mut in_single_quotes = false; let mut in_double_quotes = false; // Track whether a word exists separately from its contents: // an empty quoted string must still produce an argument. let mut token_started = false; let mut characters = line.chars().peekable(); while let Some(character) = characters.next() { match character { '\'' if !in_double_quotes => { in_single_quotes = !in_single_quotes; token_started = true; } '"' if !in_single_quotes => { in_double_quotes = !in_double_quotes; token_started = true; } '\\' if !in_single_quotes => { if in_double_quotes { match characters.peek().copied() { Some(next) if matches!(next, '"' | '\\' | '$' | '`') => { characters.next(); current.push(next); token_started = true; } Some('\n') => { characters.next(); } _ => { current.push('\\'); token_started = true; } } } else { match characters.next() { Some('\n') => {} Some(next) => { current.push(next); token_started = true; } None => { return Err(String::from( "expected character after backslash" )); } } } } '1' if !in_single_quotes && !in_double_quotes && !token_started && characters.peek() == Some(&'>') => { characters.next(); // continue the first >. if characters.peek() == Some(&'>') { characters.next(); // Consume the second >. tokens.push(Token::Append); } else { tokens.push(Token::Output); } } '2' if !in_single_quotes && !in_double_quotes && !token_started && characters.peek() == Some(&'>') => { characters.next(); if characters.peek() == Some(&'>') { characters.next(); tokens.push(Token::ErrorAppend); } else { tokens.push(Token::ErrorOutput); } } c if c.is_whitespace() && !in_double_quotes && !in_single_quotes => { if token_started { tokens.push(Token::Word(std::mem::take(&mut current))); token_started = false; } } '<' | '>' | '|' | '&' if !in_double_quotes && !in_single_quotes => { if token_started { tokens.push(Token::Word(std::mem::take(&mut current))); token_started = false; } let operator = match character { '<' => Token::Input, '|' => Token::Pipe, '>' => { if characters.peek() == Some(&'>') { characters.next(); Token::Append } else { Token::Output } } '&' => Token::Background, _ => unreachable!(), }; tokens.push(operator); } '$' if !in_single_quotes => { let mut name = String::new(); if characters.peek() == Some(&'{') { characters.next(); // Consume the opening brace. let mut closed = false; while let Some(next) = characters.next() { if next == '}' { closed = true; break; } name.push(next); } if !closed { return Err(String::from("unclosed parameter expansion")); } if !is_valid_identifier(&name) { return Err(format!("${{{name}}}: bad substitution")); } if let Some(value) = variables.get(&name) { current.push_str(value); } } else { // Existing $NAME behavior. if let Some(next) = characters.peek().copied() { if next.is_ascii_alphabetic() || next == '_' { name.push(next); characters.next(); while let Some(next) = characters.peek().copied() { if next.is_ascii_alphanumeric() || next == '_' { name.push(next); characters.next(); } else { break; } } } } if name.is_empty() { current.push('$'); } else if let Some(value) = variables.get(&name) { current.push_str(value); } token_started = true; } } c => { current.push(c); token_started = true; } } } if in_single_quotes { return Err(String::from("unclosed single quote")); } if in_double_quotes { return Err(String::from("unclosed double quote")); } if token_started { tokens.push(Token::Word(current)); } Ok(tokens) } /// Parses one command's tokens into arguments and redirection settings. /// /// Borrows word text from the token slice. Pipeline separators and a /// trailing background operator are handled by the caller. fn parse_token<'a>( tokens: &'a [Token], ) -> Result, String> { let mut tokens = tokens.iter(); let mut error_redirect = None; let command = match tokens.next() { Some(Token::Word(word)) => word.as_str(), _ => return Err(String::from("expected command")), }; let mut args = Vec::new(); let mut input_file = None; let mut output_redirect = None; while let Some(token) = tokens.next() { match token { Token::Word(word) => { args.push(word.as_str()); } Token::Input | Token::Output | Token::Append | Token::ErrorOutput | Token::ErrorAppend => { let operator = match token { Token::Input => "<", Token::Output => ">", Token::Append => ">>", Token::ErrorOutput => "2>", Token::ErrorAppend => "2>>", _ => unreachable!(), }; let filename = match tokens.next() { Some(Token::Word(word)) => word.as_str(), _ => { return Err(format!( "expected filename after {operator}" )); } }; match operator { "<" => input_file = Some(filename), "2>" | "2>>" => { error_redirect = Some((operator, filename)); } _ => { output_redirect = Some((operator, filename)); } } } Token::Pipe => { return Err(String::from("unexpected pipe inside a command")); } Token::Background => { return Err(String::from( "unexpected & inside a command" )); } } } Ok(ParsedCommand { command, args, input_file, output_redirect, error_redirect, }) } fn find_executable(name: &str) -> Option { let path = env::var_os("PATH")?; for directory in env::split_paths(&path) { let candidate = directory.join(name); if let Ok(metadata) = candidate.metadata() { let is_executable = metadata.permissions().mode() & 0o111 != 0; if metadata.is_file() && is_executable { return Some(candidate); } } } None } fn report_jobs(jobs: &mut Vec, include_running: bool) { let job_count = jobs.len(); let mut finished_ids = Vec::new(); for (index, job) in jobs.iter_mut().enumerate() { let marker = if index + 1 == job_count { '+' } else if index + 2 == job_count { '-' } else { ' ' }; let finished = match job.child.try_wait() { Ok(Some(_status)) => true, Ok(None) => false, Err(e) => { eprintln!("jobs: {}: {e}", job.id); continue; } }; if finished || include_running { let status = if finished { "Done" } else { "Running" }; let suffix = if finished { "" } else { " &" }; println!( "[{}]{} {:<24}{}{}", job.id, marker, status, job.command, suffix ); } if finished { finished_ids.push(job.id); } } jobs.retain(|job| !finished_ids.contains(&job.id)); } fn is_valid_identifier(name: &str) -> bool { let mut characters = name.chars(); let valid_start = match characters.next() { Some(c) => c.is_ascii_alphabetic() || c == '_', None => false, }; valid_start && characters.all(|c| c.is_ascii_alphanumeric() || c == '_') } const BUILTINS: &[&str] = &[ "exit", "echo", "type", "pwd", "cd", "complete", "jobs", "history", "declare", ]; fn run_builtin( command: &str, args: &[&str], completions: &mut HashMap, jobs: &mut Vec, command_history: &mut Vec, history_append_from: &mut usize, variables: &mut HashMap, ) -> BuiltinResult { match command { "exit" => BuiltinResult::Exit, "cd" => { let target = match args.first().copied() { None | Some("~") => { match env::var("HOME") { Ok(home) => home, Err(_) => { eprintln!("cd: HOME not set"); return BuiltinResult::Handled; } } } Some(path) => path.to_string(), }; if let Err(e) = env::set_current_dir(&target) { if e.kind() == std::io::ErrorKind::NotFound { eprintln!("cd: {target}: No such file or directory"); } else { eprintln!("cd: {target}: {e}"); } } BuiltinResult::Handled } "type" => { for &name in args { if BUILTINS.contains(&name) { println!("{name} is a shell builtin"); } else { match find_executable(name) { Some(path) => { println!("{name} is {}", path.display()); } None => { println!("{name}: not found"); } } } } BuiltinResult::Handled } "echo" => { println!("{}", args.join(" ")); BuiltinResult::Handled } "pwd" => { match env::current_dir() { Ok(path) => println!("{}", path.display()), Err(e) => eprintln!("pwd: {e}"), } BuiltinResult::Handled } "complete" => { match args.first().copied() { Some("-C") => { if let (Some(&script), Some(&name)) = (args.get(1), args.get(2)) { completions.insert( name.to_string(), script.to_string(), ); } else { eprintln!("complete: expected -C