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 WeztermTabBg,
43}
44
45impl LaunchMethod {
46 pub fn as_str(&self) -> &'static str {
48 match self {
49 Self::Foreground => "foreground",
50 Self::Detach => "detach",
51 Self::ItermWindow => "iterm-window",
52 Self::ItermTab => "iterm-tab",
53 Self::ItermPaneH => "iterm-pane-h",
54 Self::ItermPaneV => "iterm-pane-v",
55 Self::Tmux => "tmux",
56 Self::TmuxWindow => "tmux-window",
57 Self::TmuxPaneH => "tmux-pane-h",
58 Self::TmuxPaneV => "tmux-pane-v",
59 Self::Zellij => "zellij",
60 Self::ZellijTab => "zellij-tab",
61 Self::ZellijPaneH => "zellij-pane-h",
62 Self::ZellijPaneV => "zellij-pane-v",
63 Self::WeztermWindow => "wezterm-window",
64 Self::WeztermTab => "wezterm-tab",
65 Self::WeztermPaneH => "wezterm-pane-h",
66 Self::WeztermPaneV => "wezterm-pane-v",
67 Self::WeztermTabBg => "wezterm-tab-bg",
68 }
69 }
70
71 pub fn from_str_opt(s: &str) -> Option<Self> {
73 match s {
74 "foreground" => Some(Self::Foreground),
75 "detach" => Some(Self::Detach),
76 "iterm-window" => Some(Self::ItermWindow),
77 "iterm-tab" => Some(Self::ItermTab),
78 "iterm-pane-h" => Some(Self::ItermPaneH),
79 "iterm-pane-v" => Some(Self::ItermPaneV),
80 "tmux" => Some(Self::Tmux),
81 "tmux-window" => Some(Self::TmuxWindow),
82 "tmux-pane-h" => Some(Self::TmuxPaneH),
83 "tmux-pane-v" => Some(Self::TmuxPaneV),
84 "zellij" => Some(Self::Zellij),
85 "zellij-tab" => Some(Self::ZellijTab),
86 "zellij-pane-h" => Some(Self::ZellijPaneH),
87 "zellij-pane-v" => Some(Self::ZellijPaneV),
88 "wezterm-window" => Some(Self::WeztermWindow),
89 "wezterm-tab" => Some(Self::WeztermTab),
90 "wezterm-pane-h" => Some(Self::WeztermPaneH),
91 "wezterm-pane-v" => Some(Self::WeztermPaneV),
92 "wezterm-tab-bg" => Some(Self::WeztermTabBg),
93 _ => None,
94 }
95 }
96}
97
98impl LaunchMethod {
99 pub fn to_bg(&self) -> Option<Self> {
103 match self {
104 Self::Foreground => Some(Self::Detach),
105 Self::WeztermTab => Some(Self::WeztermTabBg),
106 _ => None,
107 }
108 }
109
110 pub fn to_fg(&self) -> Option<Self> {
113 match self {
114 Self::Detach => Some(Self::Foreground),
115 Self::WeztermTabBg => Some(Self::WeztermTab),
116 _ => None,
117 }
118 }
119}
120
121impl LaunchMethod {
122 pub fn display_name(&self) -> &'static str {
124 match self {
125 Self::Foreground => "Foreground",
126 Self::Detach => "Detach (background)",
127 Self::ItermWindow => "iTerm2 — New Window",
128 Self::ItermTab => "iTerm2 — New Tab",
129 Self::ItermPaneH => "iTerm2 — Horizontal Pane",
130 Self::ItermPaneV => "iTerm2 — Vertical Pane",
131 Self::Tmux => "tmux — New Session",
132 Self::TmuxWindow => "tmux — New Window",
133 Self::TmuxPaneH => "tmux — Horizontal Pane",
134 Self::TmuxPaneV => "tmux — Vertical Pane",
135 Self::Zellij => "Zellij — New Session",
136 Self::ZellijTab => "Zellij — New Tab",
137 Self::ZellijPaneH => "Zellij — Horizontal Pane",
138 Self::ZellijPaneV => "Zellij — Vertical Pane",
139 Self::WeztermWindow => "WezTerm — New Window",
140 Self::WeztermTab => "WezTerm — New Tab",
141 Self::WeztermPaneH => "WezTerm — Horizontal Pane",
142 Self::WeztermPaneV => "WezTerm — Vertical Pane",
143 Self::WeztermTabBg => "WezTerm — New Tab (Background)",
144 }
145 }
146}
147
148impl std::fmt::Display for LaunchMethod {
149 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150 f.write_str(self.as_str())
151 }
152}
153
154pub fn launch_method_aliases() -> HashMap<&'static str, &'static str> {
159 HashMap::from([
160 ("fg", "foreground"),
161 ("d", "detach"),
162 ("i-w", "iterm-window"),
164 ("i-t", "iterm-tab"),
165 ("i-p-h", "iterm-pane-h"),
166 ("i-p-v", "iterm-pane-v"),
167 ("t", "tmux"),
169 ("t-w", "tmux-window"),
170 ("t-p-h", "tmux-pane-h"),
171 ("t-p-v", "tmux-pane-v"),
172 ("z", "zellij"),
174 ("z-t", "zellij-tab"),
175 ("z-p-h", "zellij-pane-h"),
176 ("z-p-v", "zellij-pane-v"),
177 ("w-w", "wezterm-window"),
179 ("w-t", "wezterm-tab"),
180 ("w-p-h", "wezterm-pane-h"),
181 ("w-p-v", "wezterm-pane-v"),
182 ("w-t-b", "wezterm-tab-bg"),
183 ])
184}
185
186pub const PRESET_NAMES: &[&str] = &[
188 "claude",
189 "claude-remote",
190 "claude-yolo",
191 "claude-yolo-remote",
192 "codex",
193 "codex-yolo",
194 "no-op",
195];
196
197pub const SECS_PER_DAY: u64 = 86400;
199
200pub const SECS_PER_DAY_F64: f64 = 86400.0;
202
203pub const MIN_GIT_VERSION: &str = "2.31.0";
205
206pub const MIN_GIT_VERSION_MAJOR: u32 = 2;
208
209pub const MIN_GIT_VERSION_MINOR: u32 = 31;
211
212pub const AI_TOOL_TIMEOUT_SECS: u64 = 60;
214
215pub const AI_TOOL_POLL_MS: u64 = 100;
217
218pub const MAX_SESSION_NAME_LENGTH: usize = 50;
221
222pub const CLAUDE_SESSION_PREFIX_LENGTH: usize = 200;
224
225pub const CONFIG_KEY_BASE_BRANCH: &str = "branch.{}.worktreeBase";
227pub const CONFIG_KEY_BASE_PATH: &str = "worktree.{}.basePath";
228pub const CONFIG_KEY_INTENDED_BRANCH: &str = "worktree.{}.intendedBranch";
229
230pub fn format_config_key(template: &str, branch: &str) -> String {
232 template.replace("{}", branch)
233}
234
235pub fn home_dir_or_fallback() -> PathBuf {
237 dirs::home_dir().unwrap_or_else(|| PathBuf::from("."))
238}
239
240pub fn path_age_days(path: &Path) -> Option<f64> {
242 let mtime = path.metadata().and_then(|m| m.modified()).ok()?;
243 std::time::SystemTime::now()
244 .duration_since(mtime)
245 .ok()
246 .map(|d| d.as_secs_f64() / SECS_PER_DAY_F64)
247}
248
249pub fn version_meets_minimum(version_str: &str, min_major: u32, min_minor: u32) -> bool {
251 let parts: Vec<u32> = version_str
252 .split('.')
253 .filter_map(|p| p.parse().ok())
254 .collect();
255 parts.len() >= 2 && (parts[0] > min_major || (parts[0] == min_major && parts[1] >= min_minor))
256}
257
258pub fn sanitize_branch_name(branch_name: &str) -> String {
271 let safe = UNSAFE_RE.replace_all(branch_name, "-");
272 let safe = WHITESPACE_RE.replace_all(&safe, "-");
273 let safe = MULTI_HYPHEN_RE.replace_all(&safe, "-");
274 let safe = safe.trim_matches('-');
275
276 if safe.is_empty() {
277 "worktree".to_string()
278 } else {
279 safe.to_string()
280 }
281}
282
283pub fn default_worktree_path(repo_path: &Path, branch_name: &str) -> PathBuf {
285 let repo_path = strip_unc(
286 repo_path
287 .canonicalize()
288 .unwrap_or_else(|_| repo_path.to_path_buf()),
289 );
290 let safe_branch = sanitize_branch_name(branch_name);
291 let repo_name = repo_path
292 .file_name()
293 .map(|n| n.to_string_lossy().to_string())
294 .unwrap_or_else(|| "repo".to_string());
295
296 repo_path
297 .parent()
298 .unwrap_or(repo_path.as_path())
299 .join(format!("{}-{}", repo_name, safe_branch))
300}
301
302pub fn strip_unc(path: PathBuf) -> PathBuf {
305 #[cfg(target_os = "windows")]
306 {
307 let s = path.to_string_lossy();
308 if let Some(stripped) = s.strip_prefix(r"\\?\") {
309 return PathBuf::from(stripped);
310 }
311 }
312 path
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318
319 #[test]
320 fn test_sanitize_branch_name() {
321 assert_eq!(sanitize_branch_name("feat/auth"), "feat-auth");
322 assert_eq!(sanitize_branch_name("bugfix/issue-123"), "bugfix-issue-123");
323 assert_eq!(
324 sanitize_branch_name("feature/user@login"),
325 "feature-user-login"
326 );
327 assert_eq!(sanitize_branch_name("hotfix/v2.0"), "hotfix-v2.0");
328 assert_eq!(sanitize_branch_name("///"), "worktree");
329 assert_eq!(sanitize_branch_name(""), "worktree");
330 assert_eq!(sanitize_branch_name("simple"), "simple");
331 }
332
333 #[test]
334 fn test_launch_method_roundtrip() {
335 for method in [
336 LaunchMethod::Foreground,
337 LaunchMethod::Detach,
338 LaunchMethod::ItermWindow,
339 LaunchMethod::Tmux,
340 LaunchMethod::Zellij,
341 LaunchMethod::WeztermTab,
342 ] {
343 let s = method.as_str();
344 assert_eq!(LaunchMethod::from_str_opt(s), Some(method));
345 }
346 }
347
348 #[test]
349 fn test_format_config_key() {
350 assert_eq!(
351 format_config_key(CONFIG_KEY_BASE_BRANCH, "fix-auth"),
352 "branch.fix-auth.worktreeBase"
353 );
354 }
355
356 #[test]
357 fn test_home_dir_or_fallback() {
358 let home = home_dir_or_fallback();
359 assert!(!home.as_os_str().is_empty());
361 }
362
363 #[test]
364 fn test_path_age_days() {
365 assert!(path_age_days(std::path::Path::new("/nonexistent/path")).is_none());
367
368 let tmp = std::env::temp_dir();
370 if let Some(age) = path_age_days(&tmp) {
371 assert!(age >= 0.0);
372 }
373 }
374
375 #[test]
376 fn test_preset_names_contents() {
377 assert!(PRESET_NAMES.contains(&"claude"));
378 assert!(PRESET_NAMES.contains(&"codex"));
379 assert!(PRESET_NAMES.contains(&"no-op"));
380 }
381
382 #[test]
383 fn test_to_bg_supported_methods() {
384 assert_eq!(LaunchMethod::Foreground.to_bg(), Some(LaunchMethod::Detach));
385 assert_eq!(
386 LaunchMethod::WeztermTab.to_bg(),
387 Some(LaunchMethod::WeztermTabBg)
388 );
389 }
390
391 #[test]
392 fn test_to_bg_unsupported_methods_silent_noop() {
393 assert_eq!(LaunchMethod::ItermTab.to_bg(), None);
396 assert_eq!(LaunchMethod::TmuxWindow.to_bg(), None);
397 assert_eq!(LaunchMethod::ZellijTab.to_bg(), None);
398 assert_eq!(LaunchMethod::Detach.to_bg(), None);
399 assert_eq!(LaunchMethod::WeztermTabBg.to_bg(), None);
400 }
401
402 #[test]
403 fn test_to_fg_supported_methods() {
404 assert_eq!(LaunchMethod::Detach.to_fg(), Some(LaunchMethod::Foreground));
405 assert_eq!(
406 LaunchMethod::WeztermTabBg.to_fg(),
407 Some(LaunchMethod::WeztermTab),
408 );
409 }
410
411 #[test]
412 fn test_to_fg_unsupported_methods_silent_noop() {
413 assert_eq!(LaunchMethod::ItermTab.to_fg(), None);
414 assert_eq!(LaunchMethod::Foreground.to_fg(), None);
415 assert_eq!(LaunchMethod::WeztermTab.to_fg(), None);
416 }
417
418 #[test]
419 fn test_bg_fg_roundtrip() {
420 for m in [LaunchMethod::Foreground, LaunchMethod::WeztermTab] {
422 assert_eq!(m.to_bg().and_then(|x| x.to_fg()), Some(m));
423 }
424 }
425
426 #[test]
427 fn test_version_meets_minimum() {
428 assert!(version_meets_minimum("2.31.0", 2, 31));
429 assert!(version_meets_minimum("2.40.0", 2, 31));
430 assert!(version_meets_minimum("3.0.0", 2, 31));
431 assert!(!version_meets_minimum("2.30.0", 2, 31));
432 assert!(!version_meets_minimum("1.99.0", 2, 31));
433 assert!(!version_meets_minimum("", 2, 31));
434 assert!(!version_meets_minimum("2", 2, 31));
435 }
436}