1use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5use std::sync::LazyLock;
6
7use regex::Regex;
8use serde::{Deserialize, Serialize};
9
10static UNSAFE_RE: LazyLock<Regex> =
12 LazyLock::new(|| Regex::new(r#"[/<>:"|?*\\#@&;$`!~%^()\[\]{}=+]+"#).unwrap());
13static WHITESPACE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
14static MULTI_HYPHEN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-+").unwrap());
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[serde(rename_all = "kebab-case")]
19pub enum LaunchMethod {
20 Foreground,
21 Detach,
22 ItermWindow,
24 ItermTab,
25 ItermPaneH,
26 ItermPaneV,
27 Tmux,
29 TmuxWindow,
30 TmuxPaneH,
31 TmuxPaneV,
32 Zellij,
34 ZellijTab,
35 ZellijPaneH,
36 ZellijPaneV,
37 WeztermWindow,
39 WeztermTab,
40 WeztermPaneH,
41 WeztermPaneV,
42}
43
44impl LaunchMethod {
45 pub fn as_str(&self) -> &'static str {
47 match self {
48 Self::Foreground => "foreground",
49 Self::Detach => "detach",
50 Self::ItermWindow => "iterm-window",
51 Self::ItermTab => "iterm-tab",
52 Self::ItermPaneH => "iterm-pane-h",
53 Self::ItermPaneV => "iterm-pane-v",
54 Self::Tmux => "tmux",
55 Self::TmuxWindow => "tmux-window",
56 Self::TmuxPaneH => "tmux-pane-h",
57 Self::TmuxPaneV => "tmux-pane-v",
58 Self::Zellij => "zellij",
59 Self::ZellijTab => "zellij-tab",
60 Self::ZellijPaneH => "zellij-pane-h",
61 Self::ZellijPaneV => "zellij-pane-v",
62 Self::WeztermWindow => "wezterm-window",
63 Self::WeztermTab => "wezterm-tab",
64 Self::WeztermPaneH => "wezterm-pane-h",
65 Self::WeztermPaneV => "wezterm-pane-v",
66 }
67 }
68
69 pub fn from_str_opt(s: &str) -> Option<Self> {
71 match s {
72 "foreground" => Some(Self::Foreground),
73 "detach" => Some(Self::Detach),
74 "iterm-window" => Some(Self::ItermWindow),
75 "iterm-tab" => Some(Self::ItermTab),
76 "iterm-pane-h" => Some(Self::ItermPaneH),
77 "iterm-pane-v" => Some(Self::ItermPaneV),
78 "tmux" => Some(Self::Tmux),
79 "tmux-window" => Some(Self::TmuxWindow),
80 "tmux-pane-h" => Some(Self::TmuxPaneH),
81 "tmux-pane-v" => Some(Self::TmuxPaneV),
82 "zellij" => Some(Self::Zellij),
83 "zellij-tab" => Some(Self::ZellijTab),
84 "zellij-pane-h" => Some(Self::ZellijPaneH),
85 "zellij-pane-v" => Some(Self::ZellijPaneV),
86 "wezterm-window" => Some(Self::WeztermWindow),
87 "wezterm-tab" => Some(Self::WeztermTab),
88 "wezterm-pane-h" => Some(Self::WeztermPaneH),
89 "wezterm-pane-v" => Some(Self::WeztermPaneV),
90 _ => None,
91 }
92 }
93}
94
95impl std::fmt::Display for LaunchMethod {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 f.write_str(self.as_str())
98 }
99}
100
101pub fn launch_method_aliases() -> HashMap<&'static str, &'static str> {
106 HashMap::from([
107 ("fg", "foreground"),
108 ("d", "detach"),
109 ("i-w", "iterm-window"),
111 ("i-t", "iterm-tab"),
112 ("i-p-h", "iterm-pane-h"),
113 ("i-p-v", "iterm-pane-v"),
114 ("t", "tmux"),
116 ("t-w", "tmux-window"),
117 ("t-p-h", "tmux-pane-h"),
118 ("t-p-v", "tmux-pane-v"),
119 ("z", "zellij"),
121 ("z-t", "zellij-tab"),
122 ("z-p-h", "zellij-pane-h"),
123 ("z-p-v", "zellij-pane-v"),
124 ("w-w", "wezterm-window"),
126 ("w-t", "wezterm-tab"),
127 ("w-p-h", "wezterm-pane-h"),
128 ("w-p-v", "wezterm-pane-v"),
129 ])
130}
131
132pub const SECS_PER_DAY: u64 = 86400;
134
135pub const SECS_PER_DAY_F64: f64 = 86400.0;
137
138pub const MIN_GIT_VERSION: &str = "2.31.0";
140
141pub const MIN_GIT_VERSION_MAJOR: u32 = 2;
143
144pub const MIN_GIT_VERSION_MINOR: u32 = 31;
146
147pub const AI_TOOL_TIMEOUT_SECS: u64 = 60;
149
150pub const AI_TOOL_POLL_MS: u64 = 100;
152
153pub const MAX_SESSION_NAME_LENGTH: usize = 50;
156
157pub const CLAUDE_SESSION_PREFIX_LENGTH: usize = 200;
159
160pub const CONFIG_KEY_BASE_BRANCH: &str = "branch.{}.worktreeBase";
162pub const CONFIG_KEY_BASE_PATH: &str = "worktree.{}.basePath";
163pub const CONFIG_KEY_INTENDED_BRANCH: &str = "worktree.{}.intendedBranch";
164
165pub fn format_config_key(template: &str, branch: &str) -> String {
167 template.replace("{}", branch)
168}
169
170pub fn home_dir_or_fallback() -> PathBuf {
172 dirs::home_dir().unwrap_or_else(|| PathBuf::from("."))
173}
174
175pub fn path_age_days(path: &Path) -> Option<f64> {
177 let mtime = path.metadata().and_then(|m| m.modified()).ok()?;
178 std::time::SystemTime::now()
179 .duration_since(mtime)
180 .ok()
181 .map(|d| d.as_secs_f64() / SECS_PER_DAY_F64)
182}
183
184pub fn version_meets_minimum(version_str: &str, min_major: u32, min_minor: u32) -> bool {
186 let parts: Vec<u32> = version_str
187 .split('.')
188 .filter_map(|p| p.parse().ok())
189 .collect();
190 parts.len() >= 2 && (parts[0] > min_major || (parts[0] == min_major && parts[1] >= min_minor))
191}
192
193pub fn sanitize_branch_name(branch_name: &str) -> String {
206 let safe = UNSAFE_RE.replace_all(branch_name, "-");
207 let safe = WHITESPACE_RE.replace_all(&safe, "-");
208 let safe = MULTI_HYPHEN_RE.replace_all(&safe, "-");
209 let safe = safe.trim_matches('-');
210
211 if safe.is_empty() {
212 "worktree".to_string()
213 } else {
214 safe.to_string()
215 }
216}
217
218pub fn default_worktree_path(repo_path: &Path, branch_name: &str) -> PathBuf {
220 let repo_path = strip_unc(
221 repo_path
222 .canonicalize()
223 .unwrap_or_else(|_| repo_path.to_path_buf()),
224 );
225 let safe_branch = sanitize_branch_name(branch_name);
226 let repo_name = repo_path
227 .file_name()
228 .map(|n| n.to_string_lossy().to_string())
229 .unwrap_or_else(|| "repo".to_string());
230
231 repo_path
232 .parent()
233 .unwrap_or(repo_path.as_path())
234 .join(format!("{}-{}", repo_name, safe_branch))
235}
236
237pub fn strip_unc(path: PathBuf) -> PathBuf {
240 #[cfg(target_os = "windows")]
241 {
242 let s = path.to_string_lossy();
243 if let Some(stripped) = s.strip_prefix(r"\\?\") {
244 return PathBuf::from(stripped);
245 }
246 }
247 path
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253
254 #[test]
255 fn test_sanitize_branch_name() {
256 assert_eq!(sanitize_branch_name("feat/auth"), "feat-auth");
257 assert_eq!(sanitize_branch_name("bugfix/issue-123"), "bugfix-issue-123");
258 assert_eq!(
259 sanitize_branch_name("feature/user@login"),
260 "feature-user-login"
261 );
262 assert_eq!(sanitize_branch_name("hotfix/v2.0"), "hotfix-v2.0");
263 assert_eq!(sanitize_branch_name("///"), "worktree");
264 assert_eq!(sanitize_branch_name(""), "worktree");
265 assert_eq!(sanitize_branch_name("simple"), "simple");
266 }
267
268 #[test]
269 fn test_launch_method_roundtrip() {
270 for method in [
271 LaunchMethod::Foreground,
272 LaunchMethod::Detach,
273 LaunchMethod::ItermWindow,
274 LaunchMethod::Tmux,
275 LaunchMethod::Zellij,
276 LaunchMethod::WeztermTab,
277 ] {
278 let s = method.as_str();
279 assert_eq!(LaunchMethod::from_str_opt(s), Some(method));
280 }
281 }
282
283 #[test]
284 fn test_format_config_key() {
285 assert_eq!(
286 format_config_key(CONFIG_KEY_BASE_BRANCH, "fix-auth"),
287 "branch.fix-auth.worktreeBase"
288 );
289 }
290
291 #[test]
292 fn test_home_dir_or_fallback() {
293 let home = home_dir_or_fallback();
294 assert!(!home.as_os_str().is_empty());
296 }
297
298 #[test]
299 fn test_path_age_days() {
300 assert!(path_age_days(std::path::Path::new("/nonexistent/path")).is_none());
302
303 let tmp = std::env::temp_dir();
305 if let Some(age) = path_age_days(&tmp) {
306 assert!(age >= 0.0);
307 }
308 }
309
310 #[test]
311 fn test_version_meets_minimum() {
312 assert!(version_meets_minimum("2.31.0", 2, 31));
313 assert!(version_meets_minimum("2.40.0", 2, 31));
314 assert!(version_meets_minimum("3.0.0", 2, 31));
315 assert!(!version_meets_minimum("2.30.0", 2, 31));
316 assert!(!version_meets_minimum("1.99.0", 2, 31));
317 assert!(!version_meets_minimum("", 2, 31));
318 assert!(!version_meets_minimum("2", 2, 31));
319 }
320}