git-worktree-manager 0.0.31

CLI tool integrating git worktree with AI coding assistants
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/// Constants and default values for git-worktree-manager.
///
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use regex::Regex;
use serde::{Deserialize, Serialize};

/// Pre-compiled regex patterns for branch name sanitization.
static UNSAFE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"[/<>:"|?*\\#@&;$`!~%^()\[\]{}=+]+"#).unwrap());
static WHITESPACE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
static MULTI_HYPHEN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-+").unwrap());

/// Terminal launch methods for AI tool execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum LaunchMethod {
    Foreground,
    Detach,
    // iTerm (macOS)
    ItermWindow,
    ItermTab,
    ItermPaneH,
    ItermPaneV,
    // tmux
    Tmux,
    TmuxWindow,
    TmuxPaneH,
    TmuxPaneV,
    // Zellij
    Zellij,
    ZellijTab,
    ZellijPaneH,
    ZellijPaneV,
    // WezTerm
    WeztermWindow,
    WeztermTab,
    WeztermPaneH,
    WeztermPaneV,
    WeztermTabBg,
}

impl LaunchMethod {
    /// Convert to the canonical kebab-case string.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Foreground => "foreground",
            Self::Detach => "detach",
            Self::ItermWindow => "iterm-window",
            Self::ItermTab => "iterm-tab",
            Self::ItermPaneH => "iterm-pane-h",
            Self::ItermPaneV => "iterm-pane-v",
            Self::Tmux => "tmux",
            Self::TmuxWindow => "tmux-window",
            Self::TmuxPaneH => "tmux-pane-h",
            Self::TmuxPaneV => "tmux-pane-v",
            Self::Zellij => "zellij",
            Self::ZellijTab => "zellij-tab",
            Self::ZellijPaneH => "zellij-pane-h",
            Self::ZellijPaneV => "zellij-pane-v",
            Self::WeztermWindow => "wezterm-window",
            Self::WeztermTab => "wezterm-tab",
            Self::WeztermPaneH => "wezterm-pane-h",
            Self::WeztermPaneV => "wezterm-pane-v",
            Self::WeztermTabBg => "wezterm-tab-bg",
        }
    }

    /// Parse from a kebab-case string.
    pub fn from_str_opt(s: &str) -> Option<Self> {
        match s {
            "foreground" => Some(Self::Foreground),
            "detach" => Some(Self::Detach),
            "iterm-window" => Some(Self::ItermWindow),
            "iterm-tab" => Some(Self::ItermTab),
            "iterm-pane-h" => Some(Self::ItermPaneH),
            "iterm-pane-v" => Some(Self::ItermPaneV),
            "tmux" => Some(Self::Tmux),
            "tmux-window" => Some(Self::TmuxWindow),
            "tmux-pane-h" => Some(Self::TmuxPaneH),
            "tmux-pane-v" => Some(Self::TmuxPaneV),
            "zellij" => Some(Self::Zellij),
            "zellij-tab" => Some(Self::ZellijTab),
            "zellij-pane-h" => Some(Self::ZellijPaneH),
            "zellij-pane-v" => Some(Self::ZellijPaneV),
            "wezterm-window" => Some(Self::WeztermWindow),
            "wezterm-tab" => Some(Self::WeztermTab),
            "wezterm-pane-h" => Some(Self::WeztermPaneH),
            "wezterm-pane-v" => Some(Self::WeztermPaneV),
            "wezterm-tab-bg" => Some(Self::WeztermTabBg),
            _ => None,
        }
    }
}

