From 79682d2302b87f750bbed274536a6ea1a637a2f5 Mon Sep 17 00:00:00 2001 From: Vincent Ollivier Date: Sun, 10 Jul 2022 22:00:13 +0200 Subject: [PATCH] Add tilde expansion to shell (#367) * Add tilde expansion to shell * Add tilde expansion to auto complete * Move tilde expansion into split_args * Add doc --- doc/shell.md | 5 +++++ src/usr/shell.rs | 14 ++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/doc/shell.md b/doc/shell.md index aea435962..062192e62 100644 --- a/doc/shell.md +++ b/doc/shell.md @@ -167,3 +167,8 @@ by files matching the pattern. For example `/tmp/*.txt` will match any files with the `txt` extension inside `/tmp`, and `a?c.txt` will match a file named `abc.txt`. + +## Tilde Expansion + +The tilde character `~` is a shortcut to `$HOME` so `~/test` will be expanded +to `$HOME/test` by the shell. diff --git a/src/usr/shell.rs b/src/usr/shell.rs index 0248fddb9..201f3a857 100644 --- a/src/usr/shell.rs +++ b/src/usr/shell.rs @@ -56,7 +56,7 @@ fn shell_completer(line: &str) -> Vec { let args = split_args(line); let i = args.len() - 1; - if args.len() == 1 && !args[0].starts_with('/') { // Autocomplete command + if args.len() == 1 && !args[0].starts_with('/') && !args[0].starts_with('~') { // Autocomplete command for cmd in autocomplete_commands() { if let Some(entry) = cmd.strip_prefix(&args[i]) { entries.push(entry.into()); @@ -187,7 +187,17 @@ pub fn split_args(cmd: &str) -> Vec { args.push("".to_string()); } - args + args.iter().map(|s| tilde_expansion(&s)).collect() +} + +// Replace `~` with the value of `$HOME` when it's at the begining of an arg +fn tilde_expansion(arg: &str) -> String { + if let Some(home) = sys::process::env("HOME") { + if arg == "~" || arg.starts_with("~/") { + return arg.replacen("~", &home, 1); + } + } + arg.to_string() } fn cmd_proc(args: &[&str]) -> Result<(), ExitCode> {