git-paw 0.3.0

Parallel AI Worktrees — orchestrate multiple AI coding CLI sessions across git worktrees
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Git operations.
//!
//! Validates git repositories, lists branches, creates and removes worktrees,
//! and derives worktree directory names from project and branch names.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::error::PawError;

/// Validates that the given path is inside a git repository.
///
/// Returns the absolute path to the repository root.
pub fn validate_repo(path: &Path) -> Result<PathBuf, PawError> {
    let output = Command::new("git")
        .current_dir(path)
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .map_err(|e| PawError::BranchError(format!("failed to run git: {e}")))?;

    if !output.status.success() {
        return Err(PawError::NotAGitRepo);
    }

    let root = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(PathBuf::from(root))
}

/// Lists all branches (local and remote), deduplicated, sorted, with remote
/// prefixes stripped.
///
/// Remote branches like `origin/main` are included as `main`. If a branch
/// exists both locally and remotely, only one entry appears. `HEAD` pointers
/// are excluded.
pub fn list_branches(repo_root: &Path) -> Result<Vec<String>, PawError> {
    let output = Command::new("git")
        .current_dir(repo_root)
        .args(["branch", "-a", "--format=%(refname:short)"])
        .output()
        .map_err(|e| PawError::BranchError(format!("failed to run git branch: {e}")))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(PawError::BranchError(format!(
            "git branch failed: {stderr}"
        )));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    Ok(parse_branch_output(&stdout))
}

/// Parses `git branch -a --format=%(refname:short)` output into a
/// deduplicated, sorted list of branch names with remote prefixes stripped.
fn parse_branch_output(output: &str) -> Vec<String> {
    let mut branches = BTreeSet::new();

    for line in output.lines() {
        let name = line.trim();
        if name.is_empty() {
            continue;
        }
        // Skip HEAD pointers like "origin/HEAD"
        if name.contains("HEAD") {
            continue;
        }
        // Strip remote prefix (e.g., "origin/feature/auth" → "feature/auth")
        let stripped = strip_remote_prefix(name);
        branches.insert(stripped.to_string());
    }

    branches.into_iter().collect()
}

/// Strips the remote prefix from a branch name.
///
/// `origin/feature/auth` becomes `feature/auth`.
/// `feature/auth` stays as `feature/auth`.
fn strip_remote_prefix(branch: &str) -> &str {
    // With --format=%(refname:short), remote branches appear as "origin/branch"
    // We need to strip the first component if it looks like a remote name
    if let Some(rest) = branch.strip_prefix("origin/") {
        rest
    } else {
        branch
    }
}

/// Derives the project name from the repository root path.
///
/// Uses the final component of the path (the directory name).
pub fn project_name(repo_root: &Path) -> String {
    repo_root.file_name().map_or_else(
        || "project".to_string(),
        |n| n.to_string_lossy().to_string(),
    )
}

/// Builds the worktree directory name from a project name and branch.
///
/// Replaces `/` with `-` and strips characters that are unsafe for directory
/// names.
///
/// # Examples
///
/// - `("git-paw", "feature/auth-flow")` → `"git-paw-feature-auth-flow"`
/// - `("git-paw", "fix/db")` → `"git-paw-fix-db"`
pub fn worktree_dir_name(project: &str, branch: &str) -> String {
    let sanitized: String = branch
        .chars()
        .map(|c| if c == '/' { '-' } else { c })
        .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_' || *c == '.')
        .collect();

    format!("{project}-{sanitized}")
}

/// Prunes stale worktree registrations.
///
/// Runs `git worktree prune` to clean up references to worktrees whose
/// directories no longer exist. This prevents "already registered worktree"
/// errors when recreating worktrees after a previous session was purged.
pub fn prune_worktrees(repo_root: &Path) -> Result<(), PawError> {
    let output = Command::new("git")
        .current_dir(repo_root)
        .args(["worktree", "prune"])
        .output()
        .map_err(|e| PawError::WorktreeError(format!("failed to run git worktree prune: {e}")))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(PawError::WorktreeError(format!(
            "git worktree prune failed: {stderr}"
        )));
    }
    Ok(())
}