impl LaunchMethod {
    /// Human-readable display name.
    pub fn display_name(&self) -> &'static str {
        match self {
            Self::Foreground => "Foreground",
            Self::Detach => "Detach (background)",
            Self::ItermWindow => "iTerm2 — New Window",
            Self::ItermTab => "iTerm2 — New Tab",
            Self::ItermPaneH => "iTerm2 — Horizontal Pane",
            Self::ItermPaneV => "iTerm2 — Vertical Pane",
            Self::Tmux => "tmux — New Session",
            Self::TmuxWindow => "tmux — New Window",
            Self::TmuxPaneH => "tmux — Horizontal Pane",
            Self::TmuxPaneV => "tmux — Vertical Pane",
            Self::Zellij => "Zellij — New Session",
            Self::ZellijTab => "Zellij — New Tab",
            Self::ZellijPaneH => "Zellij — Horizontal Pane",
            Self::ZellijPaneV => "Zellij — Vertical Pane",
            Self::WeztermWindow => "WezTerm — New Window",
            Self::WeztermTab => "WezTerm — New Tab",
            Self::WeztermPaneH => "WezTerm — Horizontal Pane",
            Self::WeztermPaneV => "WezTerm — Vertical Pane",
            Self::WeztermTabBg => "WezTerm — New Tab (Background)",
        }
    }
}

impl std::fmt::Display for LaunchMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Build the alias map for launch methods.
/// First letter: i=iTerm, t=tmux, z=Zellij, w=WezTerm
/// Second: w=window, t=tab, p=pane
/// For panes: h=horizontal, v=vertical
pub fn launch_method_aliases() -> HashMap<&'static str, &'static str> {
    HashMap::from([
        ("fg", "foreground"),
        ("d", "detach"),
        // iTerm
        ("i-w", "iterm-window"),
        ("i-t", "iterm-tab"),
        ("i-p-h", "iterm-pane-h"),
        ("i-p-v", "iterm-pane-v"),
        // tmux
        ("t", "tmux"),
        ("t-w", "tmux-window"),
        ("t-p-h", "tmux-pane-h"),
        ("t-p-v", "tmux-pane-v"),
        // Zellij
        ("z", "zellij"),
        ("z-t", "zellij-tab"),
        ("z-p-h", "zellij-pane-h"),
        ("z-p-v", "zellij-pane-v"),
        // WezTerm
        ("w-w", "wezterm-window"),
        ("w-t", "wezterm-tab"),
        ("w-p-h", "wezterm-pane-h"),
        ("w-p-v", "wezterm-pane-v"),
        ("w-t-b", "wezterm-tab-bg"),
    ])
}

/// Valid hook events for lifecycle hooks.
pub const HOOK_EVENTS: &[&str] = &[
    "worktree.pre_create",
    "worktree.post_create",
    "worktree.pre_delete",
    "worktree.post_delete",
    "merge.pre",
    "merge.post",
    "pr.pre",
    "pr.post",
    "resume.pre",
    "resume.post",
    "sync.pre",
    "sync.post",
];

/// Available AI tool preset names.
pub const PRESET_NAMES: &[&str] = &[
    "claude",
    "claude-remote",
    "claude-yolo",
    "claude-yolo-remote",
    "codex",
    "codex-yolo",
    "no-op",
];

/// Return all valid `--term` values: canonical launch methods + aliases.
pub fn all_term_values() -> Vec<&'static str> {
    let mut values: Vec<&str> = vec![
        "foreground",
        "detach",
        "iterm-window",
        "iterm-tab",
        "iterm-pane-h",
        "iterm-pane-v",
        "tmux",
        "tmux-window",
        "tmux-pane-h",
        "tmux-pane-v",
        "zellij",
        "zellij-tab",
        "zellij-pane-h",
        "zellij-pane-v",
        "wezterm-window",
        "wezterm-tab",
        "wezterm-tab-bg",
        "wezterm-pane-h",
        "wezterm-pane-v",
    ];
    for alias in launch_method_aliases().keys() {
        values.push(alias);
    }
    values.sort();
    values
}

/// Seconds in one day (24 * 60 * 60).
pub const SECS_PER_DAY: u64 = 86400;

/// Seconds in one day as f64 (for floating-point age calculations).
pub const SECS_PER_DAY_F64: f64 = 86400.0;

/// Minimum required Git version for worktree features.
pub const MIN_GIT_VERSION: &str = "2.31.0";

