-
Notifications
You must be signed in to change notification settings - Fork 17
/
top.go
82 lines (70 loc) · 1.9 KB
/
top.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"context"
"fmt"
"github.com/charmbracelet/log"
"go.abhg.dev/gs/internal/must"
"go.abhg.dev/gs/internal/text"
"go.abhg.dev/gs/internal/ui"
"go.abhg.dev/gs/internal/ui/widget"
)
type topCmd struct {
checkoutOptions
}
func (*topCmd) Help() string {
return text.Dedent(`
Checks out the top-most branch in the current branch's stack.
If there are multiple possible top-most branches,
a prompt will ask you to pick one.
Use the -n flag to print the branch without checking it out.
`)
}
func (cmd *topCmd) Run(ctx context.Context, log *log.Logger, opts *globalOptions) error {
repo, _, svc, err := openRepo(ctx, log, opts)
if err != nil {
return err
}
current, err := repo.CurrentBranch(ctx)
if err != nil {
// TODO: handle not a branch
return fmt.Errorf("get current branch: %w", err)
}
tops, err := svc.FindTop(ctx, current)
if err != nil {
return fmt.Errorf("find top-most branches: %w", err)
}
must.NotBeEmptyf(tops, "FindTopmost always returns at least one branch")
branch := tops[0]
if len(tops) > 1 {
desc := "There are multiple top-level branches reachable from the current branch."
if !opts.Prompt {
log.Error(desc)
return errNoPrompt
}
items := make([]widget.BranchTreeItem, len(tops))
for i, b := range tops {
items[i] = widget.BranchTreeItem{
Branch: b,
Base: current,
}
}
// If there are multiple top-most branches,
// prompt the user to pick one.
prompt := widget.NewBranchTreeSelect().
WithValue(&branch).
WithItems(items...).
WithTitle("Pick a branch").
WithDescription(desc)
if err := ui.Run(prompt); err != nil {
return fmt.Errorf("a branch is required: %w", err)
}
}
if branch == current && !cmd.DryRun {
log.Info("Already on the top-most branch in this stack")
return nil
}
return (&branchCheckoutCmd{
checkoutOptions: cmd.checkoutOptions,
Branch: branch,
}).Run(ctx, log, opts)
}