From 65fc61f7e4cb5c743db27ccc5db9abff0e82c23a Mon Sep 17 00:00:00 2001 From: Sathish Date: Sun, 19 Sep 2021 15:16:13 +0530 Subject: [PATCH] feat untildify --- .gitignore | 3 +++ Cargo.toml | 18 ++++++++++++++++ src/lib.rs | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ad2f0ff --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target +Cargo.lock +.DS_Store \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..cd52141 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "untildify" +version = "0.1.0" +edition = "2018" +license = "MIT" +readme = "README.md" +authors = ["sathishsoundharajan "] +categories = ["development-tools"] +homepage = "https://github.com/sathishsoundharajan/untildify" +repository = "https://github.com/sathishsoundharajan/untildify" +keywords = ["tilde", "untildify", "~", "utility"] +documentation = "https://docs.rs/untildify" + +[badges.maintenance] +status = "actively-developed" + +[dependencies] +regex = "1.5.4" diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..d39bb5f --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,60 @@ +use regex::Regex; +use std::env; +use std::path::PathBuf; + +pub fn untildify(input_path: &str) -> String { + if input_path.is_empty() { + return String::from(input_path); + } + return match get_host_dir() { + Some(path) => { + let host_dir = path.to_str().unwrap(); + let re = Regex::new(r"^~([/\w]+)").unwrap(); + match re.captures(input_path) { + Some(captures) => { + return format!("{}{}", host_dir, &captures[1]); + } + None => String::from(input_path), + } + } + None => String::from(input_path), + }; +} + +#[cfg(any(unix, target_os = "redox"))] +fn get_host_dir() -> Option { + #[allow(deprecated)] + env::home_dir() +} + +#[cfg(test)] +mod tests { + use crate::untildify; + use std::env; + use std::path::Path; + + #[test] + fn test_returns_untildfyed_string() { + env::remove_var("HOME"); + + let home = Path::new("/User/Untildify"); + env::set_var("HOME", home.as_os_str()); + + assert_eq!(untildify("~/Desktop"), "/User/Untildify/Desktop"); + assert_eq!(untildify("~/a/b/c/d/e"), "/User/Untildify/a/b/c/d/e"); + assert_eq!(untildify("~/"), "/User/Untildify/"); + } + + #[test] + fn test_returns_empty_string() { + env::remove_var("HOME"); + + let home = Path::new("/User/Untildify"); + env::set_var("HOME", home.as_os_str()); + + assert_eq!(untildify("Desktop"), "Desktop"); + assert_eq!(untildify(""), ""); + assert_eq!(untildify("/"), "/"); + assert_eq!(untildify("~/Desktop/~/Code"), "/User/Untildify/Desktop/"); + } +}