/// Minimum Git major version.
pub const MIN_GIT_VERSION_MAJOR: u32 = 2;

/// Minimum Git minor version (when major == MIN_GIT_VERSION_MAJOR).
pub const MIN_GIT_VERSION_MINOR: u32 = 31;

/// Timeout in seconds for AI tool execution (e.g., PR description generation).
pub const AI_TOOL_TIMEOUT_SECS: u64 = 60;

/// Poll interval in milliseconds when waiting for AI tool completion.
pub const AI_TOOL_POLL_MS: u64 = 100;

/// Maximum session name length for tmux/zellij compatibility.
/// Zellij uses Unix sockets which have a ~108 byte path limit.
pub const MAX_SESSION_NAME_LENGTH: usize = 50;

/// Claude native session path prefix length threshold.
pub const CLAUDE_SESSION_PREFIX_LENGTH: usize = 200;

/// Git config key templates for metadata storage.
pub const CONFIG_KEY_BASE_BRANCH: &str = "branch.{}.worktreeBase";
pub const CONFIG_KEY_BASE_PATH: &str = "worktree.{}.basePath";
pub const CONFIG_KEY_INTENDED_BRANCH: &str = "worktree.{}.intendedBranch";

/// Format a git config key by replacing `{}` with the branch name.
pub fn format_config_key(template: &str, branch: &str) -> String {
    template.replace("{}", branch)
}

/// Return the user's home directory, falling back to `"."` if unavailable.
pub fn home_dir_or_fallback() -> PathBuf {
    dirs::home_dir().unwrap_or_else(|| PathBuf::from("."))
}

/// Compute the age of a file in fractional days, or `None` on error.
pub fn path_age_days(path: &Path) -> Option<f64> {
    let mtime = path.metadata().and_then(|m| m.modified()).ok()?;
    std::time::SystemTime::now()
        .duration_since(mtime)
        .ok()
        .map(|d| d.as_secs_f64() / SECS_PER_DAY_F64)
}

/// Check if a semver version string meets a minimum (major, minor).
pub fn version_meets_minimum(version_str: &str, min_major: u32, min_minor: u32) -> bool {
    let parts: Vec<u32> = version_str
        .split('.')
        .filter_map(|p| p.parse().ok())
        .collect();
    parts.len() >= 2 && (parts[0] > min_major || (parts[0] == min_major && parts[1] >= min_minor))
}

/// Convert branch name to safe directory name.
///
/// Handles branch names with slashes (feat/auth), special characters,
/// and other filesystem-unsafe characters.
///
/// # Examples
/// ```
/// use git_worktree_manager::constants::sanitize_branch_name;
/// assert_eq!(sanitize_branch_name("feat/auth"), "feat-auth");
/// assert_eq!(sanitize_branch_name("feature/user@login"), "feature-user-login");
/// assert_eq!(sanitize_branch_name("hotfix/v2.0"), "hotfix-v2.0");
/// ```
pub fn sanitize_branch_name(branch_name: &str) -> String {
    let safe = UNSAFE_RE.replace_all(branch_name, "-");
    let safe = WHITESPACE_RE.replace_all(&safe, "-");
    let safe = MULTI_HYPHEN_RE.replace_all(&safe, "-");
    let safe = safe.trim_matches('-');

    if safe.is_empty() {
        "worktree".to_string()
    } else {
        safe.to_string()
    }
}

/// Generate default worktree path: `../<repo>-<branch>`.
pub fn default_worktree_path(repo_path: &Path, branch_name: &str) -> PathBuf {
    let repo_path = strip_unc(
        repo_path
            .canonicalize()
            .unwrap_or_else(|_| repo_path.to_path_buf()),
    );
    let safe_branch = sanitize_branch_name(branch_name);
    let repo_name = repo_path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| "repo".to_string());

    repo_path
        .parent()
        .unwrap_or(repo_path.as_path())
        .join(format!("{}-{}", repo_name, safe_branch))
}

