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    WeztermTabBg,
43}
44
45impl LaunchMethod {
46    /// Convert to the canonical kebab-case string.
47    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    /// Parse from a kebab-case string.
72    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    /// Return the background variant of this launch method, if one exists.
100    /// `--bg` uses this; methods without a paired variant are left unchanged
101    /// upstream (silent no-op).
102    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    /// Return the foreground variant of this launch method, if one exists.
111    /// Inverse of `to_bg`.
112    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    /// Human-readable display name.
123    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
154/// Build the alias map for launch methods.
155/// First letter: i=iTerm, t=tmux, z=Zellij, w=WezTerm
156/// Second: w=window, t=tab, p=pane
157/// For panes: h=horizontal, v=vertical
158pub fn launch_method_aliases() -> HashMap<&'static str, &'static str> {
159    HashMap::from([
160        ("fg", "foreground"),
161        ("d", "detach"),
162        // iTerm
163        ("i-w", "iterm-window"),
164        ("i-t", "iterm-tab"),
165        ("i-p-h", "iterm-pane-h"),
166        ("i-p-v", "iterm-pane-v"),
167        // tmux
168        ("t", "tmux"),
169        ("t-w", "tmux-window"),
170        ("t-p-h", "tmux-pane-h"),
171        ("t-p-v", "tmux-pane-v"),
172        // Zellij
173        ("z", "zellij"),
174        ("z-t", "zellij-tab"),
175        ("z-p-h", "zellij-pane-h"),
176        ("z-p-v", "zellij-pane-v"),
177        // WezTerm
178        ("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
186/// Available AI tool preset names.
187pub 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
197/// Seconds in one day (24 * 60 * 60).
198pub const SECS_PER_DAY: u64 = 86400;
199
200/// Seconds in one day as f64 (for floating-point age calculations).
201pub const SECS_PER_DAY_F64: f64 = 86400.0;
202
203/// Minimum required Git version for worktree features.
204pub const MIN_GIT_VERSION: &str = "2.31.0";
205
206/// Minimum Git major version.
207pub const MIN_GIT_VERSION_MAJOR: u32 = 2;
208
209/// Minimum Git minor version (when major == MIN_GIT_VERSION_MAJOR).
210pub const MIN_GIT_VERSION_MINOR: u32 = 31;
211
212/// Timeout in seconds for AI tool execution (e.g., PR description generation).
213pub const AI_TOOL_TIMEOUT_SECS: u64 = 60;
214
215/// Poll interval in milliseconds when waiting for AI tool completion.
216pub const AI_TOOL_POLL_MS: u64 = 100;
217
218/// Maximum session name length for tmux/zellij compatibility.
219/// Zellij uses Unix sockets which have a ~108 byte path limit.
220pub const MAX_SESSION_NAME_LENGTH: usize = 50;
221
222/// Claude native session path prefix length threshold.
223pub const CLAUDE_SESSION_PREFIX_LENGTH: usize = 200;
224
225/// Git config key templates for metadata storage.
226pub 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
230/// Format a git config key by replacing `{}` with the branch name.
231pub fn format_config_key(template: &str, branch: &str) -> String {
232    template.replace("{}", branch)
233}
234
235/// Return the user's home directory, falling back to `"."` if unavailable.
236pub fn home_dir_or_fallback() -> PathBuf {
237    dirs::home_dir().unwrap_or_else(|| PathBuf::from("."))
238}
239
240/// Compute the age of a file in fractional days, or `None` on error.
241pub 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
249/// Check if a semver version string meets a minimum (major, minor).
250pub 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
258/// Convert branch name to safe directory name.
259///
260/// Handles branch names with slashes (feat/auth), special characters,
261/// and other filesystem-unsafe characters.
262///
263/// # Examples
264/// ```
265/// use git_worktree_manager::constants::sanitize_branch_name;
266/// assert_eq!(sanitize_branch_name("feat/auth"), "feat-auth");
267/// assert_eq!(sanitize_branch_name("feature/user@login"), "feature-user-login");
268/// assert_eq!(sanitize_branch_name("hotfix/v2.0"), "hotfix-v2.0");
269/// ```
270pub 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
283/// Generate default worktree path: `../<repo>-<branch>`.
284pub 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
302/// Strip Windows UNC path prefix (`\\?\`) which `canonicalize()` adds.
303/// Git doesn't understand UNC paths, so we must strip them.
304pub 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        // Should return a non-empty path (either real home or ".")
360        assert!(!home.as_os_str().is_empty());
361    }
362
363    #[test]
364    fn test_path_age_days() {
365        // Non-existent path returns None
366        assert!(path_age_days(std::path::Path::new("/nonexistent/path")).is_none());
367
368        // Existing path returns Some with non-negative value
369        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        // Unsupported launchers return None so the caller leaves the method
394        // unchanged instead of erroring.
395        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        // bg ∘ fg should return the original method for paired variants.
421        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}