Skip to content

✨ feat(worktree): add prune command to clean merged worktrees#33

Merged
samzong merged 1 commit intomainfrom
feat-wt-autoremove
Jan 7, 2026
Merged

✨ feat(worktree): add prune command to clean merged worktrees#33
samzong merged 1 commit intomainfrom
feat-wt-autoremove

Conversation

@samzong
Copy link
Owner

@samzong samzong commented Jan 7, 2026

No description provided.

Signed-off-by: samzong <samzong.lu@gmail.com>
@samzong samzong merged commit f2c2478 into main Jan 7, 2026
1 check passed
@gemini-code-assist
Copy link

Summary of Changes

Hello @samzong, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the gmc command-line tool by adding a new prune subcommand to its worktree functionality. The primary goal is to simplify the management of Git worktrees by providing an automated way to clean up those associated with branches that have already been merged. This feature helps maintain a tidy development environment by removing stale worktrees and their corresponding local branches, improving developer workflow and reducing clutter.

Highlights

  • New prune command: Introduces a new gmc wt prune command to automatically identify and remove Git worktrees whose branches have been merged into a specified base branch.
  • Flexible base branch resolution: The command intelligently determines the base branch to check merge status against, prioritizing explicit --base flag, then remote upstream/HEAD, origin/HEAD, local HEAD, and finally main or master.
  • Safety and control features: Includes --force to remove worktrees with uncommitted changes and a --dry-run option to preview which worktrees and branches would be removed without making actual changes.
  • Comprehensive testing: Adds extensive unit tests for base branch resolution logic, merge status checks, and the end-to-end pruning functionality.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a useful gmc wt prune command to clean up merged worktrees. The implementation is solid, leveraging git merge-base --is-ancestor for reliable merge checks and providing options like --force and --dry-run. The accompanying tests cover the main success path and helper functions well.

My review includes two main suggestions for improvement:

  1. Making the prune operation more robust by continuing to process other worktrees even if one fails to be removed or its branch fails to be deleted.
  2. Expanding the test suite for the prune command to cover various edge cases and skip conditions, such as dirty worktrees and unmerged branches, to ensure all logic paths are verified.

Comment on lines +90 to +101
result, err := c.runner.RunLogged(args...)
if err != nil {
return gitutil.WrapGitError("failed to remove worktree", result, err)
}
fmt.Fprintf(os.Stderr, "Removed worktree '%s'\n", name)

result, err = c.runner.RunLogged("branch", "-D", wt.Branch)
if err != nil {
return gitutil.WrapGitError("failed to delete branch", result, err)
}
fmt.Fprintf(os.Stderr, "Deleted branch '%s'\n", wt.Branch)
prunedAny = true

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current implementation halts the entire prune operation on the first failure, whether it's removing a worktree or deleting a branch. This can leave the process incomplete if one of many prunable worktrees encounters an issue. A more robust approach would be to report the error for the specific worktree/branch and continue processing the rest. This also involves adjusting when prunedAny is set to correctly reflect that at least one worktree was removed, even if its associated branch deletion failed.

Suggested change
result, err := c.runner.RunLogged(args...)
if err != nil {
return gitutil.WrapGitError("failed to remove worktree", result, err)
}
fmt.Fprintf(os.Stderr, "Removed worktree '%s'\n", name)
result, err = c.runner.RunLogged("branch", "-D", wt.Branch)
if err != nil {
return gitutil.WrapGitError("failed to delete branch", result, err)
}
fmt.Fprintf(os.Stderr, "Deleted branch '%s'\n", wt.Branch)
prunedAny = true
result, err := c.runner.RunLogged(args...)
if err != nil {
err = gitutil.WrapGitError("failed to remove worktree", result, err)
fmt.Fprintf(os.Stderr, "Error removing worktree '%s': %v\n", name, err)
continue
}
fmt.Fprintf(os.Stderr, "Removed worktree '%s'\n", name)
prunedAny = true
result, err = c.runner.RunLogged("branch", "-D", wt.Branch)
if err != nil {
err = gitutil.WrapGitError("failed to delete branch", result, err)
fmt.Fprintf(os.Stderr, "Failed to delete branch '%s': %v\n", wt.Branch, err)
continue
}
fmt.Fprintf(os.Stderr, "Deleted branch '%s'\n", wt.Branch)

Comment on lines +355 to +390
func TestPrune_RemovesMergedWorktreeAndBranch(t *testing.T) {
repoDir := initTestRepo(t)

worktreeDir := filepath.Join(repoDir, "feature-wt")
runGit(t, repoDir, "worktree", "add", "-b", "feature", worktreeDir, "main")
writeFile(t, filepath.Join(worktreeDir, "feature.txt"), "feature")
runGit(t, worktreeDir, "add", ".")
runGit(t, worktreeDir, "commit", "-m", "feature")
runGit(t, repoDir, "merge", "--no-ff", "-m", "merge feature", "feature")

cwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer func() {
if chdirErr := os.Chdir(cwd); chdirErr != nil {
t.Fatalf("failed to restore cwd: %v", chdirErr)
}
}()
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("failed to chdir: %v", err)
}

client := NewClient(Options{})
if err := client.Prune(PruneOptions{}); err != nil {
t.Fatalf("Prune() error = %v", err)
}

if _, err := os.Stat(worktreeDir); !os.IsNotExist(err) {
t.Errorf("Expected worktree to be removed, stat error = %v", err)
}

if _, err := client.runner.Run("-C", repoDir, "rev-parse", "--verify", "refs/heads/feature"); err == nil {
t.Error("Expected feature branch to be deleted")
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The test TestPrune_RemovesMergedWorktreeAndBranch covers the happy path well. However, the Prune function has several conditions for skipping worktrees (e.g., unmerged branches, dirty worktrees without --force, locked worktrees). Adding tests for these scenarios would make the test suite more comprehensive and prevent regressions in this important logic.

For example, you could add tests for:

  • A worktree with an unmerged branch is not pruned.
  • A dirty worktree is not pruned without --force.
  • A dirty worktree is pruned with --force.
  • The --dry-run option previews changes without applying them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant