package cmd import ( "context" "errors" "flag" "fmt" "os" "strings" "github.com/peterbourgon/ff/v3/ffcli" ) func (h *Handler) Branch() *ffcli.Command { fs := flag.NewFlagSet("branch", flag.ContinueOnError) noFetchFlag := fs.Bool("no-fetch", false, "Skip fetching") fs.BoolVar(noFetchFlag, "nf", *noFetchFlag, "--no-fetch") baseFlag := fs.String("base", "main", "Ref to base from") fs.StringVar(baseFlag, "b", *baseFlag, "--base") listFlag := fs.Bool("list", false, "List branches available") fs.BoolVar(listFlag, "l", *listFlag, "--list") ideFlag := fs.Bool("ide", false, "Open an IDE for the new branch") fs.BoolVar(ideFlag, "i", *ideFlag, "--ide") return &ffcli.Command{ Name: "branch", FlagSet: fs, ShortUsage: "branch --base [ref=main] ", ShortHelp: "branch creates a new branch called `name` based on `base`", Exec: func(ctx context.Context, args []string) error { if err := h.checkInit(); err != nil { return err } if *listFlag { dirs, err := os.ReadDir(h.Config.Workspace()) if err != nil { return err } for _, dir := range dirs { if !dir.IsDir() { continue } fmt.Println(dir.Name()) } return nil } if len(args) < 1 { return errors.New("branch requires a name") } name := args[0] base := *baseFlag switch { case strings.HasPrefix(base, "o/"): base = "origin/" + strings.TrimPrefix(base, "o/") case strings.HasPrefix(base, "u/"): base = "upstream/" + strings.TrimPrefix(base, "u/") } if (!strings.HasPrefix(base, "upstream") || !strings.HasPrefix(base, "origin")) && !strings.HasPrefix(base, "pr-") { base = fmt.Sprintf("upstream/%s", base) } if !*noFetchFlag { h.fetch(ctx) } if err := h.run(ctx, "git", "worktree", "add", "-B", name, h.Config.WorkspaceBranch(name), base); err != nil { return err } if *ideFlag { return h.IDE().ParseAndRun(ctx, []string{name}) } return nil }, } }