git-ea/cmd/cleanup.go

80 lines
1.8 KiB
Go

package cmd
import (
"context"
"errors"
"flag"
"github.com/AlecAivazis/survey/v2"
"github.com/peterbourgon/ff/v3/ffcli"
)
func (h *Handler) Cleanup() *ffcli.Command {
fs := flag.NewFlagSet("cleanup", flag.ContinueOnError)
forceFlag := fs.Bool("force", false, "Force cleanup")
fs.BoolVar(forceFlag, "f", *forceFlag, "--force")
pruneFlag := fs.Bool("prune", false, "Prune worktrees")
fs.BoolVar(pruneFlag, "p", *pruneFlag, "--prune")
return &ffcli.Command{
Name: "cleanup",
FlagSet: fs,
ShortUsage: "cleanup [branches...]",
ShortHelp: "cleanup removes named branches, or interactive if no arguments",
Exec: func(ctx context.Context, args []string) error {
if err := h.checkInit(); err != nil {
return err
}
if *pruneFlag {
return run(ctx, h.Config.Workspace(), "git", "worktree", "prune")
}
if len(args) > 0 {
for _, arg := range args {
if err := removeWorktree(h, ctx, arg, *forceFlag); err != nil {
return err
}
}
return nil
}
opts, err := h.Config.Branches()
if err != nil {
return err
}
if len(opts) == 0 {
return errors.New("no worktrees currently exist")
}
var remove []string
if err := survey.AskOne(&survey.MultiSelect{
Message: "Worktrees to remove",
Options: opts,
}, &remove); err != nil {
return err
}
for _, rm := range remove {
if err := removeWorktree(h, ctx, rm, *forceFlag); err != nil {
return err
}
}
return nil
},
}
}
func removeWorktree(h *Handler, ctx context.Context, name string, force bool) error {
args := []string{"worktree", "remove"}
if force {
args = append(args, "--force")
}
args = append(args, name)
if err := h.run(ctx, "git", args...); err != nil {
return nil
}
return h.run(ctx, "git", "branch", "-D", name)
}