From 28e08afada349ec55b8f7a0ad6bd8e3f430cc461 Mon Sep 17 00:00:00 2001 From: Darren Schroeder <343840+fdncred@users.noreply.github.com> Date: Fri, 26 Mar 2021 04:29:02 -0500 Subject: [PATCH] add ability to cd to ~/blah (#3210) * add ability to cd to ~/blah. tested on windows. * added dirs_next * put change behind feature for linux-minimal/wasm * clippy * holy crap minimal, i'm about done with you! --- crates/nu-engine/src/filesystem/path.rs | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/crates/nu-engine/src/filesystem/path.rs b/crates/nu-engine/src/filesystem/path.rs index b28c29f46..5b59ae5d1 100644 --- a/crates/nu-engine/src/filesystem/path.rs +++ b/crates/nu-engine/src/filesystem/path.rs @@ -11,6 +11,17 @@ where // more ugly - so we don't do anything, which should result in an equal // path on all supported systems. relative_to.as_ref().to_owned() + } else if path.as_ref().starts_with("~") { + #[cfg(feature = "dirs")] + { + let expanded_path = expand_tilde(path.as_ref()); + match expanded_path { + Some(p) => p, + _ => path.as_ref().to_owned(), + } + } + #[cfg(not(feature = "dirs"))] + relative_to.as_ref().join(path) } else { relative_to.as_ref().join(path) }; @@ -54,6 +65,32 @@ where dunce::simplified(&path).to_path_buf() } +// borrowed from here https://stackoverflow.com/questions/54267608/expand-tilde-in-rust-path-idiomatically +#[cfg(feature = "dirs")] +fn expand_tilde>(path_user_input: P) -> Option { + let p = path_user_input.as_ref(); + if !p.starts_with("~") { + return Some(p.to_path_buf()); + } + + if p == Path::new("~") { + return dirs_next::home_dir(); + } + + dirs_next::home_dir().map(|mut h| { + if h == Path::new("/") { + // Corner case: `h` root directory; + // don't prepend extra `/`, just drop the tilde. + p.strip_prefix("~") + .expect("cannot strip ~ prefix") + .to_path_buf() + } else { + h.push(p.strip_prefix("~/").expect("cannot strip ~/ prefix")); + h + } + }) +} + pub fn canonicalize(relative_to: P, path: Q) -> io::Result where P: AsRef,