custom_utils/util_args/
mod.rs1use anyhow::Context;
2use std::path::PathBuf;
3
4pub fn arg_value(long: &str, short: &str) -> Option<String> {
6 assert!(long.starts_with("--"));
7 assert!(short.starts_with('-'));
8 let mut is_val = false;
9 for arg in std::env::args() {
10 if is_val {
11 return Some(arg);
12 }
13 is_val = arg == long || arg == short;
14 }
15 None
16}
17
18pub fn exist_arg(long: &str, short: &str) -> bool {
20 assert!(long.starts_with("--"));
21 assert!(short.starts_with('-'));
22 for arg in std::env::args() {
23 if arg == long || arg == short {
24 return true;
25 }
26 }
27 false
28}
29
30pub fn command() -> Option<String> {
31 for (index, arg) in std::env::args().enumerate() {
32 if index == 1 {
33 return Some(arg);
34 }
35 }
36 None
37}
38
39pub fn get_user_home() -> anyhow::Result<PathBuf> {
41 home::home_dir().context("Failed to get user home directory")
42}
43
44pub fn expand_path(path: &str) -> anyhow::Result<PathBuf> {
46 if let Some(stripped) = path.strip_prefix('~') {
47 let home = get_user_home()?;
48 let suffix = stripped.trim_start_matches(['/', '\\']);
50 return Ok(home.join(suffix));
51 }
52
53 if path == "." || path == "./" || path == ".\\" {
54 return std::env::current_dir().context("Failed to get current directory");
55 }
56
57 if let Some(stripped) = path.strip_prefix("./").or_else(|| path.strip_prefix(".\\")) {
58 let current_dir = std::env::current_dir().context("Failed to get current directory")?;
59 let suffix = stripped.trim_start_matches(['/', '\\']);
60 return Ok(current_dir.join(suffix));
61 }
62
63 let expanded = shellexpand::tilde(path);
64 Ok(PathBuf::from(expanded.into_owned()))
65}
66
67pub fn workspace(arg_workspace: &Option<String>, app: &str) -> anyhow::Result<PathBuf> {
69 workspace_with_config(arg_workspace, &None, app)
70}
71pub fn workspace_with_config(arg_workspace: &Option<String>, config_workspace: &Option<String>, app: &str) -> anyhow::Result<PathBuf> {
73 let workspace = if let Some(workspace) = arg_workspace {
74 expand_path(workspace)?
75 } else if let Some(workspace) = config_workspace {
76 expand_path(workspace)?
77 } else {
78 get_user_home()?.join(".config").join(app)
79 };
80 log::debug!("{}", workspace.display());
81 Ok(workspace)
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87 use std::env;
88
89 #[test]
90 fn test_get_user_home() {
91 let home = get_user_home();
92 assert!(home.is_ok());
93 }
94
95 #[test]
96 fn test_expand_path_tilde() {
97 let home = get_user_home().unwrap();
98 let expanded = expand_path("~").unwrap();
99 assert_eq!(expanded, home);
100 }
101
102 #[test]
103 fn test_expand_path_dot() {
104 let cwd = std::env::current_dir().unwrap();
105 let expanded = expand_path("./test").unwrap();
106 assert_eq!(expanded, cwd.join("test"));
107 }
108
109 #[test]
110 fn test_expand_path_dot_only() {
111 let cwd = std::env::current_dir().unwrap();
112 assert_eq!(expand_path(".").unwrap(), cwd);
113 }
114}