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(
73 arg_workspace: &Option<String>,
74 config_workspace: &Option<String>,
75 app: &str,
76) -> anyhow::Result<PathBuf> {
77 let workspace = if let Some(workspace) = arg_workspace {
78 expand_path(workspace)?
79 } else if let Some(workspace) = config_workspace {
80 expand_path(workspace)?
81 } else {
82 get_user_home()?.join(".config").join(app)
83 };
84 log::debug!("{}", workspace.display());
85 Ok(workspace)
86}
87
88#[cfg(test)]
89mod tests {
90 use super::*;
91 use std::env;
92
93 #[test]
94 fn test_get_user_home() {
95 let home = get_user_home();
96 assert!(home.is_ok());
97 }
98
99 #[test]
100 fn test_expand_path_tilde() {
101 let home = get_user_home().unwrap();
102 let expanded = expand_path("~").unwrap();
103 assert_eq!(expanded, home);
104 }
105
106 #[test]
107 fn test_expand_path_dot() {
108 let cwd = std::env::current_dir().unwrap();
109 let expanded = expand_path("./test").unwrap();
110 assert_eq!(expanded, cwd.join("test"));
111 }
112
113 #[test]
114 fn test_expand_path_dot_only() {
115 let cwd = std::env::current_dir().unwrap();
116 assert_eq!(expand_path(".").unwrap(), cwd);
117 }
118}