/// Strip Windows UNC path prefix (`\\?\`) which `canonicalize()` adds.
/// Git doesn't understand UNC paths, so we must strip them.
pub fn strip_unc(path: PathBuf) -> PathBuf {
    #[cfg(target_os = "windows")]
    {
        let s = path.to_string_lossy();
        if let Some(stripped) = s.strip_prefix(r"\\?\") {
            return PathBuf::from(stripped);
        }
    }
    path
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sanitize_branch_name() {
        assert_eq!(sanitize_branch_name("feat/auth"), "feat-auth");
        assert_eq!(sanitize_branch_name("bugfix/issue-123"), "bugfix-issue-123");
        assert_eq!(
            sanitize_branch_name("feature/user@login"),
            "feature-user-login"
        );
        assert_eq!(sanitize_branch_name("hotfix/v2.0"), "hotfix-v2.0");
        assert_eq!(sanitize_branch_name("///"), "worktree");
        assert_eq!(sanitize_branch_name(""), "worktree");
        assert_eq!(sanitize_branch_name("simple"), "simple");
    }

    #[test]
    fn test_launch_method_roundtrip() {
        for method in [
            LaunchMethod::Foreground,
            LaunchMethod::Detach,
            LaunchMethod::ItermWindow,
            LaunchMethod::Tmux,
            LaunchMethod::Zellij,
            LaunchMethod::WeztermTab,
        ] {
            let s = method.as_str();
            assert_eq!(LaunchMethod::from_str_opt(s), Some(method));
        }
    }

    #[test]
    fn test_format_config_key() {
        assert_eq!(
            format_config_key(CONFIG_KEY_BASE_BRANCH, "fix-auth"),
            "branch.fix-auth.worktreeBase"
        );
    }

    #[test]
    fn test_home_dir_or_fallback() {
        let home = home_dir_or_fallback();
        // Should return a non-empty path (either real home or ".")
        assert!(!home.as_os_str().is_empty());
    }

    #[test]
    fn test_path_age_days() {
        // Non-existent path returns None
        assert!(path_age_days(std::path::Path::new("/nonexistent/path")).is_none());

        // Existing path returns Some with non-negative value
        let tmp = std::env::temp_dir();
        if let Some(age) = path_age_days(&tmp) {
            assert!(age >= 0.0);
        }
    }

    #[test]
    fn test_all_term_values_contains_canonical_and_aliases() {
        let values = all_term_values();
        // 19 canonical + aliases
        assert!(
            values.len() >= 36,
            "expected ≥36 term values, got {}",
            values.len()
        );
        // Check a few canonical values
        assert!(values.contains(&"foreground"));
        assert!(values.contains(&"tmux"));
        assert!(values.contains(&"wezterm-tab"));
        // Check a few aliases
        assert!(values.contains(&"fg"));
        assert!(values.contains(&"t"));
        assert!(values.contains(&"w-t"));
    }

    #[test]
    fn test_hook_events_not_empty() {
        assert!(!HOOK_EVENTS.is_empty());
        assert!(HOOK_EVENTS.contains(&"worktree.post_create"));
        assert!(HOOK_EVENTS.contains(&"merge.pre"));
    }

    #[test]
    fn test_preset_names_not_empty() {
        assert!(!PRESET_NAMES.is_empty());
        assert!(PRESET_NAMES.contains(&"claude"));
        assert!(PRESET_NAMES.contains(&"codex"));
        assert!(PRESET_NAMES.contains(&"no-op"));
    }

    #[test]
    fn test_version_meets_minimum() {
        assert!(version_meets_minimum("2.31.0", 2, 31));
        assert!(version_meets_minimum("2.40.0", 2, 31));
        assert!(version_meets_minimum("3.0.0", 2, 31));
        assert!(!version_meets_minimum("2.30.0", 2, 31));
        assert!(!version_meets_minimum("1.99.0", 2, 31));
        assert!(!version_meets_minimum("", 2, 31));
        assert!(!version_meets_minimum("2", 2, 31));
    }
}