diff options
| -rw-r--r-- | src/main.rs | 46 | ||||
| -rw-r--r-- | src/run/mod.rs | 4 |
2 files changed, 44 insertions, 6 deletions
diff --git a/src/main.rs b/src/main.rs index c912c04..328c4ba 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,15 +36,12 @@ macro_rules! println { }}; } -const PROMPT: &str = "> "; - fn completely_clear_screen() { print!("\x1B[2J\x1B[1;1H"); } fn clear_screen() { completely_clear_screen(); - print!("{PROMPT}") } type BString = Vec<u8>; @@ -58,6 +55,47 @@ pub struct Session { dispatch: CommandDispatch, } +/// relative path -- in case it is a proper subpath the result starts with a slash `/` +fn relative_path(root: &Path, target: &Path) -> Option<String> { + let root = root.to_string_lossy(); + let mut target = target.to_string_lossy().to_string(); + if !target.ends_with("/") { + target += "/"; + } + if let Some(("", leaf)) = target.split_once(&*root) { + Some(leaf.into()) + } else { + None + } +} + +impl Session { + fn pretty_cwd_res(&self) -> io::Result<String> { + let dir = std::env::current_dir()?; + let mut s = if let Some(home_dir) = std::env::home_dir() { + if let Some(rela) = relative_path(&home_dir, &dir) { + format!("~{rela}") + } else { + dir.to_string_lossy().to_string() + } + } else { + dir.to_string_lossy().to_string() + }; + while s.ends_with("/") { + s.remove(s.len() - 1); + } + Ok(s) + } + + fn pretty_cwd(&self) -> String { + self.pretty_cwd_res().unwrap_or_else(|_| String::new()) + } + + fn prompt(&self) -> String { + format!("{} $ ", self.pretty_cwd()) + } +} + fn event_loop() { let stdin = io::stdin(); let stdout = io::stdout(); @@ -73,7 +111,7 @@ fn event_loop() { dispatch: CommandDispatch::new(), }; - print!("{PROMPT}"); + print!("{}", se.prompt()); loop { let mut buf = [0u8; 1]; diff --git a/src/run/mod.rs b/src/run/mod.rs index 73011fd..e1dcacc 100644 --- a/src/run/mod.rs +++ b/src/run/mod.rs @@ -15,7 +15,7 @@ pub fn run(se: &mut Session, cmd: Vec<u8>) { Ok(p) => p, Err(err) => { println!("{cmd:?}"); - print!("{err:?}\r\n{PROMPT}"); + print!("{err:?}\r\n{}", se.prompt()); return; } }; @@ -137,7 +137,7 @@ pub fn run(se: &mut Session, cmd: Vec<u8>) { se.raw.enable(); - print!("\r{status_string}{PROMPT}"); + print!("\r{status_string}\r\n{}", se.prompt()); let _ = std::io::stdout().lock().flush(); } |
