workbloom 0.9.1

A Git worktree management tool with automatic file copying
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
use anyhow::{bail, Context, Result};
use std::path::{Path, PathBuf};
use std::process::Command;

pub struct GitRepo {
    pub root_dir: PathBuf,
}

fn validate_branch_name(branch_name: &str) -> Result<()> {
    // Check for empty branch name
    if branch_name.is_empty() {
        bail!("Branch name cannot be empty");
    }

    // Check for dangerous characters that could lead to command injection
    let dangerous_chars = [
        '$', '`', '(', ')', '{', '}', '|', '&', ';', '<', '>', '\n', '\r', '\0', '"', '\'', '\\',
    ];
    if branch_name.chars().any(|c| dangerous_chars.contains(&c)) {
        bail!("Branch name contains invalid characters");
    }

    // Check for valid git branch name patterns
    // Git branch names cannot start/end with dots or slashes
    if branch_name.starts_with('.') || branch_name.ends_with('.') {
        bail!("Branch name cannot start or end with a dot");
    }

    if branch_name.starts_with('/') || branch_name.ends_with('/') {
        bail!("Branch name cannot start or end with a slash");
    }

    // Check for consecutive dots
    if branch_name.contains("..") {
        bail!("Branch name cannot contain consecutive dots");
    }

    // Check for @{ sequence which has special meaning in git
    if branch_name.contains("@{") {
        bail!("Branch name cannot contain '@{{' sequence");
    }

    Ok(())
}

impl GitRepo {
    pub fn new() -> Result<Self> {
        let root_dir = get_main_repo_dir()?;
        Ok(Self { root_dir })
    }

    pub fn branch_exists(&self, branch_name: &str) -> Result<bool> {
        validate_branch_name(branch_name)?;
        let output = Command::new("git")
            .args([
                "show-ref",
                "--verify",
                "--quiet",
                &format!("refs/heads/{branch_name}"),
            ])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to check if branch exists")?;

        Ok(output.status.success())
    }

    pub fn create_branch(&self, branch_name: &str) -> Result<()> {
        validate_branch_name(branch_name)?;
        Command::new("git")
            .args(["checkout", "-b", branch_name])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to create branch")?;

        Command::new("git")
            .args(["checkout", "-"])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to switch back to previous branch")?;

        Ok(())
    }

    pub fn add_worktree(&self, worktree_path: &Path, branch_name: &str) -> Result<()> {
        validate_branch_name(branch_name)?;
        let mut cmd = Command::new("git");
        cmd.args([
            "worktree",
            "add",
            worktree_path.to_str().unwrap(),
            branch_name,
        ])
        .current_dir(&self.root_dir);
        crate::output::configure_command_for_machine_output(&mut cmd)
            .status()
            .context("Failed to create worktree")?;

        Ok(())
    }

    pub fn list_worktrees(&self) -> Result<Vec<WorktreeInfo>> {
        let output = Command::new("git")
            .args(["worktree", "list", "--porcelain"])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to list worktrees")?;

        let output_str = String::from_utf8_lossy(&output.stdout);
        parse_worktree_list(&output_str)
    }

    pub fn get_merged_branches(&self) -> Result<Vec<String>> {
        let output = Command::new("git")
            .args(["branch", "--merged", "main"])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to get merged branches")?;

        let output_str = String::from_utf8_lossy(&output.stdout);
        let branches: Vec<String> = output_str
            .lines()
            .filter(|line| !line.trim().is_empty())
            .filter(|line| !line.contains("*"))
            .filter(|line| !line.trim().eq("main") && !line.trim().eq("master"))
            .map(|line| line.trim().trim_start_matches("+ ").to_string())
            .collect();
        Ok(branches)
    }

    pub fn remove_worktree(&self, worktree_path: &Path, force: bool) -> Result<()> {
        let mut args = vec!["worktree", "remove"];
        if force {
            args.push("--force");
        }
        args.push(worktree_path.to_str().unwrap());

        let mut cmd = Command::new("git");
        cmd.args(&args).current_dir(&self.root_dir);
        crate::output::configure_command_for_machine_output(&mut cmd)
            .status()
            .context("Failed to remove worktree")?;

        Ok(())
    }

    pub fn delete_branch(&self, branch_name: &str) -> Result<()> {
        validate_branch_name(branch_name)?;
        Command::new("git")
            .args(["branch", "-D", branch_name])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to delete branch")?;

        Ok(())
    }

    pub fn is_branch_merged(&self, branch_name: &str) -> Result<bool> {
        validate_branch_name(branch_name)?;
        let output = Command::new("git")
            .args(["merge-base", "--is-ancestor", branch_name, "main"])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to check if branch is merged")?;

        Ok(output.status.success())
    }