/// Creates a git worktree for the given branch.
///
/// The worktree is placed in the parent directory of `repo_root`, named using
/// [`worktree_dir_name`]. Returns the path to the created worktree.
/// Result of creating a worktree, including whether the branch was newly created.
#[derive(Debug)]
pub struct WorktreeCreation {
    /// Path to the created worktree directory.
    pub path: PathBuf,
    /// Whether git-paw created the branch (true) or it already existed (false).
    pub branch_created: bool,
}

/// Creates a git worktree for `branch`.
///
/// If the branch already exists, checks it out in a new worktree. If the
/// branch does not exist, creates it from HEAD with `git worktree add -b`.
/// Returns both the worktree path and whether the branch was newly created,
/// so the session can track which branches to delete on purge.
pub fn create_worktree(repo_root: &Path, branch: &str) -> Result<WorktreeCreation, PawError> {
    let project = project_name(repo_root);
    let dir_name = worktree_dir_name(&project, branch);

    let parent = repo_root.parent().ok_or_else(|| {
        PawError::WorktreeError("cannot determine parent directory of repo".to_string())
    })?;
    let worktree_path = parent.join(&dir_name);

    // Try with existing branch first.
    let output = Command::new("git")
        .current_dir(repo_root)
        .args(["worktree", "add", &worktree_path.to_string_lossy(), branch])
        .output()
        .map_err(|e| PawError::WorktreeError(format!("failed to run git worktree add: {e}")))?;

    if output.status.success() {
        return Ok(WorktreeCreation {
            path: worktree_path,
            branch_created: false,
        });
    }

    let stderr = String::from_utf8_lossy(&output.stderr);

    // If the branch doesn't exist, create it with -b.
    if stderr.contains("invalid reference") {
        let output = Command::new("git")
            .current_dir(repo_root)
            .args([
                "worktree",
                "add",
                "-b",
                branch,
                &worktree_path.to_string_lossy(),
            ])
            .output()
            .map_err(|e| {
                PawError::WorktreeError(format!("failed to run git worktree add -b: {e}"))
            })?;

        if output.status.success() {
            return Ok(WorktreeCreation {
                path: worktree_path,
                branch_created: true,
            });
        }

        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(PawError::WorktreeError(format!(
            "git worktree add -b failed for branch '{branch}': {stderr}"
        )));
    }

    Err(PawError::WorktreeError(format!(
        "git worktree add failed for branch '{branch}': {stderr}"
    )))
}

/// Deletes a local git branch.
///
/// Uses `git branch -D` (force delete) because purge is a destructive
/// operation and the user has already confirmed. Only call this for branches
/// that git-paw created (tracked via `WorktreeEntry::branch_created`).
pub fn delete_branch(repo_root: &Path, branch: &str) -> Result<(), PawError> {
    let output = Command::new("git")
        .current_dir(repo_root)
        .args(["branch", "-D", branch])
        .output()
        .map_err(|e| PawError::BranchError(format!("failed to run git branch -D: {e}")))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(PawError::BranchError(format!(
            "git branch -D failed for '{branch}': {stderr}"
        )));
    }

    Ok(())
}

