diff options
author | Manos Pitsidianakis <el13635@mail.ntua.gr> | 2019-09-26 18:27:13 +0300 |
---|---|---|
committer | Manos Pitsidianakis <el13635@mail.ntua.gr> | 2019-09-26 18:27:13 +0300 |
commit | 9d69a068073e89bd965b49acf314556eeab2fe54 (patch) | |
tree | 2af289cb0772803b9eb9871920999f5f5013d8f8 /melib/src/lib.rs | |
parent | 0ece51612f68db228f6ff75e05a465ea103ceede (diff) |
melib: add ShellExpandTrait
Add trait to expand "~" and environment variables in paths.
Diffstat (limited to 'melib/src/lib.rs')
-rw-r--r-- | melib/src/lib.rs | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/melib/src/lib.rs b/melib/src/lib.rs index 1a459469..38ebfce2 100644 --- a/melib/src/lib.rs +++ b/melib/src/lib.rs @@ -128,3 +128,47 @@ pub use crate::email::{Envelope, Flag}; pub use crate::error::{MeliError, Result}; pub use crate::addressbook::*; + +pub use shellexpand::ShellExpandTrait; +pub mod shellexpand { + + use std::path::*; + + pub trait ShellExpandTrait { + fn expand(&self) -> PathBuf; + } + + impl ShellExpandTrait for Path { + fn expand(&self) -> PathBuf { + let mut ret = PathBuf::new(); + for c in self.components() { + let c_to_str = c.as_os_str().to_str(); + match c_to_str { + Some("~") => { + if let Some(home_dir) = std::env::var("HOME").ok() { + ret.push(home_dir) + } else { + return PathBuf::new(); + } + } + Some(var) if var.starts_with("$") => { + let env_name = var.split_at(1).1; + if env_name.chars().all(char::is_uppercase) { + ret.push(std::env::var(env_name).unwrap_or(String::new())); + } else { + ret.push(c); + } + } + Some(_) => { + ret.push(c); + } + None => { + /* path is invalid */ + return PathBuf::new(); + } + } + } + ret + } + } +} |