GitLabgitlab-org
cli
main
1package merge
3import (
4 "context"
5 "errors"
6 "fmt"
7 "net/http"
8 "time"
10 "charm.land/huh/v2"
11 "github.com/MakeNowJust/heredoc/v2"
12 "github.com/avast/retry-go/v5"
13 "github.com/spf13/cobra"
15 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
17 "gitlab.com/gitlab-org/cli/internal/cmdutils"
18 "gitlab.com/gitlab-org/cli/internal/commands/mr/mrutils"
19 "gitlab.com/gitlab-org/cli/internal/config"
20 "gitlab.com/gitlab-org/cli/internal/dbg"
21 "gitlab.com/gitlab-org/cli/internal/iostreams"
22 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
23)
25type MRMergeMethod int
27const (
28 MRMergeMethodMerge MRMergeMethod = iota
29 MRMergeMethodSquash
30 MRMergeMethodRebase
31)
33type options struct {
34 io *iostreams.IOStreams
35 gitlabClient func() (*gitlab.Client, error)
36 config func() config.Config
38 setAutoMerge bool
39 squashBeforeMerge bool
40 rebaseBeforeMerge bool
41 removeSourceBranch bool
42 skipPrompts bool
44 squashMessage string
45 mergeCommitMessage string
46 sha string
48 mergeMethod MRMergeMethod
49}
51func NewCmdMerge(f cmdutils.Factory) *cobra.Command {
52 opts := &options{
53 io: f.IO(),
54 gitlabClient: f.GitLabClient,
55 config: f.Config,
57 mergeMethod: MRMergeMethodMerge,
58 }
60 mrMergeCmd := &cobra.Command{
61 Use: "merge [<id | branch>]",
62 Short: `Merge or accept a merge request.`,
63 Long: heredoc.Docf(`
64 Defaults to the currently checked-out branch. When a pipeline is running,
65 auto-merge is enabled by default. Pass %[1]s--auto-merge=false%[1]s to
66 merge immediately. Use %[1]s--squash%[1]s or %[1]s--rebase%[1]s to control
67 the merge strategy, or %[1]s--remove-source-branch%[1]s to delete the
68 source branch after merging.
69 `, "`"),
70 Aliases: []string{"accept"},
71 Annotations: map[string]string{
72 mcpannotations.Destructive: "true",
73 },
74 Example: heredoc.Doc(`
75 # Merge a merge request
76 glab mr merge 235
77 glab mr accept 235
79 # Finds open merge request from current branch
80 glab mr merge`),
81 Args: cobra.MaximumNArgs(1),
82 RunE: func(cmd *cobra.Command, args []string) error {
83 if err := opts.validate(); err != nil {
84 return err
85 }
87 return opts.run(f, cmd, args)
88 },
89 }
91 mrMergeCmd.Flags().StringVarP(&opts.sha, "sha", "", "", "Merge only if the HEAD of the source branch matches this SHA. Use to ensure that only reviewed commits are merged.")
92 mrMergeCmd.Flags().BoolVarP(&opts.removeSourceBranch, "remove-source-branch", "d", false, "Remove source branch on merge.")
93 mrMergeCmd.Flags().BoolVarP(&opts.setAutoMerge, "auto-merge", "", true, "Set auto-merge.")
94 mrMergeCmd.Flags().StringVarP(&opts.mergeCommitMessage, "message", "m", "", "Custom merge commit message.")
95 mrMergeCmd.Flags().StringVarP(&opts.squashMessage, "squash-message", "", "", "Custom squash commit message.")
96 mrMergeCmd.Flags().BoolVarP(&opts.squashBeforeMerge, "squash", "s", false, "Squash commits on merge.")
97 mrMergeCmd.Flags().BoolVarP(&opts.rebaseBeforeMerge, "rebase", "r", false, "Rebase the commits onto the base branch.")
98 mrMergeCmd.Flags().BoolVarP(&opts.skipPrompts, "yes", "y", false, "Skip submission confirmation prompt.")
100 mrMergeCmd.Flags().BoolVarP(&opts.setAutoMerge, "when-pipeline-succeeds", "", true, "Merge only when pipeline succeeds")
101 _ = mrMergeCmd.Flags().MarkDeprecated("when-pipeline-succeeds", "use --auto-merge instead.")
102 mrMergeCmd.MarkFlagsMutuallyExclusive("squash", "rebase")
103 // A rebase replaces the head commit, so the merge would always fail the --sha check.
104 mrMergeCmd.MarkFlagsMutuallyExclusive("sha", "rebase")
106 return mrMergeCmd
107}
109func (o *options) validate() error {
110 if !o.squashBeforeMerge && o.squashMessage != "" {
111 return &cmdutils.FlagError{Err: errors.New("--squash-message can only be used with --squash")}
112 }
114 return nil
115}
117func (o *options) run(x cmdutils.Factory, cmd *cobra.Command, args []string) error {
118 c := o.io.Color()
120 apiClient, err := o.gitlabClient()
121 if err != nil {
122 return err
123 }
125 mr, repo, err := mrutils.MRFromArgs(cmd.Context(), x, args, "opened")
126 if err != nil {
127 return err
128 }
130 if err = mrutils.MRCheckErrors(mr, mrutils.MRCheckErrOptions{
131 Draft: true,
132 Closed: true,
133 Merged: true,
134 Conflict: true,
135 PipelineStatus: true,
136 MergePrivilege: true,
137 }); err != nil {
138 dbg.Debug("MRCheckErrors failed")
139 return err
140 }
142 if !cmd.Flags().Changed("when-pipeline-succeeds") &&
143 !cmd.Flags().Changed("auto-merge") &&
144 o.io.IsOutputTTY() &&
145 mr.Pipeline != nil &&
146 o.io.PromptEnabled() &&
147 !o.skipPrompts {
148 o.setAutoMerge = true
149 _ = x.IO().Confirm(cmd.Context(), &o.setAutoMerge, "Set auto-merge?")
150 }
152 if o.io.IsOutputTTY() && !o.skipPrompts {
153 if !o.squashBeforeMerge && !o.rebaseBeforeMerge && o.mergeCommitMessage == "" {
154 o.mergeMethod, err = mergeMethodSurvey(cmd.Context(), o.io, o.sha == "")
155 if err != nil {
156 return err
157 }
158 switch o.mergeMethod {
159 case MRMergeMethodSquash:
160 o.squashBeforeMerge = true
161 case MRMergeMethodRebase:
162 o.rebaseBeforeMerge = true
163 }
164 }
166 if o.mergeCommitMessage == "" && o.squashMessage == "" {
167 action, err := confirmSurvey(cmd.Context(), x, o.mergeMethod != MRMergeMethodRebase)
168 if err != nil {
169 // iostreams.Run already prints "Cancelled." for user cancellation
170 if errors.Is(err, iostreams.ErrUserCancelled) {
171 return cmdutils.SilentError
172 }
173 return err
174 }
176 if action == cmdutils.EditCommitMessageAction {
177 var mergeMessage string
179 editor, err := cmdutils.GetEditor(o.config)
180 if err != nil {
181 return err
182 }
183 err = o.io.Editor(cmd.Context(), &mergeMessage, "Merge commit message", "", mr.Title, editor)
184 if err != nil {
185 return err
186 }
188 if o.squashBeforeMerge {
189 o.squashMessage = mergeMessage
190 } else {
191 o.mergeCommitMessage = mergeMessage
192 }
194 action, err = confirmSurvey(cmd.Context(), x, false)
195 if err != nil {
196 // iostreams.Run already prints "Cancelled." for user cancellation
197 if errors.Is(err, iostreams.ErrUserCancelled) {
198 return cmdutils.SilentError
199 }
200 return err
201 }
202 }
203 if action == cmdutils.CancelAction {
204 o.io.LogError("Cancelled.")
205 return cmdutils.SilentError
206 }
207 }
208 }
210 mergeOpts := &gitlab.AcceptMergeRequestOptions{}
211 if o.mergeCommitMessage != "" {
212 mergeOpts.MergeCommitMessage = new(o.mergeCommitMessage)
213 }
214 if o.squashMessage != "" {
215 mergeOpts.SquashCommitMessage = new(o.squashMessage)
216 }
217 if o.squashBeforeMerge {
218 mergeOpts.Squash = new(true)
219 }
220 if o.removeSourceBranch {
221 mergeOpts.ShouldRemoveSourceBranch = new(true)
222 }
223 if o.setAutoMerge && mr.Pipeline != nil {
224 if mr.Pipeline.Status == "canceled" || mr.Pipeline.Status == "failed" {
225 o.io.LogInfo(c.FailedIcon(), "Pipeline status:", mr.Pipeline.Status)
226 o.io.LogInfo(c.FailedIcon(), "Cannot perform merge action")
227 return cmdutils.SilentError
228 }
229 mergeOpts.AutoMerge = new(true)
230 }
231 if o.sha != "" {
232 mergeOpts.SHA = new(o.sha)
233 }
235 if o.rebaseBeforeMerge {
236 err := mrutils.RebaseMR(cmd.Context(), o.io, apiClient, repo, mr, nil)
237 if err != nil {
238 return err
239 }
240 }
242 o.io.StartSpinner("Merging merge request !%d.", mr.IID)
244 // Store the IID of the merge request here before overriding the `mr` variable
245 // inside the retry function, if the function fails at first the `mr` is replaced
246 // with `nil` and will cause a crash on the second run
247 mrIID := mr.IID
249 err = retry.New(
250 retry.Attempts(3),
251 retry.Delay(time.Second*6),
252 ).Do(func() error {
253 mr, _, err = apiClient.MergeRequests.AcceptMergeRequest(repo.FullName(), mrIID, mergeOpts)
254 if err != nil {
255 // https://docs.gitlab.com/api/merge_requests/#merge-a-merge-request
256 // `406` is the documented status code we will receive if the
257 // branch cannot be merged, this will catch situations where
258 // there are actually conflicts in the branch instead of just
259 // the situation we want to workaround (GitLab thinking branch
260 // is not mergeable right after a rebase), but we want to catch
261 // situations where the user rebased via external sources like
262 // the WebUI or running `glab rebase` before trying to merge
263 if gitlab.HasStatusCode(err, http.StatusNotAcceptable) {
264 return err
265 }
267 // Return an unrecoverable error if we are not rebasing OR if the
268 // error isn't the one we are working around, this makes the retry
269 // to quit instead of trying again
270 return retry.Unrecoverable(err)
271 }
272 return err
273 })
274 if err != nil {
275 return err
276 }
277 o.io.StopSpinner("")
279 // After a successful AcceptMergeRequest the merge request is merged
280 // (mr.State == "merged"), armed for auto-merge (open with
281 // MergeWhenPipelineSucceeds), or still open for some other reason. Only the
282 // merged state is an unambiguous success; anything else surfaces the API's
283 // merge status verbatim rather than guessing whether the merge happened.
285 // Report the pipeline state when auto-merge was requested.
286 if o.setAutoMerge {
287 switch {
288 case mr.Pipeline == nil:
289 o.io.LogInfo(c.WarnIcon(), "No pipeline has been run on", mr.SourceBranch)
290 case mr.Pipeline.Status == "success":
291 o.io.LogInfo(c.GreenCheck(), "Pipeline succeeded.")
292 default:
293 o.io.LogInfo(c.WarnIcon(), "Pipeline status:", mr.Pipeline.Status)
294 }
295 }
297 // Report the merge status.
298 switch {
299 case mr.State == "merged":
300 var action string
301 switch o.mergeMethod {
302 case MRMergeMethodRebase:
303 action = "Rebased and merged!"
304 case MRMergeMethodSquash:
305 action = "Squashed and merged!"
306 default:
307 action = "Merged!"
308 }
309 o.io.LogInfo(c.GreenCheck(), action)
310 case mr.MergeWhenPipelineSucceeds:
311 o.io.LogInfo(c.GreenCheck(), "Auto-merge enabled")
312 default:
313 o.io.LogInfo(c.WarnIcon(), "Merge status:", mr.DetailedMergeStatus)
314 }
315 o.io.LogInfo(mrutils.DisplayMR(c, &mr.BasicMergeRequest, o.io.IsaTTY))
316 return nil
317}
319// allowRebase is false with --sha, for the same reason the two flags are mutually exclusive.
320func mergeMethodSurvey(ctx context.Context, io *iostreams.IOStreams, allowRebase bool) (MRMergeMethod, error) {
321 type mergeOption struct {
322 title string
323 method MRMergeMethod
324 }
326 mergeOpts := []mergeOption{{title: "Create a merge commit", method: MRMergeMethodMerge}}
327 if allowRebase {
328 mergeOpts = append(mergeOpts, mergeOption{title: "Rebase and merge", method: MRMergeMethodRebase})
329 }
330 mergeOpts = append(mergeOpts, mergeOption{title: "Squash and merge", method: MRMergeMethodSquash})
332 var options []string
333 for _, v := range mergeOpts {
334 options = append(options, v.title)
335 }
337 var selectedTitle string
338 err := io.Select(ctx, &selectedTitle, "What merge method do you want to use?", options)
339 if err != nil {
340 return MRMergeMethodMerge, err
341 }
343 // Find the method corresponding to the selected title
344 for _, opt := range mergeOpts {
345 if opt.title == selectedTitle {
346 return opt.method, nil
347 }
348 }
350 return 0, fmt.Errorf("invalid merge method selected")
351}
353func confirmSurvey(ctx context.Context, f cmdutils.Factory, allowEditMsg bool) (cmdutils.Action, error) {
354 const (
355 submitLabel = "Submit"
356 editCommitMsgLabel = "Edit commit message"
357 cancelLabel = "Cancel"
358 )
360 // If only 2 options (Submit/Cancel), use huh.NewConfirm()
361 if !allowEditMsg {
362 shouldSubmit := false // default value
364 confirm := huh.NewConfirm().
365 Title("What's next?").
366 Affirmative(submitLabel).
367 Negative(cancelLabel).
368 Value(&shouldSubmit)
370 err := f.IO().Run(ctx, confirm)
371 if err != nil {
372 return cmdutils.CancelAction, fmt.Errorf("could not prompt: %w", err)
373 }
375 if shouldSubmit {
376 return cmdutils.SubmitAction, nil
377 }
378 return cmdutils.CancelAction, nil
379 }
381 // If 3 options (Submit/Edit/Cancel), use huh.NewSelect()
382 var result string
383 selector := huh.NewSelect[string]().
384 Title("What's next?").
385 Options(
386 huh.NewOption(submitLabel, submitLabel),
387 huh.NewOption(editCommitMsgLabel, editCommitMsgLabel),
388 huh.NewOption(cancelLabel, cancelLabel),
389 ).
390 Value(&result)
392 err := f.IO().Run(ctx, selector)
393 if err != nil {
394 return cmdutils.CancelAction, fmt.Errorf("could not prompt: %w", err)
395 }
397 switch result {
398 case submitLabel:
399 return cmdutils.SubmitAction, nil
400 case editCommitMsgLabel:
401 return cmdutils.EditCommitMessageAction, nil
402 default:
403 return cmdutils.CancelAction, nil
404 }
405}
Diagnostics8 git calls · 205 ms
CallStatusSizeTime0205 ms
discover200185 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 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 KiB2 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=UPDATING 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
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=2 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:0 · deepen 1020032 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=4 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
fetchtree:02001.8 KiB · hit2 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=2 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:0200746 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=746 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=f3d413a22af5a9c2fe9aa49709b1cb36d1351a7f 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=746 git.pkt.payload.max=719 git.sideband.band1.bytes=719 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=719 git.pack.trailer=330baf80c59a4208b55120dff7dd824b7952b790Open pack map
fetchtree:0200172 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=194 git.response.bytes=172 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=953ab3e24790f4fadab9c9378f4da52e55f6cfbd 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=172 git.pkt.payload.max=145 git.sideband.band1.bytes=145 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=145 git.pack.trailer=b3e7e8a27b0e6b08fa0e1a91ed04acbcc4134bf1Open pack map
fetch2003.9 KiB194 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=4037 git.response.cache=MISS git.response.duration_ms=194 git.fetch.wants=3c3628be06e06344c2a23770d761dea5c43b2c71 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=4037 git.pkt.payload.max=4010 git.sideband.band1.bytes=4010 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
- a5e33a070af5f162
- Request
- 25e553d6…
- 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