Files
kandev/apps/backend/internal/worktree/manager_cleanup.go
T
João Salavisa 62ddfd4d17 refactor(worktree): split manager.go into per-concern files (#1055)
The Manager type owned creation, removal, state queries, and git helpers
in a single 1,615-line file (2x the lint threshold). Decompose into five
files within the same package, preserving the Manager public API and all
existing test coverage:

  - manager.go         struct, interfaces, NewManager, repo locks
  - manager_lifecycle  Create, recreate, git worktree add paths
  - manager_state      cache, persistence, Get* lookups, IsValid
  - manager_cleanup    RemoveByID, setup/cleanup scripts, dir removal
  - manager_git        branch inspection, non-interactive git, pull sync

Extract four helpers to satisfy the new-code lint baseline that fires on
moved-but-unchanged complexity hot-spots:

  - tryReuseExisting + resolveBaseRefWithFallback split Create (cyclo 21)
  - gitAddWorktreeForRecreate trims recreate below 80 lines
  - retryFetchAsRemoteTrackingRef flattens fetchBranchToLocal nesting

No behavior change; all existing internal/worktree tests pass unchanged.

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-28 23:57:11 +01:00

294 lines
8.9 KiB
Go

package worktree
import (
"context"
"fmt"
"os"
"os/exec"
"strings"
"time"
"go.uber.org/zap"
)
// RemoveByID removes a specific worktree by its ID and optionally its branch.
func (m *Manager) RemoveByID(ctx context.Context, worktreeID string, removeBranch bool) error {
wt, err := m.GetByID(ctx, worktreeID)
if err != nil {
return err
}
return m.removeWorktree(ctx, wt, removeBranch)
}
// removeWorktree performs the actual removal of a worktree.
func (m *Manager) removeWorktree(ctx context.Context, wt *Worktree, removeBranch bool) error {
// Get repository lock
repoLock := m.getRepoLock(wt.RepositoryPath)
repoLock.Lock()
defer func() {
repoLock.Unlock()
m.releaseRepoLock(wt.RepositoryPath)
}()
// Execute cleanup script BEFORE removing directory
m.runWorktreeCleanupScript(ctx, wt)
// Remove worktree directory
if err := m.removeWorktreeDir(ctx, wt.Path, wt.RepositoryPath); err != nil {
m.logger.Warn("failed to remove worktree directory",
zap.String("path", wt.Path),
zap.Error(err))
}
// Optionally remove the branch from the main repository
if removeBranch {
m.logger.Info("deleting branch from main repository",
zap.String("branch", wt.Branch),
zap.String("repository_path", wt.RepositoryPath))
cmd := exec.CommandContext(ctx, "git", "branch", "-D", wt.Branch)
cmd.Dir = wt.RepositoryPath
if output, err := cmd.CombinedOutput(); err != nil {
m.logger.Warn("failed to delete branch from main repository",
zap.String("branch", wt.Branch),
zap.String("repository_path", wt.RepositoryPath),
zap.String("output", string(output)),
zap.Error(err))
} else {
m.logger.Info("successfully deleted branch from main repository",
zap.String("branch", wt.Branch),
zap.String("repository_path", wt.RepositoryPath))
}
}
// Update store
if m.store != nil {
now := time.Now()
wt.Status = StatusDeleted
wt.DeletedAt = &now
wt.UpdatedAt = now
if err := m.store.UpdateWorktree(ctx, wt); err != nil {
// Record may already be deleted by another cleanup path (e.g. task deletion).
// This is expected and harmless - only log at debug level.
m.logger.Debug("failed to update worktree status (may already be deleted)",
zap.String("worktree_id", wt.ID),
zap.Error(err))
}
}
// Update cache: delete the (session, repo) entry. Removing a worktree only
// affects its own repo; siblings on other repos must remain cached.
m.mu.Lock()
if wt.SessionID != "" {
delete(m.worktrees, cacheKey(wt.SessionID, wt.RepositoryID))
}
m.mu.Unlock()
m.logger.Info("removed worktree",
zap.String("task_id", wt.TaskID),
zap.String("worktree_id", wt.ID),
zap.String("path", wt.Path),
zap.Bool("branch_removed", removeBranch))
return nil
}
func (m *Manager) runWorktreeSetupScript(ctx context.Context, wt *Worktree, repositoryPath string) error {
if m.scriptMsgHandler == nil || m.repoProvider == nil {
return nil
}
if wt.RepositoryID == "" {
// Nothing to set up without a linked repository; upstream may not
// always populate this field.
return nil
}
repo, err := m.repoProvider.GetRepository(ctx, wt.RepositoryID)
if err != nil {
m.logger.Warn("failed to fetch repository for setup script",
zap.String("repository_id", wt.RepositoryID),
zap.Error(err))
return nil
}
if strings.TrimSpace(repo.SetupScript) == "" {
return nil
}
m.logger.Info("executing setup script for worktree",
zap.String("worktree_id", wt.ID),
zap.String("repository_id", wt.RepositoryID))
scriptReq := ScriptExecutionRequest{
SessionID: wt.SessionID,
TaskID: wt.TaskID,
RepositoryID: wt.RepositoryID,
Script: repo.SetupScript,
WorkingDir: wt.Path,
ScriptType: "setup",
}
if err := m.scriptMsgHandler.ExecuteSetupScript(ctx, scriptReq); err != nil {
m.logger.Error("setup script failed, cleaning up worktree",
zap.String("worktree_id", wt.ID),
zap.Error(err))
m.cleanupWorktreeOnSetupFailure(ctx, wt, repositoryPath)
return fmt.Errorf("setup script failed: %w", err)
}
m.logger.Info("setup script completed successfully", zap.String("worktree_id", wt.ID))
return nil
}
// cleanupWorktreeOnSetupFailure removes the in-memory cache entry, deletes the worktree
// directory, and marks the worktree as deleted in the store after a setup script failure.
func (m *Manager) cleanupWorktreeOnSetupFailure(ctx context.Context, wt *Worktree, repositoryPath string) {
if wt.SessionID != "" {
m.mu.Lock()
delete(m.worktrees, cacheKey(wt.SessionID, wt.RepositoryID))
m.mu.Unlock()
}
if cleanupErr := m.removeWorktreeDir(ctx, wt.Path, repositoryPath); cleanupErr != nil {
m.logger.Warn("failed to cleanup worktree after setup failure", zap.Error(cleanupErr))
}
if m.store == nil {
return
}
now := time.Now()
wt.Status = StatusDeleted
wt.DeletedAt = &now
wt.UpdatedAt = now
if updateErr := m.store.UpdateWorktree(ctx, wt); updateErr != nil {
m.logger.Warn("failed to update worktree status", zap.Error(updateErr))
}
}
// runWorktreeCleanupScript executes the repository cleanup script for a worktree before removal.
func (m *Manager) runWorktreeCleanupScript(ctx context.Context, wt *Worktree) {
if m.scriptMsgHandler == nil || m.repoProvider == nil {
return
}
repo, err := m.repoProvider.GetRepository(ctx, wt.RepositoryID)
if err != nil {
m.logger.Warn("failed to fetch repository for cleanup script",
zap.String("repository_id", wt.RepositoryID),
zap.Error(err))
return
}
if strings.TrimSpace(repo.CleanupScript) == "" {
return
}
m.logger.Info("executing cleanup script for worktree",
zap.String("worktree_id", wt.ID),
zap.String("repository_id", wt.RepositoryID))
scriptReq := ScriptExecutionRequest{
SessionID: wt.SessionID,
TaskID: wt.TaskID,
RepositoryID: wt.RepositoryID,
Script: repo.CleanupScript,
WorkingDir: wt.Path,
ScriptType: "cleanup",
}
if err := m.scriptMsgHandler.ExecuteCleanupScript(ctx, scriptReq); err != nil {
m.logger.Warn("cleanup script failed, proceeding with deletion",
zap.String("worktree_id", wt.ID),
zap.Error(err))
} else {
m.logger.Info("cleanup script completed successfully",
zap.String("worktree_id", wt.ID))
}
}
// CleanupWorktrees removes provided worktrees without re-fetching from the store.
func (m *Manager) CleanupWorktrees(ctx context.Context, worktrees []*Worktree) error {
if len(worktrees) == 0 {
return nil
}
var lastErr error
for _, wt := range worktrees {
if wt == nil {
continue
}
if err := m.removeWorktree(ctx, wt, true); err != nil {
m.logger.Warn("failed to remove worktree on task deletion",
zap.String("task_id", wt.TaskID),
zap.String("worktree_id", wt.ID),
zap.Error(err))
lastErr = err
}
}
m.mu.Lock()
for _, wt := range worktrees {
if wt == nil {
continue
}
if wt.SessionID != "" {
delete(m.worktrees, cacheKey(wt.SessionID, wt.RepositoryID))
}
}
m.mu.Unlock()
return lastErr
}
// OnTaskDeleted cleans up all worktrees for a task when it is deleted.
func (m *Manager) OnTaskDeleted(ctx context.Context, taskID string) error {
// Get all worktrees for this task
worktrees, err := m.GetAllByTaskID(ctx, taskID)
if err != nil {
return err
}
return m.CleanupWorktrees(ctx, worktrees)
}
// removeWorktreeDir removes a worktree directory using git worktree remove.
func (m *Manager) removeWorktreeDir(ctx context.Context, worktreePath, repoPath string) error {
// First try git worktree remove
cmd := exec.CommandContext(ctx, "git", "worktree", "remove", "--force", worktreePath)
cmd.Dir = repoPath
if output, err := cmd.CombinedOutput(); err != nil {
m.logger.Debug("git worktree remove failed, falling back to rm",
zap.String("output", string(output)),
zap.Error(err))
if err := m.forceRemoveDir(ctx, worktreePath); err != nil {
return err
}
// Prune stale worktree entries
pruneCmd := exec.CommandContext(ctx, "git", "worktree", "prune")
pruneCmd.Dir = repoPath
if err := pruneCmd.Run(); err != nil {
m.logger.Debug("git worktree prune failed", zap.Error(err))
}
}
return nil
}
// forceRemoveDir removes a directory, retrying on transient failures.
// On macOS, os.RemoveAll can fail with "directory not empty" when files
// have special attributes or were recently released by other processes
// (e.g. .next/dev build cache). Falls back to rm -rf as a last resort.
func (m *Manager) forceRemoveDir(ctx context.Context, dir string) error {
const maxRetries = 3
const retryDelay = 200 * time.Millisecond
for i := range maxRetries {
err := os.RemoveAll(dir)
if err == nil {
return nil
}
if i < maxRetries-1 {
m.logger.Debug("os.RemoveAll failed, retrying",
zap.String("path", dir),
zap.Int("attempt", i+1),
zap.Error(err))
time.Sleep(retryDelay)
}
}
// Last resort: shell out to rm -rf which handles macOS edge cases better
cmd := exec.CommandContext(ctx, "rm", "-rf", dir)
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("rm -rf failed: %w (output: %s)", err, string(output))
}
return nil
}