Skip to main content

git_worktree_manager/
constants.rs

1/// Constants and default values for git-worktree-manager.
2///
3use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5use std::sync::LazyLock;
6
7use regex::Regex;
8use serde::{Deserialize, Serialize};
9
10/// Pre-compiled regex patterns for branch name sanitization.
11static 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/// Terminal launch methods for AI tool execution.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[serde(rename_all = "kebab-case")]
19pub enum LaunchMethod {
20    Foreground,
21    Detach,
22    // iTerm (macOS)
23    ItermWindow,
24    ItermTab,
25    ItermPaneH,
26    ItermPaneV,
27    // tmux
28    Tmux,
29    TmuxWindow,
30    TmuxPaneH,
31    TmuxPaneV,
32    // Zellij
33    Zellij,
34    ZellijTab,
35    ZellijPaneH,
36    ZellijPaneV,
37    // WezTerm
38    WeztermWindow,
39    WeztermTab,
40    WeztermPaneH,
41    WeztermPaneV,
42}
43
44impl LaunchMethod {
45    /// Convert to the canonical kebab-case string.
46    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    /// Parse from a kebab-case string.
70    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 LaunchMethod {
96    /// Human-readable display name.
97    pub fn display_name(&self) -> &'static str {
98        match self {
99            Self::Foreground => "Foreground",
100            Self::Detach => "Detach (background)",
101            Self::ItermWindow => "iTerm2 — New Window",
102            Self::ItermTab => "iTerm2 — New Tab",
103            Self::ItermPaneH => "iTerm2 — Horizontal Pane",
104            Self::ItermPaneV => "iTerm2 — Vertical Pane",
105            Self::Tmux => "tmux — New Session",
106            Self::TmuxWindow => "tmux — New Window",
107            Self::TmuxPaneH => "tmux — Horizontal Pane",
108            Self::TmuxPaneV => "tmux — Vertical Pane",
109            Self::Zellij => "Zellij — New Session",
110            Self::ZellijTab => "Zellij — New Tab",
111            Self::ZellijPaneH => "Zellij — Horizontal Pane",
112            Self::ZellijPaneV => "Zellij — Vertical Pane",
113            Self::WeztermWindow => "WezTerm — New Window",
114            Self::WeztermTab => "WezTerm — New Tab",
115            Self::WeztermPaneH => "WezTerm — Horizontal Pane",
116            Self::WeztermPaneV => "WezTerm — Vertical Pane",
117        }
118    }
119}
120
121impl std::fmt::Display for LaunchMethod {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        f.write_str(self.as_str())
124    }
125}
126
127/// Build the alias map for launch methods.
128/// First letter: i=iTerm, t=tmux, z=Zellij, w=WezTerm
129/// Second: w=window, t=tab, p=pane
130/// For panes: h=horizontal, v=vertical
131pub fn launch_method_aliases() -> HashMap<&'static str, &'static str> {
132    HashMap::from([
133        ("fg", "foreground"),
134        ("d", "detach"),
135        // iTerm
136        ("i-w", "iterm-window"),
137        ("i-t", "iterm-tab"),
138        ("i-p-h", "iterm-pane-h"),
139        ("i-p-v", "iterm-pane-v"),
140        // tmux
141        ("t", "tmux"),
142        ("t-w", "tmux-window"),
143        ("t-p-h", "tmux-pane-h"),
144        ("t-p-v", "tmux-pane-v"),
145        // Zellij
146        ("z", "zellij"),
147        ("z-t", "zellij-tab"),
148        ("z-p-h", "zellij-pane-h"),
149        ("z-p-v", "zellij-pane-v"),
150        // WezTerm
151        ("w-w", "wezterm-window"),
152        ("w-t", "wezterm-tab"),
153        ("w-p-h", "wezterm-pane-h"),
154        ("w-p-v", "wezterm-pane-v"),
155    ])
156}
157
158/// Valid hook events for lifecycle hooks.
159pub const HOOK_EVENTS: &[&str] = &[
160    "worktree.pre_create",
161    "worktree.post_create",
162    "worktree.pre_delete",
163    "worktree.post_delete",
164    "merge.pre",
165    "merge.post",
166    "pr.pre",
167    "pr.post",
168    "resume.pre",
169    "resume.post",
170    "sync.pre",
171    "sync.post",
172];
173
174/// Available AI tool preset names.
175pub const PRESET_NAMES: &[&str] = &[
176    "claude",
177    "claude-remote",
178    "claude-yolo",
179    "claude-yolo-remote",
180    "codex",
181    "codex-yolo",
182    "no-op",
183];
184
185/// Return all valid `--term` values: canonical launch methods + aliases.
186pub fn all_term_values() -> Vec<&'static str> {
187    let mut values: Vec<&str> = vec![
188        "foreground",
189        "detach",
190        "iterm-window",
191        "iterm-tab",
192        "iterm-pane-h",
193        "iterm-pane-v",
194        "tmux",
195        "tmux-window",
196        "tmux-pane-h",
197        "tmux-pane-v",
198        "zellij",
199        "zellij-tab",
200        "zellij-pane-h",
201        "zellij-pane-v",
202        "wezterm-window",
203        "wezterm-tab",
204        "wezterm-pane-h",
205        "wezterm-pane-v",
206    ];
207    for alias in launch_method_aliases().keys() {
208        values.push(alias);
209    }
210    values.sort();
211    values
212}
213
214/// Seconds in one day (24 * 60 * 60).
215pub const SECS_PER_DAY: u64 = 86400;
216
217/// Seconds in one day as f64 (for floating-point age calculations).
218pub const SECS_PER_DAY_F64: f64 = 86400.0;
219
220/// Minimum required Git version for worktree features.
221pub const MIN_GIT_VERSION: &str = "2.31.0";
222
223/// Minimum Git major version.
224pub const MIN_GIT_VERSION_MAJOR: u32 = 2;
225
226/// Minimum Git minor version (when major == MIN_GIT_VERSION_MAJOR).
227pub const MIN_GIT_VERSION_MINOR: u32 = 31;
228
229/// Timeout in seconds for AI tool execution (e.g., PR description generation).
230pub const AI_TOOL_TIMEOUT_SECS: u64 = 60;
231
232/// Poll interval in milliseconds when waiting for AI tool completion.
233pub const AI_TOOL_POLL_MS: u64 = 100;
234
235/// Maximum session name length for tmux/zellij compatibility.
236/// Zellij uses Unix sockets which have a ~108 byte path limit.
237pub const MAX_SESSION_NAME_LENGTH: usize = 50;
238
239/// Claude native session path prefix length threshold.
240pub const CLAUDE_SESSION_PREFIX_LENGTH: usize = 200;
241
242/// Git config key templates for metadata storage.
243pub const CONFIG_KEY_BASE_BRANCH: &str = "branch.{}.worktreeBase";
244pub const CONFIG_KEY_BASE_PATH: &str = "worktree.{}.basePath";
245pub const CONFIG_KEY_INTENDED_BRANCH: &str = "worktree.{}.intendedBranch";
246
247/// Format a git config key by replacing `{}` with the branch name.
248pub fn format_config_key(template: &str, branch: &str) -> String {
249    template.replace("{}", branch)
250}
251
252/// Return the user's home directory, falling back to `"."` if unavailable.
253pub fn home_dir_or_fallback() -> PathBuf {
254    dirs::home_dir().unwrap_or_else(|| PathBuf::from("."))
255}
256
257/// Compute the age of a file in fractional days, or `None` on error.
258pub fn path_age_days(path: &Path) -> Option<f64> {
259    let mtime = path.metadata().and_then(|m| m.modified()).ok()?;
260    std::time::SystemTime::now()
261        .duration_since(mtime)
262        .ok()
263        .map(|d| d.as_secs_f64() / SECS_PER_DAY_F64)
264}
265
266/// Check if a semver version string meets a minimum (major, minor).
267pub fn version_meets_minimum(version_str: &str, min_major: u32, min_minor: u32) -> bool {
268    let parts: Vec<u32> = version_str
269        .split('.')
270        .filter_map(|p| p.parse().ok())
271        .collect();
272    parts.len() >= 2 && (parts[0] > min_major || (parts[0] == min_major && parts[1] >= min_minor))
273}
274
275/// Convert branch name to safe directory name.
276///
277/// Handles branch names with slashes (feat/auth), special characters,
278/// and other filesystem-unsafe characters.
279///
280/// # Examples
281/// ```
282/// use git_worktree_manager::constants::sanitize_branch_name;
283/// assert_eq!(sanitize_branch_name("feat/auth"), "feat-auth");
284/// assert_eq!(sanitize_branch_name("feature/user@login"), "feature-user-login");
285/// assert_eq!(sanitize_branch_name("hotfix/v2.0"), "hotfix-v2.0");
286/// ```
287pub fn sanitize_branch_name(branch_name: &str) -> String {
288    let safe = UNSAFE_RE.replace_all(branch_name, "-");
289    let safe = WHITESPACE_RE.replace_all(&safe, "-");
290    let safe = MULTI_HYPHEN_RE.replace_all(&safe, "-");
291    let safe = safe.trim_matches('-');
292
293    if safe.is_empty() {
294        "worktree".to_string()
295    } else {
296        safe.to_string()
297    }
298}
299
300/// Generate default worktree path: `../<repo>-<branch>`.
301pub fn default_worktree_path(repo_path: &Path, branch_name: &str) -> PathBuf {
302    let repo_path = strip_unc(
303        repo_path
304            .canonicalize()
305            .unwrap_or_else(|_| repo_path.to_path_buf()),
306    );
307    let safe_branch = sanitize_branch_name(branch_name);
308    let repo_name = repo_path
309        .file_name()
310        .map(|n| n.to_string_lossy().to_string())
311        .unwrap_or_else(|| "repo".to_string());
312
313    repo_path
314        .parent()
315        .unwrap_or(repo_path.as_path())
316        .join(format!("{}-{}", repo_name, safe_branch))
317}
318
319/// Strip Windows UNC path prefix (`\\?\`) which `canonicalize()` adds.
320/// Git doesn't understand UNC paths, so we must strip them.
321pub fn strip_unc(path: PathBuf) -> PathBuf {
322    #[cfg(target_os = "windows")]
323    {
324        let s = path.to_string_lossy();
325        if let Some(stripped) = s.strip_prefix(r"\\?\") {
326            return PathBuf::from(stripped);
327        }
328    }
329    path
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn test_sanitize_branch_name() {
338        assert_eq!(sanitize_branch_name("feat/auth"), "feat-auth");
339        assert_eq!(sanitize_branch_name("bugfix/issue-123"), "bugfix-issue-123");
340        assert_eq!(
341            sanitize_branch_name("feature/user@login"),
342            "feature-user-login"
343        );
344        assert_eq!(sanitize_branch_name("hotfix/v2.0"), "hotfix-v2.0");
345        assert_eq!(sanitize_branch_name("///"), "worktree");
346        assert_eq!(sanitize_branch_name(""), "worktree");
347        assert_eq!(sanitize_branch_name("simple"), "simple");
348    }
349
350    #[test]
351    fn test_launch_method_roundtrip() {
352        for method in [
353            LaunchMethod::Foreground,
354            LaunchMethod::Detach,
355            LaunchMethod::ItermWindow,
356            LaunchMethod::Tmux,
357            LaunchMethod::Zellij,
358            LaunchMethod::WeztermTab,
359        ] {
360            let s = method.as_str();
361            assert_eq!(LaunchMethod::from_str_opt(s), Some(method));
362        }
363    }
364
365    #[test]
366    fn test_format_config_key() {
367        assert_eq!(
368            format_config_key(CONFIG_KEY_BASE_BRANCH, "fix-auth"),
369            "branch.fix-auth.worktreeBase"
370        );
371    }
372
373    #[test]
374    fn test_home_dir_or_fallback() {
375        let home = home_dir_or_fallback();
376        // Should return a non-empty path (either real home or ".")
377        assert!(!home.as_os_str().is_empty());
378    }
379
380    #[test]
381    fn test_path_age_days() {
382        // Non-existent path returns None
383        assert!(path_age_days(std::path::Path::new("/nonexistent/path")).is_none());
384
385        // Existing path returns Some with non-negative value
386        let tmp = std::env::temp_dir();
387        if let Some(age) = path_age_days(&tmp) {
388            assert!(age >= 0.0);
389        }
390    }
391
392    #[test]
393    fn test_all_term_values_contains_canonical_and_aliases() {
394        let values = all_term_values();
395        // 18 canonical + aliases
396        assert!(
397            values.len() >= 36,
398            "expected ≥36 term values, got {}",
399            values.len()
400        );
401        // Check a few canonical values
402        assert!(values.contains(&"foreground"));
403        assert!(values.contains(&"tmux"));
404        assert!(values.contains(&"wezterm-tab"));
405        // Check a few aliases
406        assert!(values.contains(&"fg"));
407        assert!(values.contains(&"t"));
408        assert!(values.contains(&"w-t"));
409    }
410
411    #[test]
412    fn test_hook_events_not_empty() {
413        assert!(!HOOK_EVENTS.is_empty());
414        assert!(HOOK_EVENTS.contains(&"worktree.post_create"));
415        assert!(HOOK_EVENTS.contains(&"merge.pre"));
416    }
417
418    #[test]
419    fn test_preset_names_not_empty() {
420        assert!(!PRESET_NAMES.is_empty());
421        assert!(PRESET_NAMES.contains(&"claude"));
422        assert!(PRESET_NAMES.contains(&"codex"));
423        assert!(PRESET_NAMES.contains(&"no-op"));
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}