|
| 1 | +package stack |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + |
| 7 | + "github.com/cli/go-gh/v2/pkg/prompter" |
| 8 | + "github.com/github/gh-stack/internal/config" |
| 9 | + "github.com/github/gh-stack/internal/git" |
| 10 | +) |
| 11 | + |
| 12 | +// ResolveStack finds the stack for the given branch, handling ambiguity when |
| 13 | +// a branch (typically a trunk) belongs to multiple stacks. If exactly one |
| 14 | +// stack matches, it is returned directly. If multiple stacks match, the user |
| 15 | +// is prompted to select one and the working tree is switched to the top branch |
| 16 | +// of the selected stack. Returns nil with no error if no stack contains the |
| 17 | +// branch. |
| 18 | +func (sf *StackFile) ResolveStack(branch string, cfg *config.Config) (*Stack, error) { |
| 19 | + stacks := sf.FindAllStacksForBranch(branch) |
| 20 | + |
| 21 | + switch len(stacks) { |
| 22 | + case 0: |
| 23 | + return nil, nil |
| 24 | + case 1: |
| 25 | + return stacks[0], nil |
| 26 | + } |
| 27 | + |
| 28 | + if !cfg.IsInteractive() { |
| 29 | + return nil, fmt.Errorf("branch %q belongs to multiple stacks; use an interactive terminal to select one", branch) |
| 30 | + } |
| 31 | + |
| 32 | + cfg.Warningf("Branch %q is the trunk of multiple stacks\n", branch) |
| 33 | + |
| 34 | + options := make([]string, len(stacks)) |
| 35 | + for i, s := range stacks { |
| 36 | + options[i] = s.DisplayName() |
| 37 | + } |
| 38 | + |
| 39 | + p := prompter.New(os.Stdin, os.Stdout, os.Stderr) |
| 40 | + selected, err := p.Select("Which stack would you like to use?", "", options) |
| 41 | + if err != nil { |
| 42 | + return nil, fmt.Errorf("stack selection: %w", err) |
| 43 | + } |
| 44 | + |
| 45 | + s := stacks[selected] |
| 46 | + |
| 47 | + // Switch to the top branch of the selected stack so future commands |
| 48 | + // resolve unambiguously. |
| 49 | + topBranch := s.Branches[len(s.Branches)-1].Branch |
| 50 | + if topBranch != branch { |
| 51 | + if err := git.CheckoutBranch(topBranch); err != nil { |
| 52 | + return nil, fmt.Errorf("failed to checkout branch %s: %w", topBranch, err) |
| 53 | + } |
| 54 | + cfg.Successf("Switched to %s\n", topBranch) |
| 55 | + } |
| 56 | + |
| 57 | + return s, nil |
| 58 | +} |
0 commit comments