Skip to content

Commit 329aef4

Browse files
committed
Support addressing a stack by its stack number
checkout now interprets a bare integer as a stack number first (the identifier shown in the github.com stack UI), falling back to a locally tracked PR number, then a PR number discovered from GitHub, then a branch name. A new checkoutStackByNumber resolves the stack via GetStack and checks out its top-most unmerged branch; the reconcile/import logic is shared with the PR-number path. unstack gains an optional <stack-number> positional argument to unstack a specific locally tracked stack instead of the current one. Copilot-Session: 03673c26-a245-42da-93ed-dfcebc92a740
1 parent da1c96e commit 329aef4

5 files changed

Lines changed: 311 additions & 31 deletions

File tree

‎cmd/checkout.go‎

Lines changed: 94 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,14 @@ func CheckoutCmd(cfg *config.Config) *cobra.Command {
2323
opts := &checkoutOptions{}
2424

2525
cmd := &cobra.Command{
26-
Use: "checkout [<pr-number> | <pr-url> | <branch>]",
27-
Short: "Checkout a stack from a PR number, PR URL, or branch name",
28-
Long: `Check out a stack from a pull request number, PR URL, or branch name.
26+
Use: "checkout [<stack-number> | <pr-number> | <pr-url> | <branch>]",
27+
Short: "Checkout a stack by stack number, PR number, PR URL, or branch name",
28+
Long: `Check out a stack by stack number, pull request number, PR URL, or branch name.
29+
30+
A bare number is interpreted first as a stack number (the identifier shown in
31+
the GitHub stack UI). If no stack has that number, it is then tried as a
32+
locally tracked PR number, then a PR number whose stack is discovered from
33+
GitHub, and finally a branch name.
2934
3035
When a PR number or PR URL is provided (e.g. 123 or
3136
https://github.com/owner/repo/pull/123), the command first checks
@@ -39,7 +44,10 @@ locally tracked stacks only.
3944
4045
When run without arguments, shows a menu of all locally available
4146
stacks to choose from.`,
42-
Example: ` # Check out a stack by PR number
47+
Example: ` # Check out a stack by its stack number
48+
$ gh stack checkout 7
49+
50+
# Check out a stack by PR number
4351
$ gh stack checkout 42
4452
4553
# Check out a stack by PR URL
@@ -138,28 +146,35 @@ func runCheckout(cfg *config.Config, opts *checkoutOptions) error {
138146
}
139147

140148
// resolveNumericTarget handles the case where the user passes a pure integer.
141-
// It tries, in order:
142-
// 1. Local stack lookup by PR number
143-
// 2. Remote API discovery (ListStacks → find → import)
144-
// 3. Local stack lookup by branch name (for numeric branch names like "123")
145-
func resolveNumericTarget(cfg *config.Config, sf *stack.StackFile, gitDir string, prNumber int, raw string) (*stack.Stack, string, error) {
146-
// 1. Try local PR number lookup
147-
if s, br := sf.FindStackByPRNumber(prNumber); s != nil && br != nil {
149+
// The integer is interpreted as, in order:
150+
// 1. A stack number (the primary identifier)
151+
// 2. A locally tracked PR number
152+
// 3. A PR number whose stack is discovered from GitHub
153+
// 4. A branch name (for numeric branch names like "123")
154+
func resolveNumericTarget(cfg *config.Config, sf *stack.StackFile, gitDir string, number int, raw string) (*stack.Stack, string, error) {
155+
// 1. Try as a stack number (the primary identifier).
156+
if s, targetBranch, err := checkoutStackByNumber(cfg, sf, gitDir, number); err == nil {
157+
return s, targetBranch, nil
158+
} else if !errors.Is(err, errStackNumberNotFound) {
159+
// A real error (composition conflict, interrupted import, etc.) — surface it.
160+
return nil, "", err
161+
}
162+
163+
// 2. Try a locally tracked PR number.
164+
if s, br := sf.FindStackByPRNumber(number); s != nil && br != nil {
148165
return s, br.Branch, nil
149166
}
150167

151-
// 2. Try remote API
152-
s, targetBranch, err := checkoutRemoteStack(cfg, sf, gitDir, prNumber)
168+
// 3. Try a PR number whose stack is on GitHub.
169+
s, targetBranch, err := checkoutRemoteStack(cfg, sf, gitDir, number)
153170
if err == nil {
154171
return s, targetBranch, nil
155172
}
156-
// If the API returned a definitive "not in a stack" or a real error,
157-
// fall through to the branch-name attempt only for "not in stack".
158-
// For API failures (404, network errors), still fall through —
159-
// the user might have a numeric branch name.
173+
// For API failures or "not in a stack", still fall through to the branch-name
174+
// attempt — the user might have a numeric branch name.
160175
remoteErr := err
161176

162-
// 3. Fall back to branch name lookup (handles numeric branch names)
177+
// 4. Fall back to branch name lookup (handles numeric branch names).
163178
stacks := sf.FindAllStacksForBranch(raw)
164179
if len(stacks) > 0 {
165180
s := stacks[0]
@@ -212,23 +227,78 @@ func checkoutRemoteStack(cfg *config.Config, sf *stack.StackFile, gitDir string,
212227
return nil, "", ErrAPIFailure
213228
}
214229

215-
// Determine trunk (base branch of the first PR) and the target branch
230+
// Determine trunk (base branch of the first PR) and the target branch (the
231+
// branch for the requested PR).
216232
trunk := prs[0].BaseRefName
217233
var targetBranch string
218-
allMerged := true
219234
for _, pr := range prs {
220235
if pr.Number == prNumber {
221236
targetBranch = pr.HeadRefName
222-
}
223-
if !pr.Merged {
224-
allMerged = false
237+
break
225238
}
226239
}
227240
if targetBranch == "" {
228241
cfg.Errorf("could not determine branch for PR #%d", prNumber)
229242
return nil, "", ErrAPIFailure
230243
}
231244

245+
return reconcileAndImportRemoteStack(cfg, client, sf, gitDir, remoteStack, prs, trunk, targetBranch)
246+
}
247+
248+
// errStackNumberNotFound is returned by checkoutStackByNumber when a numeric
249+
// argument does not resolve to a stack (no such stack, stacks unavailable, or
250+
// any lookup failure), signalling the caller to try interpreting the argument
251+
// as a PR number or branch name instead.
252+
var errStackNumberNotFound = errors.New("stack number not found")
253+
254+
// checkoutStackByNumber discovers a stack from GitHub by its stack number,
255+
// reconciles it with any local state, and checks out the top-most unmerged
256+
// branch. It returns errStackNumberNotFound when the number does not resolve to
257+
// a stack so the caller can fall back to other interpretations.
258+
func checkoutStackByNumber(cfg *config.Config, sf *stack.StackFile, gitDir string, stackNumber int) (*stack.Stack, string, error) {
259+
client, err := cfg.GitHubClient()
260+
if err != nil {
261+
return nil, "", errStackNumberNotFound
262+
}
263+
264+
remoteStack, err := client.GetStack(stackNumber)
265+
if err != nil || remoteStack == nil || len(remoteStack.PullRequests) == 0 {
266+
// No such stack, stacks unavailable, or a transient failure — let the
267+
// caller try the number as a PR number or branch name.
268+
return nil, "", errStackNumberNotFound
269+
}
270+
271+
prs, err := fetchStackPRDetails(client, remoteStack.PRNumbers())
272+
if err != nil {
273+
cfg.Errorf("failed to fetch PR details: %v", err)
274+
return nil, "", ErrAPIFailure
275+
}
276+
277+
trunk := prs[0].BaseRefName
278+
// Target the top-most unmerged branch, falling back to the very top.
279+
targetBranch := prs[len(prs)-1].HeadRefName
280+
for i := len(prs) - 1; i >= 0; i-- {
281+
if !prs[i].Merged {
282+
targetBranch = prs[i].HeadRefName
283+
break
284+
}
285+
}
286+
287+
return reconcileAndImportRemoteStack(cfg, client, sf, gitDir, remoteStack, prs, trunk, targetBranch)
288+
}
289+
290+
// reconcileAndImportRemoteStack reconciles a resolved remote stack with local
291+
// state — adopting a matching local stack, resolving composition conflicts, or
292+
// importing the stack from the remote — and returns the resolved local stack
293+
// and the branch to check out.
294+
func reconcileAndImportRemoteStack(cfg *config.Config, client github.ClientOps, sf *stack.StackFile, gitDir string, remoteStack *github.RemoteStack, prs []*github.PullRequest, trunk, targetBranch string) (*stack.Stack, string, error) {
295+
allMerged := true
296+
for _, pr := range prs {
297+
if !pr.Merged {
298+
allMerged = false
299+
break
300+
}
301+
}
232302
if allMerged {
233303
cfg.Infof("All PRs in this stack have been merged")
234304
cfg.Printf("To start a new stack, use `%s`", cfg.ColorCyan("gh stack init"))
@@ -237,7 +307,7 @@ func checkoutRemoteStack(cfg *config.Config, sf *stack.StackFile, gitDir string,
237307

238308
remoteStackID := strconv.Itoa(remoteStack.ID)
239309

240-
// Step 3: Check if the target branch is already in a local stack
310+
// Check if the target branch is already in a local stack.
241311
localStack := findLocalStackForRemotePRs(sf, prs)
242312

243313
if localStack != nil {

‎cmd/checkout_test.go‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,76 @@ func TestCheckout_NumericTarget_NewStack(t *testing.T) {
284284
assert.Equal(t, 12, sf.Stacks[0].Branches[2].PullRequest.Number)
285285
}
286286

287+
func TestCheckout_ByStackNumber(t *testing.T) {
288+
gitDir := t.TempDir()
289+
var checkedOut string
290+
var createdBranches []string
291+
292+
restore := git.SetOps(&git.MockOps{
293+
GitDirFn: func() (string, error) { return gitDir, nil },
294+
CurrentBranchFn: func() (string, error) { return "main", nil },
295+
BranchExistsFn: func(name string) bool { return name == "main" },
296+
FetchFn: func(remote string) error { return nil },
297+
CreateBranchFn: func(name, base string) error {
298+
createdBranches = append(createdBranches, name)
299+
return nil
300+
},
301+
SetUpstreamTrackingFn: func(branch, remote string) error { return nil },
302+
ResolveRemoteFn: func(branch string) (string, error) { return "origin", nil },
303+
CheckoutBranchFn: func(name string) error {
304+
checkedOut = name
305+
return nil
306+
},
307+
RevParseFn: func(ref string) (string, error) { return "abc123", nil },
308+
RevParseMultiFn: func(refs []string) ([]string, error) {
309+
shas := make([]string, len(refs))
310+
for i := range refs {
311+
shas[i] = "abc123"
312+
}
313+
return shas, nil
314+
},
315+
})
316+
defer restore()
317+
318+
require.NoError(t, stack.Save(gitDir, &stack.StackFile{SchemaVersion: 1, Stacks: []stack.Stack{}}))
319+
320+
var gotStackNumber int
321+
cfg, outR, errR := config.NewTestConfig()
322+
cfg.GitHubClientOverride = &github.MockClient{
323+
GetStackFn: func(n int) (*github.RemoteStack, error) {
324+
gotStackNumber = n
325+
if n == 7 {
326+
return &github.RemoteStack{ID: 42, Number: 7, PullRequests: []int{10, 11, 12}}, nil
327+
}
328+
return nil, &api.HTTPError{StatusCode: 404, Message: "Not Found"}
329+
},
330+
FindPRByNumberFn: func(number int) (*github.PullRequest, error) {
331+
prs := map[int]*github.PullRequest{
332+
10: {ID: "PR_10", Number: 10, HeadRefName: "feat-1", BaseRefName: "main", URL: "https://github.com/o/r/pull/10"},
333+
11: {ID: "PR_11", Number: 11, HeadRefName: "feat-2", BaseRefName: "feat-1", URL: "https://github.com/o/r/pull/11"},
334+
12: {ID: "PR_12", Number: 12, HeadRefName: "feat-3", BaseRefName: "feat-2", URL: "https://github.com/o/r/pull/12"},
335+
}
336+
return prs[number], nil
337+
},
338+
}
339+
340+
err := runCheckout(cfg, &checkoutOptions{target: "7"})
341+
output := collectOutput(cfg, outR, errR)
342+
343+
require.NoError(t, err)
344+
assert.Equal(t, 7, gotStackNumber, "should look the stack up by its number")
345+
// The top-most (last) branch of the stack is checked out.
346+
assert.Equal(t, "feat-3", checkedOut)
347+
assert.Contains(t, output, "Imported stack with 3 branches")
348+
349+
// Verify the stack was imported with both its internal id and stack number.
350+
sf, loadErr := stack.Load(gitDir)
351+
require.NoError(t, loadErr)
352+
require.Len(t, sf.Stacks, 1)
353+
assert.Equal(t, "42", sf.Stacks[0].ID)
354+
assert.Equal(t, 7, sf.Stacks[0].Number)
355+
}
356+
287357
func TestCheckout_NumericTarget_BranchExistsNoStack(t *testing.T) {
288358
gitDir := t.TempDir()
289359
var checkedOut string

‎cmd/unstack.go‎

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package cmd
22

33
import (
44
"errors"
5+
"strconv"
56

67
"github.com/cli/go-gh/v2/pkg/api"
78
"github.com/github/gh-stack/internal/config"
@@ -11,24 +12,44 @@ import (
1112
)
1213

1314
type unstackOptions struct {
14-
local bool
15+
local bool
16+
stackNumber int
1517
}
1618

1719
func UnstackCmd(cfg *config.Config) *cobra.Command {
1820
opts := &unstackOptions{}
1921

2022
cmd := &cobra.Command{
21-
Use: "unstack",
23+
Use: "unstack [<stack-number>]",
2224
Aliases: []string{"delete"},
23-
Short: "Delete a stack locally and on GitHub",
24-
Long: "Remove the current active stack from local tracking and delete it on GitHub. Use --local to only remove local tracking. Full unstack is blocked when every pull request is queued for merge, merging, or already merged",
25-
Example: ` # Delete the stack locally and on GitHub
25+
Short: "Remove a stack locally and on GitHub",
26+
Long: `Remove a stack from local tracking and unstack it on GitHub.
27+
28+
With no argument, the current active stack is used. Provide a stack number (the
29+
identifier shown in the github.com stack UI) to unstack a specific locally
30+
tracked stack instead. Use --local to only remove local tracking.
31+
32+
GitHub decides which pull requests can be unstacked: PRs that are queued for
33+
merge or have auto-merge enabled are left stacked. When some pull requests
34+
remain stacked, local tracking is kept.`,
35+
Example: ` # Unstack the current stack locally and on GitHub
2636
$ gh stack unstack
2737
38+
# Unstack a specific stack by its stack number
39+
$ gh stack unstack 7
40+
2841
# Only remove local tracking (keep the stack on GitHub)
2942
$ gh stack unstack --local`,
30-
Args: cobra.NoArgs,
43+
Args: cobra.MaximumNArgs(1),
3144
RunE: func(cmd *cobra.Command, args []string) error {
45+
if len(args) == 1 {
46+
n, err := strconv.Atoi(args[0])
47+
if err != nil || n <= 0 {
48+
cfg.Errorf("invalid stack number %q", args[0])
49+
return ErrInvalidArgs
50+
}
51+
opts.stackNumber = n
52+
}
3253
return runUnstack(cfg, opts)
3354
},
3455
}
@@ -39,7 +60,13 @@ func UnstackCmd(cfg *config.Config) *cobra.Command {
3960
}
4061

4162
func runUnstack(cfg *config.Config, opts *unstackOptions) error {
42-
result, err := loadStack(cfg, "")
63+
var result *loadStackResult
64+
var err error
65+
if opts.stackNumber > 0 {
66+
result, err = loadStackByNumber(cfg, opts.stackNumber)
67+
} else {
68+
result, err = loadStack(cfg, "")
69+
}
4370
if err != nil {
4471
return ErrNotInStack
4572
}

0 commit comments

Comments
 (0)