git-ea/cmd/cleanup.go

67 lines
1.3 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)
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 len(args) > 0 {
for _, arg := range args {
if err := removeWorktree(h, ctx, arg); 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); err != nil {
return err
}
}
return nil
},
}
}
func removeWorktree(h *Handler, ctx context.Context, name string) error {
if err := h.run(ctx, "git", "worktree", "remove", name); err != nil {
return nil
}
return h.run(ctx, "git", "branch", "-D", name)
}