/// Removes a git worktree at the given path.
///
/// Runs `git worktree remove --force` and then prunes stale worktree entries.
pub fn remove_worktree(repo_root: &Path, worktree_path: &Path) -> Result<(), PawError> {
    let output = Command::new("git")
        .current_dir(repo_root)
        .args([
            "worktree",
            "remove",
            "--force",
            &worktree_path.to_string_lossy(),
        ])
        .output()
        .map_err(|e| PawError::WorktreeError(format!("failed to run git worktree remove: {e}")))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(PawError::WorktreeError(format!(
            "git worktree remove failed: {stderr}"
        )));
    }

    // Prune stale worktree entries
    let _ = Command::new("git")
        .current_dir(repo_root)
        .args(["worktree", "prune"])
        .output();

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;
    use std::process::Command;
    use tempfile::TempDir;

    /// A test sandbox that owns an outer temp directory containing the git
    /// repo. Worktrees created via `create_worktree` land as siblings of the
    /// repo inside this outer dir, so everything is cleaned up when the
    /// sandbox is dropped — even if a test panics.
    struct TestRepo {
        _sandbox: TempDir,
        repo: PathBuf,
    }

    impl TestRepo {
        fn path(&self) -> &Path {
            &self.repo
        }
    }

    /// Creates a temporary git repository inside a sandbox directory.
    ///
    /// The repo lives at `<sandbox>/repo/` so that worktrees created at
    /// `../<project>-<branch>/` land inside `<sandbox>/` and are automatically
    /// cleaned up when the returned `TestRepo` is dropped.
    fn setup_test_repo() -> TestRepo {
        let sandbox = TempDir::new().expect("create sandbox dir");
        let repo = sandbox.path().join("repo");
        std::fs::create_dir(&repo).expect("create repo dir");

        Command::new("git")
            .current_dir(&repo)
            .args(["init"])
            .output()
            .expect("git init");

        Command::new("git")
            .current_dir(&repo)
            .args(["config", "user.email", "test@test.com"])
            .output()
            .expect("git config email");

        Command::new("git")
            .current_dir(&repo)
            .args(["config", "user.name", "Test"])
            .output()
            .expect("git config name");

        // Create initial commit so branches work
        std::fs::write(repo.join("README.md"), "# test").expect("write file");
        Command::new("git")
            .current_dir(&repo)
            .args(["add", "."])
            .output()
            .expect("git add");
        Command::new("git")
            .current_dir(&repo)
            .args(["commit", "-m", "initial"])
            .output()
            .expect("git commit");

        TestRepo {
            _sandbox: sandbox,
            repo,
        }
    }

    // --- validate_repo ---
    // Behavioral: tests the public contract — given a path, does the system
    // correctly identify whether it's inside a git repo and return the root?

    #[test]
    #[serial]
    fn validate_repo_returns_root_inside_repo() {
        let repo = setup_test_repo();
        let result = validate_repo(repo.path());
        assert!(result.is_ok());
        let root = result.unwrap();
        // The returned root should match the repo dir (canonicalize for symlinks)
        assert_eq!(
            root.canonicalize().unwrap(),
            repo.path().canonicalize().unwrap()
        );
    }

    #[test]
    #[serial]
    fn validate_repo_returns_not_a_git_repo_outside() {
        let dir = TempDir::new().expect("create temp dir");
        let result = validate_repo(dir.path());
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, PawError::NotAGitRepo),
            "expected NotAGitRepo, got: {err}"
        );
    }

    // --- list_branches ---
    // Behavioral: tests the public function against a real git repo.
    // Deduplication and remote-prefix stripping are covered in integration tests
    // (list_branches_strips_remote_prefix_and_deduplicates) using a real remote.

    #[test]
    #[serial]
    fn list_branches_returns_sorted_branches() {
        let repo = setup_test_repo();

        // Create branches in non-alphabetical order
        for branch in ["zebra", "alpha", "feature/auth"] {
            Command::new("git")
                .current_dir(repo.path())
                .args(["branch", branch])
                .output()
                .expect("create branch");
        }

        let branches = list_branches(repo.path()).expect("list branches");

        // The default branch name depends on git config (main or master)
        let default_branch = branches
            .iter()
            .find(|b| *b == "main" || *b == "master")
            .expect("should have a default branch")
            .clone();

        let mut expected = vec![
            "alpha".to_string(),
            "feature/auth".to_string(),
            default_branch,
            "zebra".to_string(),
        ];
        expected.sort();

        assert_eq!(
            branches, expected,
            "branches should be sorted alphabetically"
        );
    }

    // --- project_name ---
    // Behavioral: public function contract — the directory name IS the project name.
    // The exact output matters because it's used in session names and worktree paths.

    #[test]
    fn project_name_from_path() {
        assert_eq!(
            project_name(Path::new("/Users/jie/code/git-paw")),
            "git-paw"
        );
    }

    #[test]
    fn project_name_fallback_for_root() {
        assert_eq!(project_name(Path::new("/")), "project");
    }

    // --- worktree_dir_name ---
    // Behavioral: public function whose exact output determines actual directory names
    // on disk. The format is the contract — other modules depend on this for path
    // construction, so the exact string matters.

    #[test]
    fn worktree_dir_name_replaces_slash_with_dash() {
        assert_eq!(
            worktree_dir_name("git-paw", "feature/auth-flow"),
            "git-paw-feature-auth-flow"
        );
    }

    #[test]
    fn worktree_dir_name_handles_multiple_slashes() {
        assert_eq!(
            worktree_dir_name("git-paw", "feat/auth/v2"),
            "git-paw-feat-auth-v2"
        );
    }

    #[test]
    fn worktree_dir_name_strips_special_chars() {
        assert_eq!(
            worktree_dir_name("my-proj", "fix/issue#42"),
            "my-proj-fix-issue42"
        );
    }

    #[test]
    fn worktree_dir_name_simple_branch() {
        assert_eq!(worktree_dir_name("git-paw", "main"), "git-paw-main");
    }

    // --- create_worktree / remove_worktree ---
    // Behavioral: tests real git worktree operations against temp repos.
    // Verifies observable outcomes (directory exists, files present, cleanup works).

    #[test]
    #[serial]
    fn create_worktree_at_correct_path() {
        let test_repo = setup_test_repo();
        let repo_root = test_repo.path();

        Command::new("git")
            .current_dir(repo_root)
            .args(["branch", "feature/test"])
            .output()
            .expect("create branch");

        let wt = create_worktree(repo_root, "feature/test").expect("create worktree");
        let worktree_path = wt.path;

        // Verify path follows ../<project>-<sanitized-branch> convention
        let expected_dir_name = worktree_dir_name(&project_name(repo_root), "feature/test");
        assert_eq!(
            worktree_path.file_name().unwrap().to_string_lossy(),
            expected_dir_name,
            "worktree should be at ../<project>-feature-test"
        );
        assert_eq!(
            worktree_path.parent().unwrap().canonicalize().unwrap(),
            repo_root.parent().unwrap().canonicalize().unwrap(),
            "worktree should be in the parent of repo root"
        );

        // Verify files exist
        assert!(worktree_path.exists());
        assert!(worktree_path.join("README.md").exists());

        // Cleanup
        remove_worktree(repo_root, &worktree_path).expect("remove worktree");
    }

    #[test]
    #[serial]
    fn create_worktree_errors_on_checked_out_branch() {
        let test_repo = setup_test_repo();
        let repo_root = test_repo.path();

        let output = Command::new("git")
            .current_dir(repo_root)
            .args(["branch", "--show-current"])
            .output()
            .expect("get branch");
        let current = String::from_utf8_lossy(&output.stdout).trim().to_string();

        let result = create_worktree(repo_root, &current);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, PawError::WorktreeError(_)),
            "expected WorktreeError, got: {err}"
        );
    }

    // --- remove_worktree ---

    #[test]
    #[serial]
    fn remove_worktree_cleans_up_fully() {
        let test_repo = setup_test_repo();
        let repo_root = test_repo.path();

        Command::new("git")
            .current_dir(repo_root)
            .args(["branch", "feature/cleanup"])
            .output()
            .expect("create branch");

        let worktree_path = create_worktree(repo_root, "feature/cleanup")
            .expect("create worktree")
            .path;
        assert!(worktree_path.exists());

        remove_worktree(repo_root, &worktree_path).expect("remove worktree");

        assert!(
            !worktree_path.exists(),
            "worktree directory should be removed"
        );

        // Verify git no longer tracks this worktree
        let output = Command::new("git")
            .current_dir(repo_root)
            .args(["worktree", "list", "--porcelain"])
            .output()
            .expect("list worktrees");
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            !stdout.contains("feature/cleanup"),
            "worktree should not appear in git worktree list"
        );
    }
}