Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 12 additions & 16 deletions internal/worktree/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,6 @@
return err
}

mainPath, err := MainPath()
if err != nil {
return err
}

merged, err := MergedBranches()
if err != nil {
return err
Expand All @@ -84,7 +79,7 @@
removed := 0

for _, e := range entries {
if e.Path == mainPath || e.Branch == "" || !merged[e.Branch] {
if !shouldCleanEntry(e, merged) {
continue
}
fmt.Printf("Removing worktree: %s (branch: %s)\n", e.Path, e.Branch)
Expand Down Expand Up @@ -116,27 +111,20 @@
}

func runNuke() error {
mainPath, err := MainPath()
if err != nil {
return err
}

entries, err := List()
if err != nil {
return err
}

removed := 0
for _, e := range entries {
if e.Path == mainPath {
if !shouldNukeEntry(e) {
continue
}
fmt.Printf("Removing: %s\n", e.Path)
if err := Remove(e.Path, true); err != nil {
fmt.Fprintf(os.Stderr, " warning: %s — cleaning up manually\n", err)
if removeErr := os.RemoveAll(e.Path); removeErr != nil {
fmt.Fprintf(os.Stderr, " warning: manual cleanup failed: %s\n", removeErr)
}
fmt.Fprintf(os.Stderr, " warning: %s\n", err)
continue
}
if e.Branch != "" {
_ = DeleteBranch(e.Branch, true)
Expand All @@ -148,3 +136,11 @@
fmt.Printf("Removed %d worktree(s).\n", removed)
return nil
}

func shouldCleanEntry(e Entry, merged map[string]bool) bool {

Check failure on line 140 in internal/worktree/commands.go

View workflow job for this annotation

GitHub Actions / Lint

hugeParam: e is heavy (80 bytes); consider passing it by pointer (gocritic)
return !e.Protected() && e.Branch != "" && merged[e.Branch]
}

func shouldNukeEntry(e Entry) bool {

Check failure on line 144 in internal/worktree/commands.go

View workflow job for this annotation

GitHub Actions / Lint

hugeParam: e is heavy (80 bytes); consider passing it by pointer (gocritic)
return !e.Protected()
}
59 changes: 59 additions & 0 deletions internal/worktree/commands_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package worktree

import "testing"

func TestShouldCleanEntry(t *testing.T) {
t.Parallel()

merged := map[string]bool{
"merged": true,
}

cases := []struct {
name string
entry Entry
want bool
}{
{name: "merged regular worktree", entry: Entry{Branch: "merged"}, want: true},
{name: "main worktree", entry: Entry{Branch: "merged", IsMain: true}, want: false},
{name: "current worktree", entry: Entry{Branch: "merged", IsCurrent: true}, want: false},
{name: "locked worktree", entry: Entry{Branch: "merged", Locked: true}, want: false},
{name: "detached head", entry: Entry{}, want: false},
{name: "unmerged branch", entry: Entry{Branch: "feature"}, want: false},
}

for _, tc := range cases {
tc := tc

Check failure on line 26 in internal/worktree/commands_test.go

View workflow job for this annotation

GitHub Actions / Lint

The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := shouldCleanEntry(tc.entry, merged); got != tc.want {
t.Fatalf("shouldCleanEntry(%+v) = %v, want %v", tc.entry, got, tc.want)
}
})
}
}

func TestShouldNukeEntry(t *testing.T) {
t.Parallel()

cases := []struct {
name string
entry Entry
want bool
}{
{name: "regular worktree", entry: Entry{}, want: true},
{name: "main worktree", entry: Entry{IsMain: true}, want: false},
{name: "current worktree", entry: Entry{IsCurrent: true}, want: false},
{name: "locked worktree", entry: Entry{Locked: true}, want: false},
}

for _, tc := range cases {
tc := tc

Check failure on line 51 in internal/worktree/commands_test.go

View workflow job for this annotation

GitHub Actions / Lint

The copy of the 'for' variable "tc" can be deleted (Go 1.22+) (copyloopvar)
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := shouldNukeEntry(tc.entry); got != tc.want {
t.Fatalf("shouldNukeEntry(%+v) = %v, want %v", tc.entry, got, tc.want)
}
})
}
}
84 changes: 62 additions & 22 deletions internal/worktree/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,14 @@ func List() ([]Entry, error) {
return nil, fmt.Errorf("git worktree list: %w", err)
}

mainPath, err := MainPath()
if err != nil {
return nil, err
}

merged, err := MergedBranches()
if err != nil {
return nil, err
}

// Detect current working directory to mark the active worktree
cwd, _ := os.Getwd()
currentGitDir := currentWorktreeGitDir()

var entries []Entry
var cur Entry
Expand All @@ -83,10 +79,11 @@ func List() ([]Entry, error) {

// finalizeEntry fills computed fields and returns the entry ready for collection.
finalizeEntry := func(e Entry) Entry {
e.IsMain = e.Path == mainPath
entryGitDir := entryGitDir(e.Path)
e.IsMain = entryGitDir != "" && !isLinkedGitDir(entryGitDir)
e.Prunable = prunable
e.Locked = locked
e.IsCurrent = isSameOrChild(cwd, e.Path)
e.IsCurrent = isSameOrChild(cwd, e.Path) || samePath(currentGitDir, entryGitDir)
e.Status = classifyEntry(&e, merged)
// Populate LastActive for non-prunable entries with existing paths
if !e.Prunable {
Expand Down Expand Up @@ -151,12 +148,15 @@ func lastActiveTime(path string) time.Time {
var latest time.Time

// Resolve the actual git directory (handles both main checkout and linked worktrees)
gitDir := resolveGitDir(path)
candidates := []string{
filepath.Join(gitDir, "HEAD"),
filepath.Join(gitDir, "index"),
filepath.Join(path, ".git"), // mtime of .git itself (file or dir)
gitDir := entryGitDir(path)
var candidates []string
if gitDir != "" {
candidates = append(candidates,
filepath.Join(gitDir, "HEAD"),
filepath.Join(gitDir, "index"),
)
}
candidates = append(candidates, filepath.Join(path, ".git")) // mtime of .git itself (file or dir)
for _, c := range candidates {
if info, err := os.Stat(c); err == nil {
if info.ModTime().After(latest) {
Expand All @@ -173,20 +173,44 @@ func lastActiveTime(path string) time.Time {
return latest
}

func currentWorktreeGitDir() string {
out, err := exec.CommandContext(context.Background(), "git", "rev-parse", "--absolute-git-dir").Output()
if err != nil {
return ""
}
return strings.TrimSpace(string(out))
}

func entryGitDir(path string) string {
if isGitDir(path) {
return filepath.Clean(path)
}
dotGit := filepath.Join(path, ".git")
if _, err := os.Stat(dotGit); err != nil {
return ""
}
return resolveGitDir(path)
}

func isGitDir(path string) bool {
headInfo, headErr := os.Stat(filepath.Join(path, "HEAD"))
configInfo, configErr := os.Stat(filepath.Join(path, "config"))
return headErr == nil && !headInfo.IsDir() && configErr == nil && !configInfo.IsDir()
}

// resolveGitDir returns the path to the actual git directory for a worktree.
// For the main checkout, this is <path>/.git. For linked worktrees, .git is a
// file containing "gitdir: <path>" pointing to the real git metadata.
// The worktree's .git metadata may be either a directory or a file containing
// "gitdir: <path>" that points to the actual git metadata directory.
func resolveGitDir(worktreePath string) string {
dotGit := filepath.Join(worktreePath, ".git")
info, err := os.Stat(dotGit)
if err != nil {
return dotGit
}
// Main checkout: .git is a directory
// .git can be a directory or a file pointing at the real git metadata.
if info.IsDir() {
return dotGit
}
// Linked worktree: .git is a file with "gitdir: <path>"
data, err := os.ReadFile(dotGit)
if err != nil {
return dotGit
Expand All @@ -202,6 +226,19 @@ func resolveGitDir(worktreePath string) string {
return gitdir
}

func isMainWorktree(worktreePath string) bool {
gitDir := entryGitDir(worktreePath)
if gitDir == "" {
return false
}
return !isLinkedGitDir(gitDir)
}

func isLinkedGitDir(gitDir string) bool {
gitDir = filepath.Clean(gitDir)
return filepath.Base(filepath.Dir(gitDir)) == "worktrees"
}

func classifyEntry(e *Entry, merged map[string]bool) Status {
if e.Prunable {
return StatusPrunable
Expand All @@ -225,13 +262,16 @@ func isSameOrChild(child, parent string) bool {
return c == p || strings.HasPrefix(c, p+string(os.PathSeparator))
}

// MainPath returns the top-level path of the main checkout.
func MainPath() (string, error) {
out, err := exec.CommandContext(context.Background(), "git", "rev-parse", "--show-toplevel").Output()
if err != nil {
return "", fmt.Errorf("git rev-parse --show-toplevel: %w", err)
func samePath(a, b string) bool {
if a == "" || b == "" {
return false
}
x, err1 := filepath.EvalSymlinks(a)
y, err2 := filepath.EvalSymlinks(b)
if err1 != nil || err2 != nil {
return filepath.Clean(a) == filepath.Clean(b)
}
return strings.TrimSpace(string(out)), nil
return x == y
}

// MergedBranches returns branch names that are fully merged into main.
Expand Down
Loading
Loading