    pub fn has_unmerged_commits(&self, branch_name: &str) -> Result<bool> {
        validate_branch_name(branch_name)?;
        // Check if branch has commits that are not in main
        let output = Command::new("git")
            .args(["rev-list", "--count", &format!("main..{branch_name}")])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to count unmerged commits")?;

        let count_str = String::from_utf8_lossy(&output.stdout);
        let count = count_str.trim().parse::<i32>().unwrap_or(0);

        Ok(count > 0)
    }

    pub fn get_current_branch(&self, worktree_path: &Path) -> Result<String> {
        let output = Command::new("git")
            .args(["rev-parse", "--abbrev-ref", "HEAD"])
            .current_dir(worktree_path)
            .output()
            .context("Failed to get current branch")?;

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    pub fn remote_branch_exists(&self, branch_name: &str) -> Result<bool> {
        validate_branch_name(branch_name)?;
        // Use ls-remote to check without fetching - much faster
        let output = Command::new("git")
            .args(["ls-remote", "--heads", "origin", branch_name])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to check remote branch")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            bail!("Failed to check remote branch: {}", stderr);
        }

        let output_str = String::from_utf8_lossy(&output.stdout);
        Ok(!output_str.trim().is_empty())
    }

    pub fn fetch_remote_branch(&self, branch_name: &str) -> Result<()> {
        validate_branch_name(branch_name)?;
        // Fetch specific remote branch
        let output = Command::new("git")
            .args([
                "fetch",
                "origin",
                &format!("refs/heads/{branch_name}:refs/remotes/origin/{branch_name}"),
            ])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to execute git fetch command")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("couldn't find remote ref") {
                bail!("Branch '{}' does not exist on remote", branch_name);
            } else if stderr.contains("Permission denied") {
                bail!("Permission denied when fetching from remote");
            } else {
                bail!(
                    "Failed to fetch remote branch '{}': {}",
                    branch_name,
                    stderr
                );
            }
        }

        Ok(())
    }

    pub fn create_tracking_branch(&self, branch_name: &str) -> Result<()> {
        validate_branch_name(branch_name)?;
        // Create local branch tracking remote branch
        let output = Command::new("git")
            .args([
                "checkout",
                "-b",
                branch_name,
                &format!("origin/{branch_name}"),
            ])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to execute git checkout command")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("already exists") {
                bail!("Branch '{}' already exists locally", branch_name);
            } else if stderr.contains("not a valid object name") {
                bail!(
                    "Remote branch 'origin/{}' not found. Did you forget to fetch?",
                    branch_name
                );
            } else {
                bail!(
                    "Failed to create tracking branch '{}': {}",
                    branch_name,
                    stderr
                );
            }
        }

        // Switch back to the previous branch
        let switch_output = Command::new("git")
            .args(["checkout", "-"])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to execute git checkout - command")?;

        if !switch_output.status.success() {
            // Log warning but don't fail - the tracking branch was created successfully
            eprintln!(
                "Warning: Failed to switch back to previous branch: {}",
                String::from_utf8_lossy(&switch_output.stderr)
            );
        }

        Ok(())
    }

    pub fn was_branch_merged_to_main(&self, branch_name: &str) -> Result<bool> {
        validate_branch_name(branch_name)?;
        // First check if branch exists on remote
        let remote_exists = self.remote_branch_exists(branch_name)?;

        // If branch doesn't exist on remote, it's likely a new branch that shouldn't be cleaned up
        if !remote_exists {
            return Ok(false);
        }

        // Get the current HEAD commit of the branch
        let branch_head_output = Command::new("git")
            .args(["rev-parse", branch_name])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to get branch HEAD")?;

        let branch_head = String::from_utf8_lossy(&branch_head_output.stdout)
            .trim()
            .to_string();

        // Get the current HEAD commit of main
        let main_head_output = Command::new("git")
            .args(["rev-parse", "main"])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to get main HEAD")?;

        let main_head = String::from_utf8_lossy(&main_head_output.stdout)
            .trim()
            .to_string();

        // If branch points to the same commit as main, it's a new branch with no commits
        // This should NOT be considered as merged
        if branch_head == main_head {
            return Ok(false);
        }

        // Check if branch has any unique commits
        // If it has no unique commits but is different from main, it might be behind main
        let unique_commits_output = Command::new("git")
            .args(["rev-list", "--count", &format!("main..{branch_name}")])
            .current_dir(&self.root_dir)
            .output()
            .context("Failed to count unique commits")?;

        let unique_count = String::from_utf8_lossy(&unique_commits_output.stdout)
            .trim()
            .parse::<i32>()
            .unwrap_or(0);

        // If branch has no unique commits, check if it's actually been merged
        if unique_count == 0 {
            // Check if any merge commit in main has the branch HEAD as a parent
            let merge_commits_output = Command::new("git")
                .args(["log", "--merges", "--format=%H %P", "main"])
                .current_dir(&self.root_dir)
                .output()
                .context("Failed to check merge commits")?;

            let merge_commits = String::from_utf8_lossy(&merge_commits_output.stdout);

            // Check if any merge commit has our branch HEAD as a parent
            for line in merge_commits.lines() {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 2 && parts[1..].contains(&branch_head.as_str()) {
                    return Ok(true);
                }
            }
        }

        Ok(false)
    }
}

#[derive(Debug, Clone)]
pub struct WorktreeInfo {
    pub path: PathBuf,
    pub branch: Option<String>,
    pub is_detached: bool,
}

fn get_main_repo_dir() -> Result<PathBuf> {
    let output = Command::new("git")
        .args(["worktree", "list"])
        .output()
        .context("Failed to get worktree list")?;

    if output.status.success() {
        let output_str = String::from_utf8_lossy(&output.stdout);
        if let Some(first_line) = output_str.lines().next() {
            if let Some(path) = first_line.split_whitespace().next() {
                return Ok(PathBuf::from(path));
            }
        }
    }

    let output = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .context("Failed to get git root directory")?;

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

fn parse_worktree_list(output: &str) -> Result<Vec<WorktreeInfo>> {
    let mut worktrees = Vec::new();
    let mut current_path: Option<PathBuf> = None;
    let mut current_branch: Option<String> = None;
    let mut is_detached = false;

    for line in output.lines() {
        if line.starts_with("worktree ") {
            if let Some(path) = current_path.take() {
                worktrees.push(WorktreeInfo {
                    path,
                    branch: current_branch.take(),
                    is_detached,
                });
            }
            current_path = Some(PathBuf::from(line.trim_start_matches("worktree ")));
            is_detached = false;
        } else if line.starts_with("branch refs/heads/") {
            current_branch = Some(line.trim_start_matches("branch refs/heads/").to_string());
        } else if line == "detached" {
            is_detached = true;
        }
    }

    if let Some(path) = current_path {
        worktrees.push(WorktreeInfo {
            path,
            branch: current_branch,
            is_detached,
        });
    }

    Ok(worktrees)
}

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

    fn setup_test_repo() -> Result<(TempDir, GitRepo)> {
        let temp_dir = TempDir::new()?;
        let repo_path = temp_dir.path();

        // Initialize a git repo
        Command::new("git")
            .args(["init"])
            .current_dir(repo_path)
            .output()?;

        // Set git config to avoid errors
        Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(repo_path)
            .output()?;

        Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(repo_path)
            .output()?;

        // Create initial commit
        Command::new("git")
            .args(["commit", "--allow-empty", "-m", "Initial commit"])
            .current_dir(repo_path)
            .output()?;

        // Rename to main if needed
        Command::new("git")
            .args(["branch", "-M", "main"])
            .current_dir(repo_path)
            .output()?;

        let repo = GitRepo {
            root_dir: repo_path.to_path_buf(),
        };

        Ok((temp_dir, repo))
    }

    #[test]
    fn test_has_unmerged_commits_with_new_branch() -> Result<()> {
        let (_temp_dir, repo) = setup_test_repo()?;

        // Create a new branch
        repo.create_branch("test-branch")?;

        // A new branch without commits should not have unmerged commits
        assert!(!repo.has_unmerged_commits("test-branch")?);

        Ok(())
    }

    #[test]
    fn test_branch_exists() -> Result<()> {
        let (_temp_dir, repo) = setup_test_repo()?;

        // Main branch should exist
        assert!(repo.branch_exists("main")?);

        // Non-existent branch should not exist
        assert!(!repo.branch_exists("non-existent-branch")?);

        // Create a branch and check it exists
        repo.create_branch("test-branch")?;
        assert!(repo.branch_exists("test-branch")?);

        Ok(())
    }

    #[test]
    fn test_get_merged_branches() -> Result<()> {
        let (_temp_dir, repo) = setup_test_repo()?;

        // Create and immediately check merged branches
        repo.create_branch("feature-branch")?;

        // Switch back to main
        Command::new("git")
            .args(["checkout", "main"])
            .current_dir(&repo.root_dir)
            .output()?;

        let merged = repo.get_merged_branches()?;

        // A branch created from main with no new commits should appear as merged
        assert!(merged.contains(&"feature-branch".to_string()));

        Ok(())
    }
}