diff options
author | Lars Wirzenius <liw@liw.fi> | 2021-10-16 11:18:48 +0300 |
---|---|---|
committer | Lars Wirzenius <liw@liw.fi> | 2021-10-16 11:18:48 +0300 |
commit | f7d5a9e11eed3f7f0769fbb154acb10bdc7fb58d (patch) | |
tree | e2e6e500848617920b53dd126c1392e4db49a2e2 /src/util.rs | |
parent | 21521cfe1b0870e8552d19b022ac0c3902eb356e (diff) | |
download | vmadm-f7d5a9e11eed3f7f0769fbb154acb10bdc7fb58d.tar.gz |
feat: allow ~user/ in path names, not just ~/
Add the home-dir crate as a dependency for tilde expansion.
Sponsored-by: author
Diffstat (limited to 'src/util.rs')
-rw-r--r-- | src/util.rs | 28 |
1 files changed, 10 insertions, 18 deletions
diff --git a/src/util.rs b/src/util.rs index 9a86ea0..2db4390 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,5 +1,7 @@ //! Utilities. +use home_dir::HomeDirExt; + use log::debug; use std::net::TcpStream; use std::path::{Path, PathBuf}; @@ -18,34 +20,24 @@ pub fn wait_for_ssh(name: &str) { } /// Expand a ~/ at the beginning of a Path to refer to the home directory. -pub fn expand_tilde(path: &Path) -> PathBuf { - if path.starts_with("~/") { - if let Some(home) = std::env::var_os("HOME") { - let mut expanded = PathBuf::from(home); - for comp in path.components().skip(1) { - expanded.push(comp); - } - expanded - } else { - path.to_path_buf() - } - } else { - path.to_path_buf() - } +pub fn expand_tilde(path: &Path) -> Result<PathBuf, home_dir::Error> { + path.expand_home() } -pub fn expand_optional_pathbuf(maybe_path: &mut Option<PathBuf>) { +pub fn expand_optional_pathbuf(maybe_path: &mut Option<PathBuf>) -> Result<(), home_dir::Error> { if let Some(path) = maybe_path { - *maybe_path = Some(expand_tilde(path)); + *maybe_path = Some(expand_tilde(path)?); } + Ok(()) } -pub fn expand_optional_pathbufs(maybe_paths: &mut Option<Vec<PathBuf>>) { +pub fn expand_optional_pathbufs(maybe_paths: &mut Option<Vec<PathBuf>>) -> Result<(), home_dir::Error> { if let Some(paths) = maybe_paths { let mut expanded = vec![]; for path in paths { - expanded.push(expand_tilde(path)); + expanded.push(expand_tilde(path)?); } *maybe_paths = Some(expanded); } + Ok(()) } |