Something went wrong. Try again.
I buiit my own shell in Rust! I plan to refactor this code by creating a second version with a gui if possible!
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278use 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<String, String>,}
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<Pair>)> { 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<Pair>)> { 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<String, String>,) -> Result<Vec<Token>, 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<ParsedCommand<'a>, 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<std::path::PathBuf> { 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<Job>, 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<String, String>, jobs: &mut Vec<Job>, command_history: &mut Vec<String>, history_append_from: &mut usize, variables: &mut HashMap<String, String>,) -> 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 <script> <command>"); } } Some("-p") => { for &name in &args[1..] { match completions.get(name) { Some(script) => { println!("complete -C '{script}' {name}"); } None => { eprintln!("complete: {name}: no completion specification"); } } } } Some("-r") => { for &name in &args[1..] { completions.remove(name); } } _ => {} }
BuiltinResult::Handled } "jobs" => { report_jobs(jobs, true); BuiltinResult::Handled } "history" => { if args.first().copied() == Some("-r") { let Some(&path) = args.get(1) else { eprintln!("history: -r: expected a file path"); return BuiltinResult::Handled; };
match std::fs::read_to_string(path) { Ok(contents) => { for entry in contents.lines() { if !entry.is_empty() { command_history.push(entry.to_string()); } } } Err(e) => { eprintln!("{path}: {e}"); } } return BuiltinResult::Handled; }
if args.first().copied() == Some("-w") { let Some(&path) = args.get(1) else { eprintln!("history: -w: expected a file path"); return BuiltinResult::Handled; };
let mut contents = command_history.join("\n");
if !command_history.is_empty() { contents.push('\n'); }
if let Err(e) = std::fs::write(path, contents) { eprintln!("history: {path}: {e}"); }
return BuiltinResult::Handled; } if args.first().copied() == Some("-a") { let Some(&path) = args.get(1) else { eprintln!("history: -a: expected a file path"); return BuiltinResult::Handled; };
let new_entries = &command_history[*history_append_from..]; let mut contents = new_entries.join("\n");
if !new_entries.is_empty() { contents.push('\n'); }
let result = std::fs::OpenOptions::new() .create(true) .append(true) .open(path) .and_then(|mut file| file.write_all(contents.as_bytes()));
match result { Ok(()) => { *history_append_from = command_history.len(); } Err(e) => { eprintln!("history: {path}: {e}"); } }
return BuiltinResult::Handled; }
let count = match args.first() { Some(value) => match value.parse::<usize>() { Ok(count) => count, Err(_) => { eprintln!("{value}: expected a non-negative integer"); return BuiltinResult::Handled } }, None => command_history.len(), };
let start = command_history.len().saturating_sub(count);
for (index, entry) in command_history .iter() .enumerate() .skip(start)
{ println!("{:>5} {}", index + 1, entry); }
BuiltinResult::Handled } "declare" => { if args.first().copied() == Some("-p") { for &name in &args[1..] { match variables.get(name) { Some(value) => { println!("declare -- {name}=\"{value}\""); } None => { eprintln!("declare: {name}: not found"); } } } } else { for &assignment in args { if let Some((name, value)) = assignment.split_once('=') { if !is_valid_identifier(name) { eprintln!("declare: `{assignment}': not a valid identifier"); continue; }
variables.insert( name.to_string(), value.to_string()); } } }
BuiltinResult::Handled } _ => BuiltinResult::NotBuiltin, }}
fn run_pipeline(parsed_stages: &[ParsedCommand<'_>]) { let mut children: Vec<Child> = Vec::new(); let mut previous_stdout: Option<Stdio> = None;
for (i, parsed) in parsed_stages.iter().enumerate() { let mut stderr = Stdio::inherit(); let is_last = i == parsed_stages.len() - 1;
let mut stdin = if i == 0 { Stdio::inherit() } else { previous_stdout.take().unwrap_or_else(Stdio::null) };
let mut stdout = if is_last { Stdio::inherit() } else { Stdio::piped() };
if let Some(filename) = parsed.input_file { match File::open(filename) { Ok(file) => stdin = Stdio::from(file), Err(e) => { eprintln!("$: {filename}: {e}"); break; } } }
if let Some((operator, filename)) = parsed.output_redirect { let file_result = if operator == ">>" { std::fs::OpenOptions::new() .create(true) .append(true) .open(filename) } else { File::create(filename) }; match file_result { Ok(file) => stdout = Stdio::from(file), Err(e) => { eprintln!("{filename}: {e}"); break; } } }
if let Some((operator, filename)) = parsed.error_redirect { let file_result = if operator == "2>>" { std::fs::OpenOptions::new() .create(true) .append(true) .open(filename) } else { File::create(filename) }; match file_result { Ok(file) => stderr = Stdio::from(file), Err(e) => { eprintln!("{filename}: {e}"); break; } } }
let mut process = if BUILTINS.contains(&parsed.command) { let shell_path = match env::current_exe() { Ok(path) => path, Err(e) => { eprintln!("cannot locate shell executable: {e}"); break; } };
let mut child_shell = Command::new(shell_path); child_shell .arg("--run-builtin") .arg(parsed.command);
child_shell } else { Command::new(parsed.command) };
match process .args(&parsed.args) .stdin(stdin) .stdout(stdout) .stderr(stderr) .spawn()
{ Ok(mut child) => { previous_stdout = child.stdout.take().map(Stdio::from); children.push(child); } Err(e) => { eprintln!("$: {}: {e}", parsed.command); break; } } }
// Start every stage before waiting so pipe readers and writers // can run concurrently, even when output exceeds the pipe's buffer. for mut child in children { let _ = child.wait(); }}fn spawn_command( parsed: &ParsedCommand<'_>,) -> std::io::Result<Child> { let mut process = Command::new(parsed.command); process.args(&parsed.args);
if let Some(filename) = parsed.input_file { let file = File::open(filename)?; process.stdin(Stdio::from(file)); }
if let Some((operator, filename)) = parsed.output_redirect { let file = if operator == ">>" { std::fs::OpenOptions::new() .create(true) .append(true) .open(filename)? } else { File::create(filename)? };
process.stdout(Stdio::from(file)); }
if let Some((operator, filename)) = parsed.error_redirect { let file = if operator == "2>>" { std::fs::OpenOptions::new() .create(true) .append(true) .open(filename)? } else { File::create(filename)? };
process.stderr(Stdio::from(file)); }
process.spawn()}
fn handle_redirection( parsed: &ParsedCommand<'_>,) -> std::io::Result<bool> { if parsed.input_file.is_none() && parsed.output_redirect.is_none() && parsed.error_redirect.is_none() { return Ok(false); }
spawn_command(parsed)?.wait()?;
Ok(true)}
fn run_external(command: &str, args: &[&str]) { match Command::new(command).args(args).spawn() { Ok(mut child) => { if let Err(e) = child.wait() { eprintln!("$: failed to wait on {command}: {e}"); } } Err(e) => { if e.kind() == std::io::ErrorKind::NotFound { eprintln!("{command}: command not found"); } else { eprintln!("{command}: {e}"); } } }}
fn run_line( line: &str, completions: &mut HashMap<String, String>, jobs: &mut Vec<Job>, command_history: &mut Vec<String>, history_append_from: &mut usize, variables: &mut HashMap<String, String>,) -> bool { let mut tokens = match tokenize(line, variables) { Ok(tokens) => tokens, Err(message) => { eprintln!("$: {message}"); return false; } };
let background = matches!(tokens.last(), Some(Token::Background));
if background { tokens.pop();
if tokens.is_empty() { eprintln!("expected command before &"); return false; } }
if tokens.is_empty() { return false; }
let mut parsed_stages = Vec::new();
for stage in tokens.split(|token| matches!(token, Token::Pipe)) { match parse_token(stage) { Ok(parsed) => parsed_stages.push(parsed), Err(message) => { eprintln!("$: {message}"); return false; } } }
if background { if parsed_stages.len() != 1 { eprintln!("background pipelines are not supported yet"); return false; }
let parsed = &parsed_stages[0];
match spawn_command(parsed) { Ok(child) => { let id = jobs.iter().map(|job| job.id).max().unwrap_or(0) + 1; let pid = child.id();
jobs.push(Job { id, child, command: line .trim_end() .strip_suffix('&') .unwrap_or(line) .trim_end() .to_string(), });
println!("[{id}] {pid}"); } Err(e) => { eprintln!("{}: {e}", parsed.command); } }
return false; }
if parsed_stages.len() == 1 { let parsed = &parsed_stages[0];
match handle_redirection(parsed) { Ok(true) => return false, Ok(false) => {} Err(e) => { eprintln!("$: {e}"); return false; } }
match run_builtin( parsed.command, &parsed.args, completions, jobs, command_history, history_append_from, variables, ) { BuiltinResult::Exit => return true, BuiltinResult::Handled => return false, BuiltinResult::NotBuiltin => {} }
run_external(parsed.command, &parsed.args); } else { run_pipeline(&parsed_stages); }
false}
fn main() -> rustyline::Result<()> { let startup_args: Vec<String> = env::args().skip(1).collect();
if startup_args.first().map(String::as_str) == Some("--run-builtin") { let Some(command) = startup_args.get(1) else { eprintln!("expected builtin name"); return Ok(()); };
let args: Vec<&str> = startup_args[2..] .iter() .map(String::as_str) .collect();
let mut completions = HashMap::new(); let mut jobs = Vec::new(); let mut command_history: Vec<String> = Vec::new(); let mut history_append_from: usize = 0; let mut variables: HashMap<String, String> = HashMap::new();
run_builtin( command, &args, &mut completions, &mut jobs, &mut command_history, &mut history_append_from, &mut variables, );
return Ok(()); } let config = rustyline::Config::builder() .completion_type(rustyline::CompletionType::List) .build();
let mut editor = Editor::<ShellHelper, DefaultHistory>::with_config(config)?; editor.set_helper(Some(ShellHelper { completions: HashMap::new(), }));
let mut jobs: Vec<Job> = Vec::new(); let mut command_history: Vec<String> = Vec::new(); let history_path = env::var_os("HISTFILE");
if let Some(path) = &history_path { match std::fs::read_to_string(path) { Ok(contents) => { for entry in contents.lines() { if !entry.is_empty(){ command_history.push(entry.to_string()); editor.add_history_entry(entry)?; } } } Err(e) if e.kind() == std::io::ErrorKind::NotFound => { // No existing history file to load. } Err(e) => { eprintln!("history: {e}"); } } }
// Loaded entries are already on disk. Append only entries added afterward. let mut history_append_from = command_history.len(); let mut variables: HashMap<String, String> = HashMap::new();
loop { report_jobs(&mut jobs, false);
match editor.readline("$ ") { Ok(line) => { let line = line.trim(); if line.is_empty() { continue; } command_history.push(line.to_string()); editor.add_history_entry(line)?;
let should_exit = { let helper = editor .helper_mut() .expect("ShellHelper was installed");
run_line( line, &mut helper.completions, &mut jobs, &mut command_history, &mut history_append_from, &mut variables, ) };
if should_exit { break; } } Err(ReadlineError::Interrupted) => { // Ctrl+C: cancel the current line, don't kill the shell. continue; } Err(ReadlineError::Eof) => break, // Ctrl+D Err(e) => { eprintln!("$: readline error: {e}"); break; } } }
if let Some(path) = &history_path { let mut contents = command_history.join("\n");
if !command_history.is_empty() { contents.push('\n'); }
if let Err(e) = std::fs::write(path, contents) { eprintln!("history: {e}"); } }
Ok(())
}