GitLabgitlab-org
cli
main
1package infer
3import (
4 "context"
5 "errors"
6 "fmt"
7 "strings"
8 "time"
10 "github.com/MakeNowJust/heredoc/v2"
11 "github.com/spf13/cobra"
13 "gitlab.com/gitlab-org/cli/internal/cmdutils"
14 "gitlab.com/gitlab-org/cli/internal/commands/stack/stackutils"
15 "gitlab.com/gitlab-org/cli/internal/git"
16 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
17 "gitlab.com/gitlab-org/cli/internal/text"
18 "gitlab.com/gitlab-org/cli/internal/utils"
19)
21type options struct {
22 stackName string
23 baseBranch string
24 allCommits bool
25}
27func NewCmdInferStack(f cmdutils.Factory, gr git.GitRunner) *cobra.Command {
28 o := &options{}
30 stackInferCmd := &cobra.Command{
31 Use: "infer <revision-range>",
32 Short: `Add diffs to a stack based on a range of commits. (EXPERIMENTAL)`,
33 Long: heredoc.Doc(`
34 Opens an editor with the commits in the range for you to choose from.
35 With --all, includes every commit in the range without opening an editor.
37 When you save and close the file (or pass --all), the command creates one diff for each commit listed in the file and appends them to the stack. If there's no stack to add them to, the command creates one first.
38 `) + text.ExperimentalString,
39 Example: heredoc.Doc(`
40 # Commit range syntax is similar to "git rev-list".
41 # The start of the range must be a branch name (not a relative ref like HEAD~5).
43 # Add diffs from the commits between main and the current branch
44 glab stack infer main..HEAD
46 # Add diffs from all commits between main and the current branch without an editor
47 glab stack infer --all main..HEAD
49 # Add diffs from the commits on a feature branch since it diverged from develop
50 glab stack infer develop..HEAD
52 # If there's no stack to add the diffs to, create one with a specific name
53 glab stack infer --name feature-stack main..HEAD
54 `),
55 Args: cobra.MinimumNArgs(1),
56 Annotations: map[string]string{
57 mcpannotations.Destructive: "true",
58 },
59 RunE: func(cmd *cobra.Command, args []string) error {
60 return run(cmd.Context(), f, gr, args, o)
61 },
62 }
64 stackInferCmd.Flags().StringVarP(&o.stackName, "name", "n", "", "Name for the new stack (used when creating a stack)")
65 stackInferCmd.Flags().BoolVarP(&o.allCommits, "all", "a", false, "Include all commits in the revision range without prompting")
67 return stackInferCmd
68}
70func parseBaseBranch(gr git.GitRunner, args []string) (string, error) {
71 for _, arg := range args {
72 if before, _, found := strings.Cut(arg, ".."); found {
73 return resolveBaseBranch(gr, before)
74 }
75 }
76 return "", nil
77}
79// resolveBaseBranch resolves a revision expression to a branch name.
80// Relative refs like HEAD~3 are not valid base branches because they drift
81// as new commits are added.
82func resolveBaseBranch(gr git.GitRunner, ref string) (string, error) {
83 branch, err := gr.Git("rev-parse", "--abbrev-ref", ref)
84 if err != nil {
85 return "", fmt.Errorf("could not resolve %q to a branch: %w", ref, err)
86 }
88 branch = strings.TrimSpace(branch)
90 // rev-parse --abbrev-ref returns the ref unchanged when it can't
91 // abbreviate it to a symbolic name (e.g. HEAD~3 stays HEAD~3).
92 // Detect this by checking if the resolved name still matches the
93 // original non-branch-like ref.
94 if branch == ref && strings.ContainsAny(ref, "~^@{}") {
95 return "", fmt.Errorf(
96 "%q is a relative revision, not a branch name. "+
97 "Use a branch name as the start of the range (e.g. main..HEAD)",
98 ref,
99 )
100 }
102 return branch, nil
103}
105func run(ctx context.Context, f cmdutils.Factory, gr git.GitRunner, args []string, o *options) error {
106 if err := stackutils.CheckNoRebaseInProgress(); err != nil {
107 return err
108 }
110 if !o.allCommits && !f.IO().IsOutputTTY() {
111 return errors.New("no TTY available: use --all to include all commits in the revision range (glab stack infer --all <revision-range>)")
112 }
114 baseBranch, err := parseBaseBranch(gr, args)
115 if err != nil {
116 return err
117 }
118 o.baseBranch = baseBranch
120 // check if in a stack
121 title, err := git.GetCurrentStackTitle()
122 if err != nil {
123 title, err = promptAndCreateStack(ctx, f, gr, o)
124 if err != nil {
125 return fmt.Errorf("could not create new stack: %w", err)
126 }
127 }
129 stack, err := git.GatherStackRefs(title)
130 if err != nil {
131 stack = git.Stack{Title: title, Refs: make(map[string]git.StackRef)}
132 }
134 io := f.IO()
135 color := io.Color()
137 io.StopSpinner("")
138 // pausing the spinner in case it's a terminal based editor
140 commits, err := promptForCommits(ctx, f, gr, args, o.allCommits)
141 if err != nil {
142 return fmt.Errorf("error getting commits for stack: %w", err)
143 }
145 if len(commits) == 0 {
146 return fmt.Errorf("no commits selected for stack")
147 }
149 io.StartSpinner("Creating stack diffs...")
150 defer io.StopSpinner("")
152 err = createBranches(f, gr, commits, title, stack)
153 if err != nil {
154 return fmt.Errorf("error creating stack diffs: %w", err)
155 }
157 io.StopSpinner("")
158 io.LogInfof("%s Added %d diff(s) to stack %q. Run `glab stack sync` to push and create merge requests.\n",
159 color.GreenCheck(), len(commits), title)
161 return nil
162}
164func createBranches(f cmdutils.Factory, gr git.GitRunner, commits []string, title string, stack git.Stack) error {
165 author, err := git.GitUserName()
166 if err != nil {
167 return fmt.Errorf("error getting Git author: %w", err)
168 }
170 originalBranch, err := gr.Git("symbolic-ref", "--quiet", "--short", "HEAD")
171 if err != nil {
172 return fmt.Errorf("error getting current branch: %w", err)
173 }
174 originalBranch = strings.TrimSpace(originalBranch)
176 restoreOriginalBranch := func() {
177 _, _ = gr.Git("checkout", originalBranch)
178 }
179 defer restoreOriginalBranch()
181 baseBranch, err := stack.BaseBranch(gr)
182 if err != nil {
183 return fmt.Errorf("error getting stack base branch: %w", err)
184 }
186 var prevSHA string
187 prevBranch := baseBranch
188 if !stack.Empty() {
189 last := stack.Last()
190 prevSHA = last.SHA
191 prevBranch = last.Branch
192 }
194 var createdBranches []string
195 var createdRefs []git.StackRef
196 modifiedRefs := make(map[string]git.StackRef) // original state of existing refs we modified
198 rollback := func() {
199 restoreOriginalBranch()
200 for _, b := range createdBranches {
201 _, _ = gr.Git("branch", "-D", b)
202 }
203 for _, ref := range createdRefs {
204 _ = git.DeleteStackRefFile(title, ref)
205 }
206 for _, originalRef := range modifiedRefs {
207 _ = git.UpdateStackRefFile(title, originalRef)
208 }
209 }
211 for i, commitHash := range commits {
212 description, err := stackutils.CommitSubject(gr, commitHash)
213 if err != nil {
214 rollback()
215 return fmt.Errorf("error getting commit subject for %s: %w", commitHash, err)
216 }
218 stackSHA, err := stackutils.GenerateStackSha(description, title, string(author), time.Now())
219 if err != nil {
220 rollback()
221 return fmt.Errorf("error generating stack SHA: %w", err)
222 }
224 branchName, err := stackutils.CreateShaBranch(f, stackSHA, title)
225 if err != nil {
226 rollback()
227 return fmt.Errorf("error creating branch name: %w", err)
228 }
230 _, err = gr.Git("checkout", "-b", branchName, prevBranch)
231 if err != nil {
232 rollback()
233 return fmt.Errorf("error creating branch %s from %s: %w", branchName, prevBranch, err)
234 }
235 createdBranches = append(createdBranches, branchName)
237 _, err = gr.Git("cherry-pick", commitHash)
238 if err != nil {
239 _, _ = gr.Git("cherry-pick", "--abort")
240 rollback()
241 return fmt.Errorf(
242 "conflict cherry-picking commit %d/%d (%s %q) onto %s. "+
243 "The selected commits may not be independent — try selecting a contiguous range",
244 i+1, len(commits), commitHash, description, prevBranch,
245 )
246 }
248 if prevSHA != "" {
249 prevRef := stack.Refs[prevSHA]
250 if _, tracked := modifiedRefs[prevSHA]; !tracked {
251 modifiedRefs[prevSHA] = prevRef // save original state before mutation
252 }
253 prevRef.Next = stackSHA
254 err = git.UpdateStackRefFile(title, prevRef)
255 if err != nil {
256 rollback()
257 return fmt.Errorf("error updating previous ref: %w", err)
258 }
259 stack.Refs[prevSHA] = prevRef
260 }
262 newRef := git.StackRef{
263 Prev: prevSHA,
264 SHA: stackSHA,
265 Branch: branchName,
266 Description: description,
267 }
269 err = git.AddStackRefFile(title, newRef)
270 if err != nil {
271 rollback()
272 return fmt.Errorf("error creating stack ref file: %w", err)
273 }
275 createdRefs = append(createdRefs, newRef)
276 stack.Refs[stackSHA] = newRef
277 prevSHA = stackSHA
278 prevBranch = branchName
279 }
281 return nil
282}
284// promptAndCreateStack creates a new stack with the provided name or prompts for one
285func promptAndCreateStack(ctx context.Context, f cmdutils.Factory, gr git.GitRunner, o *options) (string, error) {
286 var titleString string
288 if o.stackName != "" {
289 titleString = o.stackName
290 } else {
291 if !f.IO().IsOutputTTY() {
292 return "", fmt.Errorf("no stack found and no TTY available. Use --name to specify a stack name")
293 }
294 err := f.IO().Input(ctx, &titleString, "No stack found. Enter a name for a new stack:", "", func(s string) error {
295 if s == "" {
296 return fmt.Errorf("title is required")
297 }
298 return nil
299 })
300 if err != nil {
301 return "", fmt.Errorf("error prompting for title: %w", err)
302 }
303 }
305 io := f.IO()
306 color := io.Color()
308 title := utils.ReplaceNonAlphaNumericChars(titleString, "-")
309 if title != titleString {
310 io.LogErrorf("%s warning: invalid characters have been replaced with dashes: %s\n",
311 color.WarnIcon(),
312 color.Blue(title))
313 }
315 err := git.SetCurrentStackTitle(title)
316 if err != nil {
317 return "", fmt.Errorf("error setting current stack: %w", err)
318 }
320 _, err = git.AddStackRefDir(title)
321 if err != nil {
322 return "", fmt.Errorf("error adding stack metadata directory: %w", err)
323 }
325 baseBranch := o.baseBranch
326 if baseBranch == "" {
327 baseBranch, err = gr.Git("symbolic-ref", "--quiet", "--short", "HEAD")
328 if err != nil {
329 return "", fmt.Errorf("error determining current branch: %w", err)
330 }
331 }
333 err = git.AddStackBaseBranch(title, baseBranch)
334 if err != nil {
335 return "", fmt.Errorf("error adding base branch to metadata: %w", err)
336 }
338 io.LogInfof("New stack created with title %q.\n", title)
340 return title, nil
341}
Diagnostics8 git calls · 236 ms
CallStatusSizeTime0236 ms
discover200185 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB · hit2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=59849 git.response.cache=HIT git.response.duration_ms=2 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 1020032 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=44Open pack map
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:02001.8 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=1857 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=1857 git.pkt.payload.max=1830 git.sideband.band1.bytes=1830 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1830 git.pack.trailer=fb03183b7909876778f740d196d7516811003517Open pack map
fetchtree:0200432 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=432 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=ff2d1e7abc74964e5679ebdb51f1ac0d0dc3aff0 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=432 git.pkt.payload.max=405 git.sideband.band1.bytes=405 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=405 git.pack.trailer=8f3029a269217d94d12d0671e0490fe3d5506303Open pack map
fetchtree:0200199 B · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=199 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=8109696a12928135171f031112e487158b02c470 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=199 git.pkt.payload.max=172 git.sideband.band1.bytes=172 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=172 git.pack.trailer=7619d11a8f208890971c50dea8f51b0e072e21b9Open pack map
fetch2003.3 KiB220 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=220 git.response.bytes=3340 git.response.cache=MISS git.response.duration_ms=220 git.fetch.wants=b531c759e5bb878651411caeb8954791a2f57c42 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=3340 git.pkt.payload.max=3313 git.sideband.band1.bytes=3313 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://gitlab.com/gitlab-org/cli
- Ref
- refs/heads/main
- Commit
- 0dd7574dce9e385c5c30540e6c15657adc6bdce9
- cf-ray
- a5e21bd80943ecd4
- Request
- 0674c6d6…
- Protocol
- v2 · sha1
- Agent
- git/2.56.g1891de4-Linux
- Filter
- advertised
- Fetch
- shallow wait-for-done filter
- Capabilities
- agent ls-refs fetch server-option object-format