GitLabgitlab-org
cli
main
1package create
3import (
4 "context"
5 "errors"
6 "fmt"
7 "net/url"
8 "os"
9 "regexp"
10 "strconv"
11 "strings"
13 "charm.land/huh/v2"
14 "github.com/MakeNowJust/heredoc/v2"
15 "github.com/spf13/cobra"
17 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
19 "gitlab.com/gitlab-org/cli/internal/api"
20 "gitlab.com/gitlab-org/cli/internal/cmdutils"
21 "gitlab.com/gitlab-org/cli/internal/commands/issue/issueutils"
22 "gitlab.com/gitlab-org/cli/internal/commands/mr/mrutils"
23 "gitlab.com/gitlab-org/cli/internal/config"
24 "gitlab.com/gitlab-org/cli/internal/git"
25 "gitlab.com/gitlab-org/cli/internal/glrepo"
26 "gitlab.com/gitlab-org/cli/internal/iostreams"
27 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
28 "gitlab.com/gitlab-org/cli/internal/recovery"
29 "gitlab.com/gitlab-org/cli/internal/text"
30 "gitlab.com/gitlab-org/cli/internal/utils"
31)
33type options struct {
34 Title string `json:"title,omitempty"`
35 Description string `json:"description,omitempty"`
36 Attach []string `json:"attach,omitempty"`
37 SourceBranch string `json:"source_branch,omitempty"`
38 TargetBranch string `json:"target_branch,omitempty"`
39 TargetTrackingBranch string `json:"target_tracking_branch,omitempty"`
40 Labels []string `json:"labels,omitempty"`
41 Assignees []string `json:"assignees,omitempty"`
42 Reviewers []string `json:"reviewers,omitempty"`
43 Milestone int64 `json:"milestone,omitempty"`
44 MilestoneFlag string `json:"milestone_flag,omitempty"`
45 MRCreateTargetProject string `json:"mr_create_target_project,omitempty"`
46 Template string `json:"template,omitempty"`
48 RelatedIssue string `json:"related_issue,omitempty"`
49 CopyIssueLabels bool `json:"copy_issue_labels,omitempty"`
51 CreateSourceBranch bool `json:"create_source_branch,omitempty"`
52 RemoveSourceBranch *bool `json:"remove_source_branch,omitempty"`
53 AllowCollaboration *bool `json:"allow_collaboration,omitempty"`
54 SquashBeforeMerge *bool `json:"squash_before_merge,omitempty"`
55 AutoMerge bool `json:"auto_merge,omitempty"`
57 Autofill bool `json:"autofill,omitempty"`
58 FillCommitBody bool `json:"fill_commit_body,omitempty"`
59 IsDraft bool `json:"is_draft,omitempty"`
60 IsWIP bool `json:"is_wip,omitempty"`
61 ShouldPush bool `json:"should_push,omitempty"`
63 noEditor bool
64 needsPrompt bool
65 yes bool
66 web bool
67 recover bool
68 signoff bool
69 pushSet bool
71 // Unexported, so a recovery file keeps the description the user wrote.
72 body string
74 io *iostreams.IOStreams `json:"-"`
75 branch func() (string, error) `json:"-"`
76 remotes func() (glrepo.Remotes, error) `json:"-"`
77 gitlabClient func() (*gitlab.Client, error) `json:"-"`
78 config func() config.Config `json:"-"`
79 baseRepo func() (glrepo.Interface, error) `json:"-"`
80 headRepo func() (glrepo.Interface, error) `json:"-"`
81 apiClient func(repoHost string) (*api.Client, error)
82 defaultHostname string
84 // SourceProject is the Project we create the merge request in and where we push our branch
85 // it is the project we have permission to push so most likely one's fork
86 SourceProject *gitlab.Project `json:"source_project,omitempty"`
87 // TargetProject is the one we query for changes between our branch and the target branch
88 // it is the one we merge request will appear in
89 TargetProject *gitlab.Project `json:"target_project,omitempty"`
90}
92func NewCmdCreate(f cmdutils.Factory) *cobra.Command {
93 opts := &options{
94 io: f.IO(),
95 branch: f.Branch,
96 remotes: f.Remotes,
97 gitlabClient: f.GitLabClient,
98 config: f.Config,
99 baseRepo: f.BaseRepo,
100 apiClient: f.ApiClient,
101 defaultHostname: f.DefaultHostname(),
102 }
104 mrCreateCmd := &cobra.Command{
105 Use: "create",
106 Short: `Create a new merge request.`,
107 Long: heredoc.Docf(`
108 Defaults to the current branch as the source branch. Use %[1]s--fill%[1]s
109 to automatically fill the title and description from the commit history. Use
110 %[1]s--draft%[1]s to create a draft merge request.
112 %[1]s--attach%[1]s uploads a file and references it at the end of the description. Repeat the flag for more than one file, or pass %[1]s-%[1]s to read the file from standard input. Files upload to the target project, so the references resolve even for a merge request from a fork.
113 %[2]s
114 The %[1]s--recover%[1]s flag is an experiment: it might be unstable or
115 removed at any time, and is not ready for production use. For more
116 information, see
117 https://docs.gitlab.com/policy/development_stages_support/.
118 `, "`", fmt.Sprintf(text.ExperimentalFlagString, "`--attach`")),
119 Aliases: []string{"new"},
120 Example: heredoc.Doc(`
121 # Create a merge request interactively from the current branch
122 glab mr new
124 # Assign a user and set a title without prompting for description
125 glab mr create -a username -t "fix annoying bug"
127 # Fill title and description from commits, mark as draft, add a label
128 glab mr create -f --draft --label RFC
130 # Fill from commits and preview the compare page in the browser
131 glab mr create --fill --web
133 # Fill from commits, expand each commit body into the description
134 glab mr create --fill --fill-commit-body --yes
136 # Fill from commits without pushing, for a branch already on the remote
137 glab mr create --fill --push=false --yes
139 # Use a merge request template for the description
140 glab mr create -t "Fix login bug" --template bug_fix
141 glab mr create -t "Security patch" --template security_fix.md --yes
143 # Use a template file from outside the repository
144 glab mr create -t "Fix login bug" --template ~/team-templates/bug_fix.md
146 # Create against another project without a local clone. All inputs must be passed as flags; no --push, --fill, or --template.
147 glab mr create --repo group/project --source-branch feature-branch --target-branch main --title "Add feature" --description "Details..." --yes
149 # Create a fork merge request from your fork into the upstream project, without a local clone.
150 glab mr create --repo upstream/project --head your-namespace/project --source-branch feature-branch --target-branch main --title "Add feature" --description "Details..." --yes
152 # Read the description from a file
153 glab mr create -t "Fix login bug" --description-file description.md
155 # Read the description from standard input
156 cat description.md | glab mr create -t "Fix login bug" --description-file -
158 # Attach a screenshot to the description
159 glab mr create -t "Fix login bug" -d "Before and after:" --attach ./before.png --attach ./after.png`),
160 Args: cobra.NoArgs,
161 ValidArgsFunction: cobra.NoFileCompletions,
162 PreRun: func(cmd *cobra.Command, args []string) {
163 repoOverride, _ := cmd.Flags().GetString("head")
164 if repoFromEnv := os.Getenv("GITLAB_HEAD_REPO"); repoOverride == "" && repoFromEnv != "" {
165 repoOverride = repoFromEnv
166 }
167 if repoOverride != "" {
168 headRepoOverride(opts, repoOverride)
169 return
170 }
172 // Only fall back to baseRepo when there is no local git repo (or no
173 // remotes at all). Actionable resolver errors — GITLAB_HOST mismatch,
174 // unknown GitLab host — must propagate so the user sees the diagnostic.
175 resolved := ResolvedHeadRepo(cmd.Context(), f)
176 opts.headRepo = func() (glrepo.Interface, error) {
177 _, err := f.Remotes()
178 switch {
179 case err == nil:
180 return resolved()
181 case errors.Is(err, git.ErrNotAGitRepository), errors.Is(err, cmdutils.ErrNoGitRemotes):
182 return f.BaseRepo()
183 default:
184 return nil, err
185 }
186 }
187 },
188 Annotations: map[string]string{
189 mcpannotations.Destructive: "true",
190 },
191 RunE: func(cmd *cobra.Command, args []string) error {
192 if err := cmdutils.ResolveDescriptionFile(opts.io, cmd); err != nil {
193 return err
194 }
196 opts.complete(cmd)
198 if err := opts.validate(cmd); err != nil {
199 return err
200 }
201 if err := opts.run(cmd.Context()); err != nil {
202 // always save options to file
203 recoverErr := createRecoverSaveFile(opts)
204 if recoverErr != nil {
205 opts.io.LogErrorf("Could not create recovery file: %v", recoverErr)
206 }
208 return err
209 }
211 return nil
212 },
213 }
214 mrCreateCmd.Flags().BoolVarP(&opts.Autofill, "fill", "f", false, "Do not prompt for title or description, and just use commit info. Pushes the branch unless --push=false is set.")
215 mrCreateCmd.Flags().BoolVarP(&opts.FillCommitBody, "fill-commit-body", "", false, "Fill description with each commit body when multiple commits. Can only be used with --fill.")
216 mrCreateCmd.Flags().BoolVarP(&opts.IsDraft, "draft", "", false, "Mark merge request as a draft.")
217 mrCreateCmd.Flags().BoolVarP(&opts.IsWIP, "wip", "", false, "Mark merge request as a draft. Alternative to --draft.")
218 mrCreateCmd.Flags().BoolVarP(&opts.ShouldPush, "push", "", false, "Push committed changes before creating the merge request. Make sure you have committed changes. Defaults to true with --fill. Use --push=false to skip the push.")
219 mrCreateCmd.Flags().StringVarP(&opts.Title, "title", "t", "", "Supply a title for the merge request.")
220 mrCreateCmd.Flags().StringVarP(&opts.Description, "description", "d", "", "Supply a description for the merge request. Set to \"-\" to open an editor.")
221 mrCreateCmd.Flags().StringSliceVarP(&opts.Labels, "label", "l", []string{}, "Add label by name. Multiple labels can be comma-separated or specified by repeating the flag.")
222 mrCreateCmd.Flags().StringSliceVarP(&opts.Assignees, "assignee", "a", []string{}, "Assign merge request to people by their `usernames`. Multiple usernames can be comma-separated or specified by repeating the flag.")
223 mrCreateCmd.Flags().StringSliceVarP(&opts.Reviewers, "reviewer", "", []string{}, "Request review from users by their `usernames`. Multiple usernames can be comma-separated or specified by repeating the flag.")
224 mrCreateCmd.Flags().StringVarP(&opts.SourceBranch, "source-branch", "s", "", "Create a merge request from this branch. Default is the current branch.")
225 mrCreateCmd.Flags().StringVarP(&opts.TargetBranch, "target-branch", "b", "", "The target or base branch into which you want your code merged into.")
226 mrCreateCmd.Flags().BoolVarP(&opts.CreateSourceBranch, "create-source-branch", "", false, "Create a source branch if it does not exist.")
227 mrCreateCmd.Flags().StringVarP(&opts.MilestoneFlag, "milestone", "m", "", "The global ID or title of a milestone to assign.")
228 mrCreateCmd.Flags().Bool("allow-collaboration", false, "Allow commits from other members. Set to true/false to override project defaults, or omit to use project settings.")
229 mrCreateCmd.Flags().Bool("remove-source-branch", false, "Remove source branch on merge. Set to true/false to override project defaults, or omit to use project settings.")
230 mrCreateCmd.Flags().Bool("squash-before-merge", false, "Squash commits into a single commit when merging. Set to true/false to override project defaults, or omit to use project settings.")
231 mrCreateCmd.Flags().BoolVarP(&opts.AutoMerge, "auto-merge", "", false, "Set the merge request to merge when all merge checks pass.")
232 mrCreateCmd.Flags().BoolVarP(&opts.noEditor, "no-editor", "", false, "Don't open editor to enter a description. If true, uses prompt. Defaults to false.")
233 mrCreateCmd.Flags().StringP("head", "H", "", "Select another head repository using the `OWNER/REPO` or `GROUP/NAMESPACE/REPO` format, the project ID, or the full URL.")
234 mrCreateCmd.Flags().BoolVarP(&opts.yes, "yes", "y", false, "Skip submission confirmation prompt. Use --fill to skip all optional prompts.")
235 mrCreateCmd.Flags().BoolVarP(&opts.web, "web", "w", false, "Continue merge request creation in a browser.")
236 mrCreateCmd.Flags().BoolVarP(&opts.CopyIssueLabels, "copy-issue-labels", "", false, "Copy labels from issue to the merge request. Used with --related-issue.")
237 mrCreateCmd.Flags().StringVarP(&opts.RelatedIssue, "related-issue", "i", "", "Create a merge request for an issue. If --title is not provided, uses the issue title.")
238 mrCreateCmd.Flags().BoolVar(&opts.recover, "recover", false, "Save the options to a file if the merge request creation fails. If the file exists, the options are loaded from the recovery file. (EXPERIMENTAL)")
239 mrCreateCmd.Flags().BoolVar(&opts.signoff, "signoff", false, "Append a DCO signoff to the merge request description.")
241 mrCreateCmd.Flags().StringVarP(&opts.MRCreateTargetProject, "target-project", "", "", "Add target project by id, OWNER/REPO, or GROUP/NAMESPACE/REPO.")
242 _ = mrCreateCmd.Flags().MarkHidden("target-project")
243 _ = mrCreateCmd.Flags().MarkDeprecated("target-project", "Use --repo instead.")
245 mrCreateCmd.Flags().StringVar(&opts.Template, "template", "", "Template to pre-populate the description. A name is looked up in '.gitlab/merge_request_templates/' of the local repository, and the '.md' extension is optional. A value that is absolute or contains a path separator is read as a file path, for example '~/templates/feature.md'.")
246 cmdutils.AddDescriptionFileFlag(mrCreateCmd, "merge request")
247 cmdutils.AddAttachFlag(mrCreateCmd, &opts.Attach, "description")
248 mrCreateCmd.MarkFlagsMutuallyExclusive("template", "description")
249 mrCreateCmd.MarkFlagsMutuallyExclusive("template", "description-file")
250 mrCreateCmd.MarkFlagsMutuallyExclusive("template", "fill")
251 mrCreateCmd.MarkFlagsMutuallyExclusive("template", "related-issue")
253 return mrCreateCmd
254}
256func (o *options) complete(cmd *cobra.Command) {
257 hasTitle := cmd.Flags().Changed("title")
258 hasDescription := cmd.Flags().Changed("description")
259 hasTemplate := cmd.Flags().Changed("template")
260 hasAttachment := len(o.Attach) > 0
262 // Interactive mode prompts when either the title or description/template is missing.
263 // Non-interactive mode only requires a title.
264 o.needsPrompt = !hasTitle || (o.io.IsInteractive() && !hasDescription && !hasTemplate && !hasAttachment)
266 // Handle boolean flags: only set if explicitly provided by user
267 // This allows users to override project defaults or use them when omitted
268 if cmd.Flags().Changed("allow-collaboration") {
269 allowCollab, _ := cmd.Flags().GetBool("allow-collaboration")
270 o.AllowCollaboration = &allowCollab
271 }
273 if cmd.Flags().Changed("remove-source-branch") {
274 removeSource, _ := cmd.Flags().GetBool("remove-source-branch")
275 o.RemoveSourceBranch = &removeSource
276 }
278 if cmd.Flags().Changed("squash-before-merge") {
279 squash, _ := cmd.Flags().GetBool("squash-before-merge")
280 o.SquashBeforeMerge = &squash
281 }
283 o.pushSet = cmd.Flags().Changed("push")
284}
286func (o *options) validate(cmd *cobra.Command) error {
287 hasTitle := cmd.Flags().Changed("title")
288 hasDescription := cmd.Flags().Changed("description")
290 if hasTitle && hasDescription && o.Autofill {
291 return &cmdutils.FlagError{
292 Err: errors.New("usage of --title and --description overrides --fill"),
293 }
294 }
295 if o.needsPrompt && !o.io.IsInteractive() && !o.Autofill {
296 return &cmdutils.FlagError{Err: errors.New("--title or --fill required for non-interactive mode")}
297 }
298 if cmd.Flags().Changed("wip") && cmd.Flags().Changed("draft") {
299 return &cmdutils.FlagError{Err: errors.New("specify --draft")}
300 }
301 if !o.Autofill && o.FillCommitBody {
302 return &cmdutils.FlagError{Err: errors.New("--fill-commit-body should be used with --fill")}
303 }
304 // Remove this once --yes does more than just skip the prompts that --web happen to skip
305 // by design
306 if o.yes && o.web {
307 return &cmdutils.FlagError{Err: errors.New("--web already skips all prompts currently skipped by --yes")}
308 }
310 if o.CopyIssueLabels && o.RelatedIssue == "" {
311 return &cmdutils.FlagError{Err: errors.New("--copy-issue-labels can only be used with --related-issue")}
312 }
314 return nil
315}
317func parseIssue(apiClientFunc func(repoHost string) (*api.Client, error), gitlabClient *gitlab.Client, opts *options) (*gitlab.Issue, error) {
318 issue, _, err := issueutils.IssueFromArg(apiClientFunc, gitlabClient, opts.baseRepo, opts.defaultHostname, opts.config(), opts.RelatedIssue)
319 if err != nil {
320 return nil, err
321 }
323 return issue, nil
324}
326func (o *options) selectTemplate(ctx context.Context, client *gitlab.Client, getBaseRepoRemote func() (*glrepo.Remote, error)) (string, error) {
327 templateNames, err := cmdutils.ListGitLabTemplates(cmdutils.MergeRequestTemplate)
328 if err != nil {
329 return "", fmt.Errorf("error getting templates: %w", err)
330 }
332 const mrWithCommitsTemplate = "Open a merge request with commit messages."
333 const mrEmptyTemplate = "Open a blank merge request."
335 templateNames = append(templateNames, mrWithCommitsTemplate)
336 templateNames = append(templateNames, mrEmptyTemplate)
338 var templateName string
339 if err := o.io.Select(ctx, &templateName, "Choose a template:", templateNames); err != nil {
340 return "", fmt.Errorf("could not prompt: %w", err)
341 }
343 var templateContents string
344 switch templateName {
345 case mrWithCommitsTemplate:
346 baseRepoRemote, err := getBaseRepoRemote()
347 if err != nil {
348 return "", err
349 }
350 o.TargetTrackingBranch = fmt.Sprintf("%s/%s", baseRepoRemote.Name, o.TargetBranch)
351 commits, err := git.Commits(o.TargetTrackingBranch, o.SourceBranch)
352 if err != nil {
353 return "", fmt.Errorf("failed to get commits: %w", err)
354 }
355 templateContents, err = mrutils.GenerateMRCommitListBody(commits, true)
356 if err != nil {
357 return "", err
358 }
359 if o.signoff {
360 u, _, err := client.Users.CurrentUser()
361 if err != nil {
362 return "", fmt.Errorf("failed to get current user for signoff: %w", err)
363 }
364 templateContents += "Signed-off-by: " + u.Name + " <" + u.Email + ">"
365 }
366 case mrEmptyTemplate:
367 if o.signoff {
368 u, _, err := client.Users.CurrentUser()
369 if err != nil {
370 return "", fmt.Errorf("failed to get current user for signoff: %w", err)
371 }
372 templateContents += "Signed-off-by: " + u.Name + " <" + u.Email + ">"
373 }
374 default:
375 templateContents, err = cmdutils.LoadGitLabTemplate(cmdutils.MergeRequestTemplate, templateName)
376 if err != nil {
377 return "", fmt.Errorf("failed to get template contents: %w", err)
378 }
379 }
381 return templateContents, nil
382}
384func (o *options) run(ctx context.Context) error {
385 c := o.io.Color()
386 mrCreateOpts := &gitlab.CreateMergeRequestOptions{}
387 glRepo, err := o.baseRepo()
388 if err != nil {
389 return err
390 }
392 if o.recover {
393 if err := recovery.FromFile(glRepo.FullName(), "mr.json", o); err != nil {
394 // if the file to recover doesn't exist, we can just ignore the error and move on
395 if !errors.Is(err, os.ErrNotExist) {
396 o.io.LogErrorf("Failed to recover from file: %v", err)
397 }
398 } else {
399 o.io.LogInfo("Recovered create options from file")
400 }
401 }
403 client, err := o.gitlabClient()
404 if err != nil {
405 return err
406 }
408 baseRepo, err := o.baseRepo()
409 if err != nil {
410 return err
411 }
413 headRepo, err := o.headRepo()
414 if err != nil {
415 return err
416 }
418 // only fetch source project if it wasn't saved for recovery
419 if o.SourceProject == nil {
420 o.SourceProject, err = api.GetProject(client, headRepo.FullName())
421 if err != nil {
422 return err
423 }
424 }
426 // only fetch target project if it wasn't saved for recovery
427 if o.TargetProject == nil {
428 // if the user set the target_project, get details of the target
429 if o.MRCreateTargetProject != "" {
430 o.TargetProject, err = api.GetProject(client, o.MRCreateTargetProject)
431 if err != nil {
432 return err
433 }
434 } else {
435 // If both the baseRepo and headRepo are the same then re-use the SourceProject
436 if baseRepo.FullName() == headRepo.FullName() {
437 o.TargetProject = o.SourceProject
438 } else {
439 // Otherwise assume the user wants to create the merge request against the
440 // baseRepo
441 o.TargetProject, err = api.GetProject(client, baseRepo.FullName())
442 if err != nil {
443 return err
444 }
445 }
446 }
447 }
449 if !o.TargetProject.MergeRequestsEnabled { //nolint:staticcheck // Unlike MergeRequestsAccessLevel, MergeRequestsEnabled reflects the current user's access, which this check needs.
450 o.io.LogErrorf("Failed to create a merge request for project %q. Please ensure:\n", o.TargetProject.PathWithNamespace)
451 o.io.LogErrorf(" - You are authenticated with the GitLab CLI.\n")
452 o.io.LogErrorf(" - Merge requests are enabled for this project.\n")
453 o.io.LogErrorf(" - Your role in this project allows you to create merge requests.\n")
454 return cmdutils.SilentError
455 }
457 // repoRemote can mutate the current repo (git.AddRemote for glab-head /
458 // glab-base) and fails outside a repo. Only invoke it at the point of use.
459 var (
460 cachedHeadRepoRemote *glrepo.Remote
461 cachedBaseRepoRemote *glrepo.Remote
462 )
463 getHeadRepoRemote := func() (*glrepo.Remote, error) {
464 if cachedHeadRepoRemote != nil {
465 return cachedHeadRepoRemote, nil
466 }
467 r, err := repoRemote(o, headRepo, o.SourceProject, "glab-head")
468 if err != nil {
469 return nil, err
470 }
471 cachedHeadRepoRemote = r
472 return r, nil
473 }
474 getBaseRepoRemote := func() (*glrepo.Remote, error) {
475 if cachedBaseRepoRemote != nil {
476 return cachedBaseRepoRemote, nil
477 }
478 if glrepo.IsSame(baseRepo, headRepo) {
479 r, err := getHeadRepoRemote()
480 if err != nil {
481 return nil, err
482 }
483 cachedBaseRepoRemote = r
484 return r, nil
485 }
486 r, err := repoRemote(o, baseRepo, o.TargetProject, "glab-base")
487 if err != nil {
488 return nil, err
489 }
490 cachedBaseRepoRemote = r
491 return r, nil
492 }
494 if o.MilestoneFlag != "" {
495 o.Milestone, err = cmdutils.ParseMilestone(client, baseRepo, o.MilestoneFlag)
496 if err != nil {
497 return err
498 }
499 }
501 if o.CreateSourceBranch && o.SourceBranch == "" {
502 o.SourceBranch = utils.ReplaceNonAlphaNumericChars(o.Title, "-")
503 } else if o.SourceBranch == "" && o.RelatedIssue == "" {
504 o.SourceBranch, err = o.branch()
505 if err != nil {
506 return err
507 }
508 }
510 if o.TargetBranch == "" {
511 var err error
512 o.TargetBranch, err = getTargetBranch(client, o.TargetProject, o.SourceBranch)
513 if err != nil {
514 o.io.LogErrorf("warning: failed to fetch target branch rules: %v\n", err)
515 }
516 }
518 if o.RelatedIssue != "" {
519 issue, err := parseIssue(o.apiClient, client, o)
520 if err != nil {
521 return err
522 }
524 if o.CopyIssueLabels {
525 mrCreateOpts.Labels = (*gitlab.LabelOptions)(&issue.Labels)
526 }
528 o.Description += fmt.Sprintf("\n\nCloses #%d", issue.IID)
530 if o.Title == "" {
531 o.Title = fmt.Sprintf("Resolve %q", issue.Title)
532 }
534 // MRs created with a related issue will always be created as a draft, same as the UI
535 if !o.IsDraft && !o.IsWIP {
536 o.IsDraft = true
537 }
539 if o.SourceBranch == "" {
540 issueBranch := fmt.Sprintf("%d-%s", issue.IID, utils.ReplaceNonAlphaNumericChars(strings.ToLower(issue.Title), "-"))
541 o.SourceBranch, err = mrutils.CreateUniqueBranch(ctx, client, baseRepo.FullName(), issueBranch, o.TargetBranch)
542 if err != nil {
543 return err
544 }
545 }
546 } else {
547 if o.SourceBranch == o.TargetBranch && glrepo.IsSame(baseRepo, headRepo) {
548 o.io.LogErrorf("You must be on a different branch other than %q\n", o.TargetBranch)
549 return cmdutils.SilentError
550 }
552 // Handle -d- flag: show template selection first, then open editor
553 err = cmdutils.HandleDescriptionEditor(ctx, &o.Description, o.io, o.config, func(ctx context.Context) (string, error) {
554 return o.selectTemplate(ctx, client, getBaseRepoRemote)
555 })
556 if err != nil {
557 return err
558 }
560 if o.Template != "" && o.Description == "" {
561 content, err := cmdutils.LoadGitLabTemplate(cmdutils.MergeRequestTemplate, o.Template)
562 if err != nil {
563 return err
564 }
565 if content == "" {
566 return fmt.Errorf("template %q not found in .gitlab/merge_request_templates/", o.Template)
567 }
568 o.Description = content
569 }
571 if o.Autofill {
572 baseRepoRemote, err := getBaseRepoRemote()
573 if err != nil {
574 return err
575 }
576 o.TargetTrackingBranch = fmt.Sprintf("%s/%s", baseRepoRemote.Name, o.TargetBranch)
577 if err := mrBodyAndTitle(o); err != nil {
578 return err
579 }
580 _, _, err = client.Commits.GetCommit(baseRepo.FullName(), o.TargetBranch, nil)
581 if err != nil {
582 return fmt.Errorf("target branch %s does not exist on remote. Specify target branch with the --target-branch flag",
583 o.TargetBranch)
584 }
586 if !o.pushSet {
587 o.ShouldPush = true
588 }
589 } else if o.needsPrompt {
590 var templateContents string
591 if o.Description == "" {
592 if o.noEditor {
593 err = o.io.Multiline(ctx, &o.Description, "Description:", "")
594 if err != nil {
595 return err
596 }
597 } else {
598 templateContents, err = o.selectTemplate(ctx, client, getBaseRepoRemote)
599 if err != nil {
600 return err
601 }
602 }
603 }
605 // Combine Title + Description into a single form
606 var fields []huh.Field
607 needsTitle := o.Title == ""
608 needsDescription := o.Description == ""
610 if needsTitle {
611 fields = append(fields, huh.NewInput().
612 Title("Title").
613 Value(&o.Title).
614 Validate(func(s string) error {
615 if s == "" {
616 return fmt.Errorf("title is required")
617 }
618 return nil
619 }))
620 }
622 if needsDescription {
623 if o.noEditor {
624 fields = append(fields, huh.NewText().
625 Title("Description").
626 Value(&o.Description))
627 } else {
628 editor, err := cmdutils.GetEditor(o.config)
629 if err != nil {
630 return err
631 }
633 if templateContents != "" {
634 o.Description = templateContents
635 }
637 textField := huh.NewText().
638 Title("Description").
639 Value(&o.Description).
640 ExternalEditor(true).
641 EditorExtension(".md")
643 if editor != "" {
644 // Parse editor command to handle arguments properly
645 // huh.Editor() accepts variadic args: Editor(cmd, arg1, arg2, ...)
646 editorParts := utils.ParseEditorCommand(editor)
647 if len(editorParts) > 0 {
648 textField = textField.Editor(editorParts...)
649 }
650 }
652 fields = append(fields, textField)
653 }
654 }
656 // Run the combined form
657 if len(fields) > 0 {
658 err = o.io.RunForm(ctx, fields...)
659 if err != nil {
660 return err
661 }
662 }
663 }
664 }
666 if o.Title == "" {
667 return fmt.Errorf("title can't be blank")
668 }
670 if o.IsDraft {
671 o.Title, _ = cmdutils.EnsureTitlePrefix(o.Title, "Draft:")
672 } else if o.IsWIP {
673 o.Title, _ = cmdutils.EnsureTitlePrefix(o.Title, "WIP:")
674 }
675 mrCreateOpts.Title = &o.Title
676 mrCreateOpts.Description = &o.Description
677 mrCreateOpts.SourceBranch = &o.SourceBranch
678 mrCreateOpts.TargetBranch = &o.TargetBranch
680 // Assign boolean flags directly. If nil, GitLab uses the project's default settings.
681 // If set to true or false, the user's choice overrides project defaults.
682 mrCreateOpts.AllowCollaboration = o.AllowCollaboration
683 mrCreateOpts.RemoveSourceBranch = o.RemoveSourceBranch
684 mrCreateOpts.Squash = o.SquashBeforeMerge
686 if o.TargetProject != nil {
687 mrCreateOpts.TargetProjectID = &o.TargetProject.ID
688 }
690 if o.CreateSourceBranch {
691 lb := &gitlab.CreateBranchOptions{
692 Branch: &o.SourceBranch,
693 Ref: &o.TargetBranch,
694 }
695 o.io.LogError("\nCreating related branch...")
696 branch, _, err := client.Branches.CreateBranch(headRepo.FullName(), lb)
697 if err == nil {
698 o.io.LogError("Branch created: ", branch.WebURL)
699 } else {
700 o.io.LogError("Error creating branch: ", err.Error())
701 }
702 }
704 var action cmdutils.Action
706 // submit without prompting for non interactive mode
707 if !o.needsPrompt || o.yes {
708 action = cmdutils.SubmitAction
709 }
711 if o.web {
712 action = cmdutils.PreviewAction
713 }
715 if action == cmdutils.NoAction {
716 action, err = cmdutils.ConfirmSubmission(ctx, o.io, true)
717 if err != nil {
718 return fmt.Errorf("unable to confirm: %w", err)
719 }
720 }
722 if action == cmdutils.AddMetadataAction {
723 metadataOptions := []string{
724 "labels",
725 "assignees",
726 "milestones",
727 "reviewers",
728 }
729 var metadataActions []string
731 err := o.io.MultiSelect(ctx, &metadataActions, "Which metadata types to add?", metadataOptions)
732 if err != nil {
733 return fmt.Errorf("failed to pick the metadata to add: %w", err)
734 }
736 if len(metadataActions) > 0 {
737 baseRepoRemote, err := getBaseRepoRemote()
738 if err != nil {
739 return err
740 }
742 for _, x := range metadataActions {
743 if x == "labels" {
744 err = cmdutils.LabelsPrompt(ctx, o.io, &o.Labels, client, baseRepoRemote)
745 if err != nil {
746 return err
747 }
748 }
749 if x == "assignees" {
750 // Use minimum permission level 30 (Maintainer) as it is the minimum level
751 // to accept a merge request
752 err = cmdutils.UsersPrompt(ctx, &o.Assignees, client, baseRepoRemote, o.io, 30, x)
753 if err != nil {
754 return err
755 }
756 }
757 if x == "milestones" {
758 err = cmdutils.MilestonesPrompt(ctx, &o.Milestone, client, baseRepoRemote, o.io)
759 if err != nil {
760 return err
761 }
762 }
763 if x == "reviewers" {
764 // Use minimum permission level 30 (Maintainer) as it is the minimum level
765 // to accept a merge request
766 err = cmdutils.UsersPrompt(ctx, &o.Reviewers, client, baseRepoRemote, o.io, 30, x)
767 if err != nil {
768 return err
769 }
770 }
771 }
772 }
774 // Ask the user again but don't permit AddMetadata a second time
775 action, err = cmdutils.ConfirmSubmission(ctx, o.io, false)
776 if err != nil {
777 return err
778 }
779 }
781 // This check protects against possibly dereferencing a nil pointer.
782 if mrCreateOpts.Labels == nil {
783 mrCreateOpts.Labels = &gitlab.LabelOptions{}
784 }
785 // These actions need to be done here, after the `Add metadata` prompt because
786 // they are metadata that can be modified by the prompt
787 *mrCreateOpts.Labels = append(*mrCreateOpts.Labels, o.Labels...)
789 if len(o.Assignees) > 0 {
790 users, err := api.UsersByNames(client, o.Assignees)
791 if err != nil {
792 return err
793 }
794 mrCreateOpts.AssigneeIDs = cmdutils.IDsFromUsers(users)
795 }
797 if len(o.Reviewers) > 0 {
798 users, err := api.UsersByNames(client, o.Reviewers)
799 if err != nil {
800 return err
801 }
802 mrCreateOpts.ReviewerIDs = cmdutils.IDsFromUsers(users)
803 }
805 if o.Milestone != 0 {
806 mrCreateOpts.MilestoneID = new(o.Milestone)
807 }
809 if action == cmdutils.CancelAction {
810 o.io.LogError("Discarded.")
811 return nil
812 }
814 if o.ShouldPush {
815 headRepoRemote, err := getHeadRepoRemote()
816 if err != nil {
817 return err
818 }
819 if err := handlePush(o, headRepoRemote); err != nil {
820 return err
821 }
822 }
824 // After the cancel check so a discarded merge request uploads nothing, before
825 // the preview branch so --web carries the references too. Uploads target the
826 // project that renders the description, not the head repo it is created against.
827 o.body, err = cmdutils.AppendAttachments(ctx, o.io, client, o.TargetProject.PathWithNamespace, o.Description, o.Attach)
828 if err != nil {
829 return err
830 }
832 if action == cmdutils.PreviewAction {
833 return previewMR(o)
834 }
836 if action == cmdutils.SubmitAction {
837 mrCreateOpts.Description = &o.body
839 message := "\nCreating merge request for %s into %s in %s\n\n"
840 if o.IsDraft || o.IsWIP {
841 message = "\nCreating draft merge request for %s into %s in %s\n\n"
842 }
844 o.io.LogErrorf(message, c.Cyan(o.SourceBranch), c.Cyan(o.TargetBranch), baseRepo.FullName())
846 // It is intentional that we create against the head repo, it is necessary
847 // for cross-repository merge requests
848 mr, _, err := client.MergeRequests.CreateMergeRequest(headRepo.FullName(), mrCreateOpts)
849 if err != nil {
850 return err
851 }
853 // Enable auto-merge if requested
854 if o.AutoMerge {
855 mergeOpts := &gitlab.AcceptMergeRequestOptions{
856 AutoMerge: new(true),
857 SHA: new(mr.SHA),
858 }
860 _, _, err = client.MergeRequests.AcceptMergeRequest(headRepo.FullName(), mr.IID, mergeOpts)
861 if err != nil {
862 o.io.LogInfo(mrutils.DisplayMR(c, &mr.BasicMergeRequest, o.io.IsaTTY))
863 return fmt.Errorf("merge request created but auto-merge could not be enabled: %w", err)
864 }
866 o.io.LogInfo(mrutils.DisplayMR(c, &mr.BasicMergeRequest, o.io.IsaTTY))
867 o.io.LogInfof("%s Auto-merge enabled. Will merge when all checks pass.\n", c.GreenCheck())
868 return nil
869 }
871 o.io.LogInfo(mrutils.DisplayMR(c, &mr.BasicMergeRequest, o.io.IsaTTY))
872 return nil
873 }
875 return errors.New("expected to cancel, preview in browser, or submit")
876}
878func mrBodyAndTitle(opts *options) error {
879 // TODO: detect forks
880 commits, err := git.Commits(opts.TargetTrackingBranch, opts.SourceBranch)
881 if err != nil {
882 return err
883 }
884 if len(commits) == 1 {
885 if opts.Title == "" {
886 opts.Title = commits[0].Title
887 }
888 if opts.Description == "" {
889 body, err := git.CommitBody(commits[0].Sha)
890 if err != nil {
891 return err
892 }
893 opts.Description = body
894 }
895 } else {
896 if opts.Title == "" {
897 opts.Title = utils.Humanize(opts.SourceBranch)
898 }
900 if opts.Description == "" {
901 description, err := mrutils.GenerateMRCommitListBody(commits, opts.FillCommitBody)
902 if err != nil {
903 return err
904 }
905 opts.Description = description
906 }
907 }
908 return nil
909}
911func handlePush(opts *options, remote *glrepo.Remote) error {
912 if opts.ShouldPush {
913 sourceRemote := remote
915 sourceBranch := opts.SourceBranch
917 if sourceBranch != "" {
918 if idx := strings.IndexRune(sourceBranch, ':'); idx >= 0 {
919 sourceBranch = sourceBranch[idx+1:]
920 }
921 }
923 if c, err := git.UncommittedChangeCount(); c != 0 {
924 if err != nil {
925 return err
926 }
927 opts.io.LogErrorf("\nwarning: you have %s\n", utils.Pluralize(c, "uncommitted change"))
928 }
929 err := git.Push(sourceRemote.Name, fmt.Sprintf("HEAD:%s", sourceBranch), opts.io.StdOut, opts.io.StdErr)
930 if err == nil {
931 branchConfig := git.ReadBranchConfig(sourceBranch)
932 if branchConfig.RemoteName == "" && (branchConfig.MergeRef == "" || branchConfig.RemoteURL == nil) {
933 // No remote is set so set it
934 _ = git.SetUpstream(sourceRemote.Name, sourceBranch, opts.io.StdOut, opts.io.StdErr)
935 }
936 }
937 return err
938 }
940 return nil
941}
943func previewMR(opts *options) error {
944 repo, err := opts.baseRepo()
945 if err != nil {
946 return err
947 }
949 cfg := opts.config()
951 openURL, err := generateMRCompareURL(opts)
952 if err != nil {
953 return err
954 }
956 if opts.io.IsOutputTTY() {
957 opts.io.LogErrorf("Opening %s in your browser.\n", utils.DisplayURL(openURL))
958 }
959 browser, _ := cfg.Get(repo.RepoHost(), "browser")
960 return utils.OpenInBrowser(openURL, browser)
961}
963func generateMRCompareURL(opts *options) (string, error) {
964 description := opts.body
966 if len(opts.Labels) > 0 {
967 // this uses the slash commands to add labels to the description
968 // See https://docs.gitlab.com/user/project/quick_actions/
969 // See also https://gitlab.com/gitlab-org/gitlab-foss/-/issues/19731#note_32550046
970 description += fmt.Sprintf("\n/label ~%s", strings.Join(opts.Labels, ", ~"))
971 }
972 if len(opts.Assignees) > 0 {
973 // this uses the slash commands to add assignees to the description
974 description += fmt.Sprintf("\n/assign %s", strings.Join(opts.Assignees, ", "))
975 }
976 if len(opts.Reviewers) > 0 {
977 // this uses the slash commands to add reviewers to the description
978 description += fmt.Sprintf("\n/reviewer %s", strings.Join(opts.Reviewers, ", "))
979 }
980 if opts.Milestone != 0 {
981 // this uses the slash commands to add milestone to the description
982 description += fmt.Sprintf("\n/milestone %%%d", opts.Milestone)
983 }
985 // The merge request **must** be opened against the head repo
986 u, err := url.Parse(opts.SourceProject.WebURL)
987 if err != nil {
988 return "", err
989 }
991 u.Path += "/-/merge_requests/new"
992 q := u.Query()
993 q.Set("merge_request[title]", opts.Title)
994 q.Add("merge_request[description]", description)
995 q.Add("merge_request[source_branch]", opts.SourceBranch)
996 q.Add("merge_request[target_branch]", opts.TargetBranch)
997 q.Add("merge_request[source_project_id]", strconv.FormatInt(opts.SourceProject.ID, 10))
998 q.Add("merge_request[target_project_id]", strconv.FormatInt(opts.TargetProject.ID, 10))
999 u.RawQuery = q.Encode()
1001 return u.String(), nil
1002}
1004func ResolvedHeadRepo(ctx context.Context, f cmdutils.Factory) func() (glrepo.Interface, error) {
1005 return func() (glrepo.Interface, error) {
1006 client, err := f.GitLabClient()
1007 if err != nil {
1008 return nil, err
1009 }
1010 remotes, err := f.Remotes()
1011 if err != nil {
1012 return nil, err
1013 }
1014 repoContext, err := glrepo.ResolveRemotesToRepos(remotes, client, f.DefaultHostname(), f.Config())
1015 if err != nil {
1016 return nil, err
1017 }
1018 headRepo, err := repoContext.HeadRepo(ctx, f.IO())
1019 if err != nil {
1020 return nil, err
1021 }
1023 return headRepo, nil
1024 }
1025}
1027func headRepoOverride(opts *options, repo string) {
1028 opts.headRepo = func() (glrepo.Interface, error) {
1029 return glrepo.FromFullName(repo, opts.defaultHostname, opts.config())
1030 }
1031}
1033func repoRemote(opts *options, repo glrepo.Interface, project *gitlab.Project, remoteName string) (*glrepo.Remote, error) {
1034 remotes, err := opts.remotes()
1035 if err != nil {
1036 return nil, err
1037 }
1038 repoRemote, _ := remotes.FindByRepo(repo.RepoOwner(), repo.RepoName())
1039 if repoRemote == nil {
1040 cfg := opts.config()
1041 gitProtocol, _ := cfg.Get(repo.RepoHost(), "git_protocol")
1042 repoURL, err := glrepo.RemoteURL(project, gitProtocol)
1043 if err != nil {
1044 return nil, err
1045 }
1047 gitRemote, err := git.AddRemote(remoteName, repoURL)
1048 if err != nil {
1049 return nil, fmt.Errorf("error adding remote: %w", err)
1050 }
1051 repoRemote = &glrepo.Remote{
1052 Remote: gitRemote,
1053 Repo: repo,
1054 }
1055 }
1057 return repoRemote, nil
1058}
1060func getTargetBranch(client *gitlab.Client, targetProject *gitlab.Project, sourceBranch string) (string, error) {
1061 if sourceBranch != "" {
1062 rules, _, err := client.Projects.ListProjectTargetBranchRules(targetProject.PathWithNamespace)
1063 if err != nil {
1064 return targetProject.DefaultBranch, err
1065 }
1066 for _, rule := range rules {
1067 if matched, _ := matchBranchPattern(rule.Name, sourceBranch); matched {
1068 return rule.TargetBranch, nil
1069 }
1070 }
1071 }
1072 return targetProject.DefaultBranch, nil
1073}
1075// matchBranchPattern reports whether branch matches a GitLab branch name
1076// pattern. GitLab patterns are glob-style where '*' matches any sequence of
1077// characters, including '/'.
1078func matchBranchPattern(pattern, branch string) (bool, error) {
1079 re, err := regexp.Compile("^" + strings.ReplaceAll(regexp.QuoteMeta(pattern), `\*`, `.*`) + "$")
1080 if err != nil {
1081 return false, err
1082 }
1083 return re.MatchString(branch), nil
1084}
1086// createRecoverSaveFile will try save the issue create options to a file
1087func createRecoverSaveFile(opts *options) error {
1088 glRepo, err := opts.baseRepo()
1089 if err != nil {
1090 return err
1091 }
1093 recoverFile, err := recovery.CreateFile(glRepo.FullName(), "mr.json", opts)
1094 if err != nil {
1095 return err
1096 }
1098 opts.io.LogErrorf("Failed to create merge request. Created recovery file: %s\nRun the command again with the '--recover' option to retry.\n", recoverFile)
1099 return nil
1100}
Diagnostics9 git calls · 353 ms
CallStatusSizeTime0353 ms
discover200185 B91 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 KiB93 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
fetchtree:0 · deepen 1020032 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=32926 git.response.cache=HIT git.response.duration_ms=2 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.1 KiB · hit16 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=16 git.response.bytes=1112 git.response.cache=HIT git.response.duration_ms=16 git.fetch.filter=tree:0 git.fetch.wants=fed5065f0120a857fec6fa567dcdacfd34c3187b 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=1112 git.pkt.payload.max=1085 git.sideband.band1.bytes=1085 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1085 git.pack.trailer=792a8e6885c3db50fcc6be7a28de09363c6fb5e4Open pack map
fetchtree:0200890 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=890 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=11daffb8433226c87be08ba8cfc35154e4957d77 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=890 git.pkt.payload.max=863 git.sideband.band1.bytes=863 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=863 git.pack.trailer=b909e7b7573f11b0bb74a32781c8c5e4e19277f4Open pack map
fetchtree:02001.8 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=1857 git.response.cache=HIT git.response.duration_ms=4 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 · 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=746 git.response.cache=HIT git.response.duration_ms=2 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:0200202 B · hit7 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=7 git.response.bytes=202 git.response.cache=HIT git.response.duration_ms=7 git.fetch.filter=tree:0 git.fetch.wants=02d69f71dcced584f60d05385e3a545c407a76f4 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=202 git.pkt.payload.max=175 git.sideband.band1.bytes=175 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=175 git.pack.trailer=55b73a97e35a386cfe7e8d263dc4f59f2b43b52aOpen pack map
fetch20010 KiB226 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=226 git.response.bytes=10598 git.response.cache=MISS git.response.duration_ms=226 git.fetch.wants=76e82c1615193a3933efcbf9bf1626d2bdc6e459 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=10598 git.pkt.payload.max=10571 git.sideband.band1.bytes=10571 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
- a5e2be84ce5489da
- Request
- e1f8a0a2…
- 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