GitLabgitlab-org
cli
main
1//go:build !integration
3package create
5import (
6 "context"
7 "errors"
8 "fmt"
9 "io/fs"
10 "net/http"
11 "net/url"
12 "os"
13 "path/filepath"
14 "slices"
15 "strings"
16 "testing"
18 "git.sr.ht/~timofurrer/ugh"
19 "github.com/MakeNowJust/heredoc/v2"
20 "github.com/spf13/cobra"
21 "github.com/stretchr/testify/assert"
22 "github.com/stretchr/testify/require"
23 "go.uber.org/mock/gomock"
25 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
26 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
28 "gitlab.com/gitlab-org/cli/internal/cmdutils"
29 "gitlab.com/gitlab-org/cli/internal/config"
30 "gitlab.com/gitlab-org/cli/internal/git"
31 "gitlab.com/gitlab-org/cli/internal/glinstance"
32 "gitlab.com/gitlab-org/cli/internal/glrepo"
33 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
34 "gitlab.com/gitlab-org/cli/test"
35)
37func TestNewCmdCreate_tty(t *testing.T) {
38 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
39 t.Setenv("NO_COLOR", "true")
41 testClient := gitlabtesting.NewTestClient(t)
43 // Mock GetProject
44 testClient.MockProjects.EXPECT().
45 GetProject("OWNER/REPO", gomock.Any()).
46 Return(&gitlab.Project{
47 ID: 1,
48 DefaultBranch: "master",
49 WebURL: "http://gitlab.com/OWNER/REPO",
50 Name: "OWNER",
51 Path: "REPO",
52 MergeRequestsEnabled: true,
53 PathWithNamespace: "OWNER/REPO",
54 }, nil, nil)
56 // Mock ListMilestones
57 testClient.MockMilestones.EXPECT().
58 ListMilestones("OWNER/REPO", gomock.Any()).
59 Return([]*gitlab.Milestone{
60 {
61 ID: 1,
62 IID: 3,
63 Description: "foo",
64 },
65 }, nil, nil)
67 // Mock ListProjectTargetBranchRules (no rules configured)
68 testClient.MockProjects.EXPECT().
69 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
70 Return([]gitlab.TargetBranchRule{}, nil, nil)
72 // Mock ListUsers
73 testClient.MockUsers.EXPECT().
74 ListUsers(gomock.Any()).
75 Return([]*gitlab.User{
76 {
77 Username: "testuser",
78 },
79 }, nil, nil)
81 // Mock CreateMergeRequest
82 testClient.MockMergeRequests.EXPECT().
83 CreateMergeRequest("OWNER/REPO", gomock.Any()).
84 Return(&gitlab.MergeRequest{
85 BasicMergeRequest: gitlab.BasicMergeRequest{
86 ID: 1,
87 IID: 12,
88 ProjectID: 3,
89 Title: "myMRtitle",
90 Description: "myMRbody",
91 State: "opened",
92 TargetBranch: "master",
93 SourceBranch: "feat-new-mr",
94 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
95 },
96 }, nil, nil)
98 cs, csTeardown := test.InitCmdStubber()
99 defer csTeardown()
100 cs.Stub("HEAD branch: master\n")
101 cs.Stub(heredoc.Doc(`
102 deadbeef HEAD
103 deadb00f refs/remotes/upstream/feat-new-mr
104 deadbeef refs/remotes/origin/feat-new-mr
105 `))
107 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
109 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
110 cmdtest.WithGitLabClient(testClient.Client),
111 func(f *cmdtest.Factory) {
112 f.RemotesStub = func() (glrepo.Remotes, error) {
113 return glrepo.Remotes{
114 {
115 Remote: &git.Remote{
116 Name: "upstream",
117 Resolved: "head",
118 PushURL: pu,
119 },
120 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
121 },
122 {
123 Remote: &git.Remote{
124 Name: "origin",
125 Resolved: "base",
126 PushURL: pu,
127 },
128 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
129 },
130 }, nil
131 }
132 f.BranchStub = func() (string, error) {
133 return "feat-new-mr", nil
134 }
135 },
136 )
138 cliStr := []string{
139 "-t", "myMRtitle",
140 "-d", "myMRbody",
141 "-l", "test,bug",
142 "--milestone", "foo",
143 "--assignee", "testuser",
144 }
146 cli := strings.Join(cliStr, " ")
148 output, err := exec(cli)
149 if err != nil {
150 if errors.Is(err, cmdutils.SilentError) {
151 t.Errorf("Unexpected error: %q", output.Stderr())
152 }
153 t.Error(err)
154 return
155 }
157 outputLines := strings.SplitN(output.String(), "\n", 2)
158 assert.Contains(t, outputLines[0], "!12 myMRtitle (feat-new-mr)")
159 assert.Contains(t, output.Stderr(), "\nCreating merge request for feat-new-mr into master in OWNER/REPO\n\n")
160 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/merge_requests/12")
161}
163func TestNewCmdCreate_RelatedIssue(t *testing.T) {
164 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
165 t.Setenv("NO_COLOR", "true")
167 testClient := gitlabtesting.NewTestClient(t)
169 // Mock GetProject
170 testClient.MockProjects.EXPECT().
171 GetProject("OWNER/REPO", gomock.Any()).
172 Return(&gitlab.Project{
173 ID: 1,
174 DefaultBranch: "master",
175 WebURL: "http://gitlab.com/OWNER/REPO",
176 Name: "OWNER",
177 Path: "REPO",
178 MergeRequestsEnabled: true,
179 PathWithNamespace: "OWNER/REPO",
180 }, nil, nil)
182 // Mock ListProjectTargetBranchRules (no rules configured)
183 testClient.MockProjects.EXPECT().
184 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
185 Return([]gitlab.TargetBranchRule{}, nil, nil)
187 // Mock GetIssue
188 testClient.MockIssues.EXPECT().
189 GetIssue("OWNER/REPO", int64(1), gomock.Any()).
190 Return(&gitlab.Issue{
191 ID: 1,
192 IID: 1,
193 ProjectID: 1,
194 Title: "this is a issue title",
195 Description: "issue description",
196 }, nil, nil)
198 // Mock CreateMergeRequest and verify the title and description
199 testClient.MockMergeRequests.EXPECT().
200 CreateMergeRequest("OWNER/REPO", gomock.Any()).
201 DoAndReturn(func(pid any, opts *gitlab.CreateMergeRequestOptions, options ...gitlab.RequestOptionFunc) (*gitlab.MergeRequest, *gitlab.Response, error) {
202 assert.Contains(t, *opts.Title, `Draft: Resolve "this is a issue title"`)
203 assert.Contains(t, *opts.Description, "\n\nCloses #1")
204 return &gitlab.MergeRequest{
205 BasicMergeRequest: gitlab.BasicMergeRequest{
206 ID: 1,
207 IID: 12,
208 ProjectID: 3,
209 Title: `Draft: Resolve "this is a issue title"`,
210 Description: "\n\nCloses #1",
211 State: "opened",
212 TargetBranch: "master",
213 SourceBranch: "feat-new-mr",
214 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
215 },
216 }, nil, nil
217 })
219 cs, csTeardown := test.InitCmdStubber()
220 defer csTeardown()
221 cs.Stub("HEAD branch: master\n")
222 cs.Stub(heredoc.Doc(`
223 deadbeef HEAD
224 deadb00f refs/remotes/upstream/feat-new-mr
225 deadbeef refs/remotes/origin/feat-new-mr
226 `))
228 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
230 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
231 cmdtest.WithGitLabClient(testClient.Client),
232 func(f *cmdtest.Factory) {
233 f.RemotesStub = func() (glrepo.Remotes, error) {
234 return glrepo.Remotes{
235 {
236 Remote: &git.Remote{
237 Name: "upstream",
238 Resolved: "head",
239 PushURL: pu,
240 },
241 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
242 },
243 {
244 Remote: &git.Remote{
245 Name: "origin",
246 Resolved: "base",
247 PushURL: pu,
248 },
249 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
250 },
251 }, nil
252 }
253 f.BranchStub = func() (string, error) {
254 return "feat-new-mr", nil
255 }
256 },
257 )
259 cliStr := []string{
260 "--related-issue", "1",
261 "--source-branch", "feat-new-mr",
262 "--yes",
263 }
265 cli := strings.Join(cliStr, " ")
267 t.Log(cli)
269 output, err := exec(cli)
270 if err != nil {
271 if errors.Is(err, cmdutils.SilentError) {
272 t.Errorf("Unexpected error: %q", output.Stderr())
273 }
274 t.Error(err)
275 return
276 }
277 outputLines := strings.SplitN(output.String(), "\n", 2)
278 assert.Contains(t, outputLines[0], `!12 Draft: Resolve "this is a issue title" (feat-new-mr)`)
279 assert.Contains(t, output.Stderr(), "\nCreating draft merge request for feat-new-mr into master in OWNER/REPO\n\n")
280 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/merge_requests/12")
281}
283func TestNewCmdCreate_RelatedIssueBranchCreation(t *testing.T) {
284 branchExists := &gitlab.ErrorResponse{StatusCode: http.StatusBadRequest, Message: "{message: Branch already exists}"}
286 tests := []struct {
287 name string
288 branchErrors []error
289 wantBranches []string
290 wantMRBranch string
291 wantErr string
292 }{
293 {
294 name: "returns an error that is not about an existing branch",
295 branchErrors: []error{&gitlab.ErrorResponse{StatusCode: http.StatusForbidden, Message: "{message: 403 Forbidden}"}},
296 wantBranches: []string{"1-fix-crash-in-config-"},
297 wantErr: `could not create branch "1-fix-crash-in-config-": 403 {message: 403 Forbidden}`,
298 },
299 {
300 name: "uses a sanitized numbered branch when the branch exists",
301 branchErrors: []error{branchExists, nil},
302 wantBranches: []string{"1-fix-crash-in-config-", "1-fix-crash-in-config--1"},
303 wantMRBranch: "1-fix-crash-in-config--1",
304 },
305 }
307 for _, tt := range tests {
308 t.Run(tt.name, func(t *testing.T) {
309 testClient := gitlabtesting.NewTestClient(t)
310 testClient.MockProjects.EXPECT().
311 GetProject("OWNER/REPO", gomock.Any()).
312 Return(&gitlab.Project{
313 ID: 1,
314 DefaultBranch: "master",
315 WebURL: "http://gitlab.com/OWNER/REPO",
316 Name: "OWNER",
317 Path: "REPO",
318 MergeRequestsEnabled: true,
319 PathWithNamespace: "OWNER/REPO",
320 }, nil, nil)
321 testClient.MockProjects.EXPECT().
322 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
323 Return([]gitlab.TargetBranchRule{}, nil, nil).
324 AnyTimes()
325 testClient.MockIssues.EXPECT().
326 GetIssue("OWNER/REPO", int64(1), gomock.Any()).
327 Return(&gitlab.Issue{ID: 1, IID: 1, ProjectID: 1, Title: "Fix: crash in ~/.config?"}, nil, nil)
329 var branches []string
330 testClient.MockBranches.EXPECT().
331 CreateBranch("OWNER/REPO", gomock.Any(), gomock.Any()).
332 DoAndReturn(func(_ any, opts *gitlab.CreateBranchOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.Branch, *gitlab.Response, error) {
333 branches = append(branches, *opts.Branch)
334 if err := tt.branchErrors[len(branches)-1]; err != nil {
335 return nil, nil, err
336 }
337 return &gitlab.Branch{Name: *opts.Branch}, nil, nil
338 }).
339 Times(len(tt.branchErrors))
340 if tt.wantMRBranch != "" {
341 testClient.MockMergeRequests.EXPECT().
342 CreateMergeRequest("OWNER/REPO", gomock.Any()).
343 DoAndReturn(func(_ any, opts *gitlab.CreateMergeRequestOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.MergeRequest, *gitlab.Response, error) {
344 assert.Equal(t, tt.wantMRBranch, *opts.SourceBranch)
345 return &gitlab.MergeRequest{
346 BasicMergeRequest: gitlab.BasicMergeRequest{
347 IID: 12,
348 Title: *opts.Title,
349 State: "opened",
350 SourceBranch: *opts.SourceBranch,
351 TargetBranch: "master",
352 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
353 },
354 }, nil, nil
355 })
356 }
358 cs, csTeardown := test.InitCmdStubber()
359 defer csTeardown()
360 cs.Stub("HEAD branch: master\n")
361 cs.Stub(heredoc.Doc(`
362 deadbeef HEAD
363 deadb00f refs/remotes/upstream/feat-new-mr
364 deadbeef refs/remotes/origin/feat-new-mr
365 `))
367 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
368 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
369 cmdtest.WithGitLabClient(testClient.Client),
370 func(f *cmdtest.Factory) {
371 f.RemotesStub = func() (glrepo.Remotes, error) {
372 return glrepo.Remotes{
373 {
374 Remote: &git.Remote{Name: "upstream", Resolved: "head", PushURL: pu},
375 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
376 },
377 {
378 Remote: &git.Remote{Name: "origin", Resolved: "base", PushURL: pu},
379 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
380 },
381 }, nil
382 }
383 f.BranchStub = func() (string, error) {
384 return "feat-new-mr", nil
385 }
386 },
387 )
389 _, err := exec("--related-issue 1 --target-branch master --yes")
391 assert.Equal(t, tt.wantBranches, branches)
392 if tt.wantErr != "" {
393 require.EqualError(t, err, tt.wantErr)
394 return
395 }
396 require.NoError(t, err)
397 })
398 }
399}
401func TestNewCmdCreate_TemplateFromCommitMessages(t *testing.T) {
402 testClient := gitlabtesting.NewTestClient(t)
404 // Mock GetProject
405 testClient.MockProjects.EXPECT().
406 GetProject("OWNER/REPO", gomock.Any()).
407 Return(&gitlab.Project{
408 ID: 1,
409 DefaultBranch: "master",
410 WebURL: "http://gitlab.com/OWNER/REPO",
411 Name: "OWNER",
412 Path: "REPO",
413 MergeRequestsEnabled: true,
414 PathWithNamespace: "OWNER/REPO",
415 }, nil, nil)
417 // Mock ListProjectTargetBranchRules (no rules configured)
418 testClient.MockProjects.EXPECT().
419 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
420 Return([]gitlab.TargetBranchRule{}, nil, nil)
422 // Mock CreateMergeRequest and verify the description contains commit messages
423 testClient.MockMergeRequests.EXPECT().
424 CreateMergeRequest("OWNER/REPO", gomock.Any()).
425 DoAndReturn(func(pid any, opts *gitlab.CreateMergeRequestOptions, options ...gitlab.RequestOptionFunc) (*gitlab.MergeRequest, *gitlab.Response, error) {
426 assert.Contains(t, *opts.Description, "- commit msg 1 \n\n")
427 assert.Contains(t, *opts.Description, "- commit msg 2 \ncommit body")
428 return &gitlab.MergeRequest{
429 BasicMergeRequest: gitlab.BasicMergeRequest{
430 ID: 1,
431 IID: 12,
432 ProjectID: 3,
433 Title: "...",
434 Description: "...",
435 State: "opened",
436 TargetBranch: "master",
437 SourceBranch: "feat-new-mr",
438 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
439 },
440 }, nil, nil
441 })
443 cs, csTeardown := test.InitCmdStubber()
444 defer csTeardown()
446 cs.Stub("/") // git rev-parse --show-toplevel
448 // git -c log.ShowSignature=false log --pretty=format:%H,%s --cherry upstream/master...feat-new-mr
449 cs.Stub(heredoc.Doc(`
450 deadb00f,commit msg 2
451 deadbeef,commit msg 1
452 `))
454 // git -c log.ShowSignature=false show -s --pretty=format:%b deadbeef
455 cs.Stub("")
456 // git -c log.ShowSignature=false show -s --pretty=format:%b deadb00f
457 cs.Stub("commit body")
459 c := ugh.New(t)
460 c.Expect(ugh.Select("Choose a template:")).
461 Do(ugh.SelectIndex(0))
462 c.Expect(ugh.Input("Description")).
463 Do(ugh.Type("- commit msg 1 \n\n- commit msg 2 \ncommit body"))
465 cliStr := []string{
466 "--source-branch", "feat-new-mr",
467 "--title", "mr-title",
468 "--yes",
469 }
471 cli := strings.Join(cliStr, " ")
473 t.Log(cli)
475 // Use SetupCmdForTest pattern for responder
476 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
478 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
479 // Set up factory with remotes stub
480 tf, ok := f.(*cmdtest.Factory)
481 require.True(t, ok, "expected cmdtest.Factory")
482 tf.RemotesStub = func() (glrepo.Remotes, error) {
483 return glrepo.Remotes{
484 {
485 Remote: &git.Remote{
486 Name: "upstream",
487 Resolved: "head",
488 PushURL: pu,
489 },
490 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
491 },
492 {
493 Remote: &git.Remote{
494 Name: "origin",
495 Resolved: "head",
496 PushURL: pu,
497 },
498 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
499 },
500 }, nil
501 }
502 tf.BranchStub = func() (string, error) {
503 return "feat-new-mr", nil
504 }
506 return NewCmdCreate(f)
507 }, true,
508 cmdtest.WithGitLabClient(testClient.Client),
509 cmdtest.WithConfig(config.NewFromString("editor: vi")),
510 cmdtest.WithConsole(t, c),
511 )
513 output, err := exec(cli)
514 if err != nil {
515 if errors.Is(err, cmdutils.SilentError) {
516 t.Errorf("Unexpected error: %q", output.Stderr())
517 }
518 t.Error(err)
519 return
520 }
521}
523func TestNewCmdCreate_RelatedIssueWithTitleAndDescription(t *testing.T) {
524 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
525 t.Setenv("NO_COLOR", "true")
527 testClient := gitlabtesting.NewTestClient(t)
529 // Mock GetProject
530 testClient.MockProjects.EXPECT().
531 GetProject("OWNER/REPO", gomock.Any()).
532 Return(&gitlab.Project{
533 ID: 1,
534 DefaultBranch: "master",
535 WebURL: "http://gitlab.com/OWNER/REPO",
536 Name: "OWNER",
537 Path: "REPO",
538 MergeRequestsEnabled: true,
539 PathWithNamespace: "OWNER/REPO",
540 }, nil, nil)
542 // Mock ListProjectTargetBranchRules (no rules configured)
543 testClient.MockProjects.EXPECT().
544 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
545 Return([]gitlab.TargetBranchRule{}, nil, nil)
547 // Mock GetIssue
548 testClient.MockIssues.EXPECT().
549 GetIssue("OWNER/REPO", int64(1), gomock.Any()).
550 Return(&gitlab.Issue{
551 ID: 1,
552 IID: 1,
553 ProjectID: 1,
554 Title: "this is a issue title",
555 Description: "issue description",
556 }, nil, nil)
558 // Mock CreateMergeRequest and verify the title and description
559 testClient.MockMergeRequests.EXPECT().
560 CreateMergeRequest("OWNER/REPO", gomock.Any()).
561 DoAndReturn(func(pid any, opts *gitlab.CreateMergeRequestOptions, options ...gitlab.RequestOptionFunc) (*gitlab.MergeRequest, *gitlab.Response, error) {
562 assert.Equal(t, "Draft: my custom MR title", *opts.Title)
563 assert.Contains(t, *opts.Description, "my custom MR description\n\nCloses #1")
564 return &gitlab.MergeRequest{
565 BasicMergeRequest: gitlab.BasicMergeRequest{
566 ID: 1,
567 IID: 12,
568 ProjectID: 3,
569 Title: "my custom MR title",
570 Description: "myMRbody",
571 State: "opened",
572 TargetBranch: "master",
573 SourceBranch: "feat-new-mr",
574 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
575 },
576 }, nil, nil
577 })
579 cs, csTeardown := test.InitCmdStubber()
580 defer csTeardown()
581 cs.Stub("HEAD branch: master\n")
582 cs.Stub(heredoc.Doc(`
583 deadbeef HEAD
584 deadb00f refs/remotes/upstream/feat-new-mr
585 deadbeef refs/remotes/origin/feat-new-mr
586 `))
588 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
590 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
591 cmdtest.WithGitLabClient(testClient.Client),
592 func(f *cmdtest.Factory) {
593 f.RemotesStub = func() (glrepo.Remotes, error) {
594 return glrepo.Remotes{
595 {
596 Remote: &git.Remote{
597 Name: "upstream",
598 Resolved: "head",
599 PushURL: pu,
600 },
601 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
602 },
603 {
604 Remote: &git.Remote{
605 Name: "origin",
606 Resolved: "base",
607 PushURL: pu,
608 },
609 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
610 },
611 }, nil
612 }
613 f.BranchStub = func() (string, error) {
614 return "feat-new-mr", nil
615 }
616 },
617 )
619 cliStr := []string{
620 "--title", `"my custom MR title"`,
621 "--description", `"my custom MR description"`,
622 "--related-issue", "1",
623 "--source-branch", "feat-new-mr",
624 }
626 cli := strings.Join(cliStr, " ")
628 t.Log(cli)
630 output, err := exec(cli)
631 if err != nil {
632 if errors.Is(err, cmdutils.SilentError) {
633 t.Errorf("Unexpected error: %q", output.Stderr())
634 }
635 t.Error(err)
636 return
637 }
639 outputLines := strings.SplitN(output.String(), "\n", 2)
640 assert.Contains(t, outputLines[0], "!12 my custom MR title (feat-new-mr)")
641 assert.Contains(t, output.Stderr(), "\nCreating draft merge request for feat-new-mr into master in OWNER/REPO\n\n")
642 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/merge_requests/12")
643}
645// withMRCreateRemotes stubs the upstream/origin remotes and current branch that
646// most mr create tests need.
647func withMRCreateRemotes(branch string) func(*cmdtest.Factory) {
648 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
649 return func(f *cmdtest.Factory) {
650 f.RemotesStub = func() (glrepo.Remotes, error) {
651 return glrepo.Remotes{
652 {
653 Remote: &git.Remote{Name: "upstream", Resolved: "head", PushURL: pu},
654 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
655 },
656 {
657 Remote: &git.Remote{Name: "origin", Resolved: "base", PushURL: pu},
658 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
659 },
660 }, nil
661 }
662 f.BranchStub = func() (string, error) { return branch, nil }
663 }
664}
666func TestNewCmdCreate_DoesNotDoublePrefixTitle(t *testing.T) {
667 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
668 t.Setenv("NO_COLOR", "true")
670 tests := []struct {
671 name string
672 title string
673 extraArgs []string
674 relatedIssue bool
675 wantTitle string
676 }{
677 {
678 name: "--draft prepends when prefix is absent",
679 title: "my custom MR title",
680 extraArgs: []string{"--draft"},
681 wantTitle: "Draft: my custom MR title",
682 },
683 {
684 name: "--draft leaves an existing Draft prefix alone",
685 title: "Draft: my custom MR title",
686 extraArgs: []string{"--draft"},
687 wantTitle: "Draft: my custom MR title",
688 },
689 {
690 name: "--draft matches the prefix case-insensitively",
691 title: "draft: my custom MR title",
692 extraArgs: []string{"--draft"},
693 wantTitle: "draft: my custom MR title",
694 },
695 {
696 name: "--draft ignores leading whitespace before the prefix",
697 title: " Draft: my custom MR title",
698 extraArgs: []string{"--draft"},
699 wantTitle: " Draft: my custom MR title",
700 },
701 {
702 name: "--draft leaves a [Draft] title alone",
703 title: "[Draft] my custom MR title",
704 extraArgs: []string{"--draft"},
705 wantTitle: "[Draft] my custom MR title",
706 },
707 {
708 name: "--draft leaves a (Draft) title alone",
709 title: "(Draft) my custom MR title",
710 extraArgs: []string{"--draft"},
711 wantTitle: "(Draft) my custom MR title",
712 },
713 {
714 name: "--wip prepends when prefix is absent",
715 title: "my custom MR title",
716 extraArgs: []string{"--wip"},
717 wantTitle: "WIP: my custom MR title",
718 },
719 {
720 name: "--wip leaves an existing WIP prefix alone",
721 title: "WIP: my custom MR title",
722 extraArgs: []string{"--wip"},
723 wantTitle: "WIP: my custom MR title",
724 },
725 {
726 name: "--related-issue implies draft and does not double-prefix",
727 title: "Draft: my custom MR title",
728 extraArgs: []string{"--related-issue", "1"},
729 relatedIssue: true,
730 wantTitle: "Draft: my custom MR title",
731 },
732 }
734 for _, tt := range tests {
735 t.Run(tt.name, func(t *testing.T) {
736 testClient := gitlabtesting.NewTestClient(t)
737 testClient.MockProjects.EXPECT().
738 GetProject("OWNER/REPO", gomock.Any()).
739 Return(&gitlab.Project{
740 ID: 1,
741 DefaultBranch: "master",
742 WebURL: "http://gitlab.com/OWNER/REPO",
743 Name: "OWNER",
744 Path: "REPO",
745 MergeRequestsEnabled: true,
746 PathWithNamespace: "OWNER/REPO",
747 }, nil, nil)
748 testClient.MockProjects.EXPECT().
749 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
750 Return([]gitlab.TargetBranchRule{}, nil, nil)
752 if tt.relatedIssue {
753 testClient.MockIssues.EXPECT().
754 GetIssue("OWNER/REPO", int64(1), gomock.Any()).
755 Return(&gitlab.Issue{ID: 1, IID: 1, ProjectID: 1, Title: "this is a issue title"}, nil, nil)
756 }
758 testClient.MockMergeRequests.EXPECT().
759 CreateMergeRequest("OWNER/REPO", gomock.Any()).
760 DoAndReturn(func(pid any, opts *gitlab.CreateMergeRequestOptions, options ...gitlab.RequestOptionFunc) (*gitlab.MergeRequest, *gitlab.Response, error) {
761 assert.Equal(t, tt.wantTitle, *opts.Title)
762 return &gitlab.MergeRequest{
763 BasicMergeRequest: gitlab.BasicMergeRequest{
764 ID: 1,
765 IID: 12,
766 ProjectID: 3,
767 Title: tt.wantTitle,
768 State: "opened",
769 TargetBranch: "master",
770 SourceBranch: "feat-new-mr",
771 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
772 },
773 }, nil, nil
774 })
776 cs, csTeardown := test.InitCmdStubber()
777 defer csTeardown()
778 cs.Stub("HEAD branch: master\n")
779 cs.Stub(heredoc.Doc(`
780 deadbeef HEAD
781 deadb00f refs/remotes/upstream/feat-new-mr
782 deadbeef refs/remotes/origin/feat-new-mr
783 `))
785 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
786 cmdtest.WithGitLabClient(testClient.Client),
787 withMRCreateRemotes("feat-new-mr"),
788 )
790 args := append([]string{
791 "--title", `"` + tt.title + `"`,
792 "--description", `"my custom MR description"`,
793 "--source-branch", "feat-new-mr",
794 }, tt.extraArgs...)
796 output, err := exec(strings.Join(args, " "))
797 require.NoError(t, err, output.Stderr())
799 outputLines := strings.SplitN(output.String(), "\n", 2)
800 assert.Contains(t, outputLines[0], "!12 "+tt.wantTitle+" (feat-new-mr)")
801 assert.Contains(t, output.Stderr(), "\nCreating draft merge request for feat-new-mr into master in OWNER/REPO\n\n")
802 })
803 }
804}
806func TestMRCreate_nontty_insufficient_flags(t *testing.T) {
807 t.Parallel()
809 testClient := gitlabtesting.NewTestClient(t)
811 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
813 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false,
814 cmdtest.WithGitLabClient(testClient.Client),
815 func(f *cmdtest.Factory) {
816 f.RemotesStub = func() (glrepo.Remotes, error) {
817 return glrepo.Remotes{
818 {
819 Remote: &git.Remote{
820 Name: "upstream",
821 Resolved: "head",
822 PushURL: pu,
823 },
824 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
825 },
826 {
827 Remote: &git.Remote{
828 Name: "origin",
829 Resolved: "base",
830 PushURL: pu,
831 },
832 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
833 },
834 }, nil
835 }
836 f.BranchStub = func() (string, error) {
837 return "test-br", nil
838 }
839 },
840 )
842 _, err := exec("")
843 require.Error(t, err)
844 assert.Equal(t, "--title or --fill required for non-interactive mode", err.Error())
845}
847func TestMRCreate_nontty_titleDoesNotRequireDescription(t *testing.T) {
848 t.Parallel()
850 testClient := gitlabtesting.NewTestClient(t)
851 testClient.MockProjects.EXPECT().
852 GetProject("OWNER/REPO", gomock.Any()).
853 Return(nil, nil, errors.New("stop after validation"))
854 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
856 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false,
857 cmdtest.WithGitLabClient(testClient.Client),
858 func(f *cmdtest.Factory) {
859 f.RemotesStub = func() (glrepo.Remotes, error) {
860 return glrepo.Remotes{
861 {
862 Remote: &git.Remote{Name: "upstream", Resolved: "head", PushURL: pu},
863 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
864 },
865 {
866 Remote: &git.Remote{Name: "origin", Resolved: "base", PushURL: pu},
867 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
868 },
869 }, nil
870 }
871 f.BranchStub = func() (string, error) {
872 return "test-br", nil
873 }
874 },
875 )
877 _, err := exec("--title test-title")
878 require.EqualError(t, err, "stop after validation")
879}
881func TestMrBodyAndTitle(t *testing.T) {
882 opts := &options{
883 SourceBranch: "mr-autofill-test-br",
884 TargetBranch: "master",
885 TargetTrackingBranch: "origin/master",
886 }
887 t.Run("", func(t *testing.T) {
888 cs, csTeardown := test.InitCmdStubber()
889 defer csTeardown()
890 cs.Stub("d1sd2e,docs: add some changes to txt file") // git log
891 cs.Stub("Here, I am adding some commit body.\nLittle longer\n\nResolves #1\n") // git log
893 if err := mrBodyAndTitle(opts); err != nil {
894 t.Errorf("unexpected error: %v", err)
895 return
896 }
898 assert.Equal(t, "docs: add some changes to txt file", opts.Title)
899 assert.Equal(t, "Here, I am adding some commit body.\nLittle longer\n\nResolves #1\n", opts.Description)
900 })
901 t.Run("given-title", func(t *testing.T) {
902 cs, csTeardown := test.InitCmdStubber()
903 defer csTeardown()
905 cs.Stub("d1sd2e,docs: add some changes to txt file")
906 cs.Stub("Here, I am adding some commit body.\nLittle longer\n\nResolves #1\n") // git log
908 opts := *opts
909 opts.Title = "docs: make some other stuff"
910 if err := mrBodyAndTitle(&opts); err != nil {
911 t.Errorf("unexpected error: %v", err)
912 return
913 }
915 assert.Equal(t, "docs: make some other stuff", opts.Title)
916 assert.Equal(t, `Here, I am adding some commit body.
917Little longer
919Resolves #1
920`, opts.Description)
921 })
922 t.Run("given-description", func(t *testing.T) {
923 cs, csTeardown := test.InitCmdStubber()
924 defer csTeardown()
926 cs.Stub("d1sd2e,docs: add some changes to txt file")
928 opts := *opts
929 opts.Description = `Make it multiple lines
930like this
932resolves #1
933`
934 if err := mrBodyAndTitle(&opts); err != nil {
935 t.Errorf("unexpected error: %v", err)
936 return
937 }
939 assert.Equal(t, "docs: add some changes to txt file", opts.Title)
940 assert.Equal(t, `Make it multiple lines
941like this
943resolves #1
944`, opts.Description)
945 })
946 t.Run("given-fill-commit-body", func(t *testing.T) {
947 opts = &options{
948 SourceBranch: "mr-autofill-test-br",
949 TargetBranch: "master",
950 TargetTrackingBranch: "origin/master",
951 }
952 cs, csTeardown := test.InitCmdStubber()
953 defer csTeardown()
955 cs.Stub("d1sd2e,chore: some tidying\nd2asa3,docs: more changes to more things")
956 cs.Stub("Here, I am adding some commit body.\nLittle longer\n\nResolves #1\n")
957 cs.Stub("another body for another commit\ncloses 1234\n")
959 opts := *opts
960 opts.FillCommitBody = true
962 if err := mrBodyAndTitle(&opts); err != nil {
963 t.Errorf("unexpected error: %v", err)
964 return
965 }
967 assert.Equal(t, "mr autofill test br", opts.Title)
968 // Note: trailing spaces (markdown line breaks) are added to certain lines
969 assert.Equal(t, "- docs: more changes to more things \nHere, I am adding some commit body.\nLittle longer \nResolves #1\n\n- chore: some tidying \nanother body for another commit\ncloses 1234\n\n", opts.Description)
970 })
971}
973func TestGenerateMRCompareURL(t *testing.T) {
974 opts := &options{
975 Labels: []string{"backend", "frontend"},
976 Assignees: []string{"johndoe", "janedoe"},
977 Reviewers: []string{"user", "person"},
978 Milestone: 15,
979 TargetProject: &gitlab.Project{ID: 100},
980 SourceProject: &gitlab.Project{
981 ID: 101,
982 WebURL: "https://gitlab.example.com/gitlab-org/gitlab",
983 },
984 Title: "Autofill tests | for this @project",
985 SourceBranch: "@|calc",
986 TargetBranch: "project/my-branch",
987 }
989 u, err := generateMRCompareURL(opts)
991 expectedUrl := "https://gitlab.example.com/gitlab-org/gitlab/-/merge_requests/new?" +
992 "merge_request%5Bdescription%5D=%0A%2Flabel+~backend%2C+~frontend%0A%2Fassign+johndoe%2C+janedoe%0A%2Freviewer+user%2C+person%0A%2Fmilestone+%2515&" +
993 "merge_request%5Bsource_branch%5D=%40%7Ccalc&merge_request%5Bsource_project_id%5D=101&merge_request%5Btarget_branch%5D=project%2Fmy-branch&merge_request%5Btarget_project_id%5D=100&" +
994 "merge_request%5Btitle%5D=Autofill+tests+%7C+for+this+%40project"
996 require.NoError(t, err)
997 assert.Equal(t, expectedUrl, u)
998}
1000func Test_MRCreate_With_Recover_Integration(t *testing.T) {
1001 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
1002 t.Setenv("NO_COLOR", "true")
1004 testClient := gitlabtesting.NewTestClient(t)
1006 // For the first run: GitLabClientStub returns error to trigger recovery file creation
1007 // For the second run: Normal API mocks
1009 // Mock GetProject (only called on recovery run - first run fails before API call)
1010 testClient.MockProjects.EXPECT().
1011 GetProject("OWNER/REPO", gomock.Any()).
1012 Return(&gitlab.Project{
1013 ID: 1,
1014 DefaultBranch: "master",
1015 WebURL: "http://gitlab.com/OWNER/REPO",
1016 Name: "OWNER",
1017 Path: "REPO",
1018 MergeRequestsEnabled: true,
1019 PathWithNamespace: "OWNER/REPO",
1020 }, nil, nil)
1022 // Mock ListProjectTargetBranchRules (called on recovery run)
1023 testClient.MockProjects.EXPECT().
1024 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
1025 Return([]gitlab.TargetBranchRule{}, nil, nil)
1027 // Mock ListUsers (called on recovery)
1028 testClient.MockUsers.EXPECT().
1029 ListUsers(gomock.Any()).
1030 Return([]*gitlab.User{
1031 {
1032 Username: "testuser",
1033 },
1034 }, nil, nil)
1036 // Mock CreateMergeRequest (called on recovery)
1037 testClient.MockMergeRequests.EXPECT().
1038 CreateMergeRequest("OWNER/REPO", gomock.Any()).
1039 Return(&gitlab.MergeRequest{
1040 BasicMergeRequest: gitlab.BasicMergeRequest{
1041 ID: 1,
1042 IID: 12,
1043 ProjectID: 3,
1044 Title: "myMRtitle",
1045 Description: "myMRbody",
1046 State: "opened",
1047 TargetBranch: "master",
1048 SourceBranch: "feat-new-mr",
1049 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
1050 },
1051 }, nil, nil)
1053 cs, csTeardown := test.InitCmdStubber()
1054 defer csTeardown()
1055 cs.Stub("HEAD branch: master\n")
1056 cs.Stub(heredoc.Doc(`
1057 deadbeef HEAD
1058 deadb00f refs/remotes/upstream/feat-new-mr
1059 deadbeef refs/remotes/origin/feat-new-mr
1060 `))
1061 // For recovery run
1062 cs.Stub("HEAD branch: master\n")
1063 cs.Stub(heredoc.Doc(`
1064 deadbeef HEAD
1065 deadb00f refs/remotes/upstream/feat-new-mr
1066 deadbeef refs/remotes/origin/feat-new-mr
1067 `))
1069 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
1071 cliStr := []string{
1072 "-t", "myMRtitle",
1073 "-d", "myMRbody",
1074 "-l", "test,bug",
1075 "--milestone", "1",
1076 "--assignee", "testuser",
1077 }
1079 cli := strings.Join(cliStr, " ")
1081 // First run - let it fail to create recovery file
1082 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
1083 cmdtest.WithGitLabClient(testClient.Client),
1084 func(f *cmdtest.Factory) {
1085 f.RemotesStub = func() (glrepo.Remotes, error) {
1086 return glrepo.Remotes{
1087 {
1088 Remote: &git.Remote{
1089 Name: "upstream",
1090 Resolved: "head",
1091 PushURL: pu,
1092 },
1093 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
1094 },
1095 {
1096 Remote: &git.Remote{
1097 Name: "origin",
1098 Resolved: "base",
1099 PushURL: pu,
1100 },
1101 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
1102 },
1103 }, nil
1104 }
1105 f.BranchStub = func() (string, error) {
1106 return "feat-new-mr", nil
1107 }
1108 // Return error to trigger recovery file creation
1109 f.GitLabClientStub = func() (*gitlab.Client, error) {
1110 return nil, errors.New("fail on purpose")
1111 }
1112 },
1113 )
1115 output, err := exec(cli)
1117 outErr := output.Stderr()
1119 require.Errorf(t, err, "fail on purpose")
1120 require.Contains(t, outErr, "Failed to create merge request. Created recovery file: ")
1122 // Run create issue with recover
1123 newCliStr := append(slices.Clone(cliStr), "--recover")
1125 newCli := strings.Join(newCliStr, " ")
1127 // Second run - recover from file
1128 exec2 := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
1129 cmdtest.WithGitLabClient(testClient.Client),
1130 func(f *cmdtest.Factory) {
1131 f.RemotesStub = func() (glrepo.Remotes, error) {
1132 return glrepo.Remotes{
1133 {
1134 Remote: &git.Remote{
1135 Name: "upstream",
1136 Resolved: "head",
1137 PushURL: pu,
1138 },
1139 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
1140 },
1141 {
1142 Remote: &git.Remote{
1143 Name: "origin",
1144 Resolved: "base",
1145 PushURL: pu,
1146 },
1147 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
1148 },
1149 }, nil
1150 }
1151 f.BranchStub = func() (string, error) {
1152 return "feat-new-mr", nil
1153 }
1154 },
1155 )
1157 newOutput, newErr := exec2(newCli)
1158 if newErr != nil {
1159 if errors.Is(err, cmdutils.SilentError) {
1160 t.Errorf("Unexpected error: %q", newOutput.Stderr())
1161 }
1162 t.Error(newErr)
1163 return
1164 }
1166 outputLines := strings.SplitN(newOutput.String(), "\n", 2)
1167 require.NoError(t, newErr)
1168 assert.Contains(t, outputLines[0], "Recovered create options from file")
1169 assert.Contains(t, newOutput.String(), "!12 myMRtitle (feat-new-mr)")
1170 assert.Contains(t, newOutput.Stderr(), "\nCreating merge request for feat-new-mr into master in OWNER/REPO\n\n")
1171 assert.Contains(t, newOutput.String(), "https://gitlab.com/OWNER/REPO/-/merge_requests/12")
1172}
1174func TestMRCreate_NoGitRepo_FlagCompleteSucceeds(t *testing.T) {
1175 t.Parallel()
1177 testClient := gitlabtesting.NewTestClient(t)
1179 testClient.MockProjects.EXPECT().
1180 GetProject("OWNER/REPO", gomock.Any()).
1181 Return(&gitlab.Project{
1182 ID: 1,
1183 DefaultBranch: "main",
1184 WebURL: "http://gitlab.com/OWNER/REPO",
1185 Name: "OWNER",
1186 Path: "REPO",
1187 MergeRequestsEnabled: true,
1188 PathWithNamespace: "OWNER/REPO",
1189 }, nil, nil).AnyTimes()
1191 testClient.MockMergeRequests.EXPECT().
1192 CreateMergeRequest("OWNER/REPO", gomock.Any()).
1193 Return(&gitlab.MergeRequest{
1194 BasicMergeRequest: gitlab.BasicMergeRequest{
1195 ID: 1,
1196 IID: 12,
1197 Title: "Test",
1198 Description: "TestDesc",
1199 State: "opened",
1200 TargetBranch: "main",
1201 SourceBranch: "test-branch",
1202 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
1203 },
1204 }, nil, nil)
1206 exec := cmdtest.SetupCmdForTest(t,
1207 func(f cmdutils.Factory) *cobra.Command {
1208 tf, ok := f.(*cmdtest.Factory)
1209 require.True(t, ok, "expected cmdtest.Factory")
1211 // Mirrors what git.Remotes() returns outside a repo: git's own
1212 // (localized) message, labelled with git.ErrNotAGitRepository.
1213 tf.RemotesStub = func() (glrepo.Remotes, error) {
1214 return nil, fmt.Errorf("%w: fatal: not a git repository (or any of the parent directories): .git", git.ErrNotAGitRepository)
1215 }
1216 tf.BranchStub = func() (string, error) {
1217 return "", errors.New("fatal: not a git repository (or any of the parent directories): .git")
1218 }
1220 return NewCmdCreate(f)
1221 },
1222 false,
1223 cmdtest.WithGitLabClient(testClient.Client),
1224 )
1226 cli := "--source-branch test-branch --target-branch main --title Test --description TestDesc --no-editor --yes"
1227 output, err := exec(cli)
1229 require.NoError(t, err, "flag-complete mr create should succeed outside a git repo")
1230 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/merge_requests/12")
1231 assert.Contains(t, output.Stderr(), "Creating merge request for test-branch into main in OWNER/REPO")
1232}
1234func TestMRCreate_PushOutsideGitRepo_PropagatesError(t *testing.T) {
1235 t.Parallel()
1237 testClient := gitlabtesting.NewTestClient(t)
1239 testClient.MockProjects.EXPECT().
1240 GetProject("OWNER/REPO", gomock.Any()).
1241 Return(&gitlab.Project{
1242 ID: 1,
1243 DefaultBranch: "main",
1244 WebURL: "http://gitlab.com/OWNER/REPO",
1245 Name: "OWNER",
1246 Path: "REPO",
1247 MergeRequestsEnabled: true,
1248 PathWithNamespace: "OWNER/REPO",
1249 }, nil, nil).AnyTimes()
1251 exec := cmdtest.SetupCmdForTest(t,
1252 func(f cmdutils.Factory) *cobra.Command {
1253 tf, ok := f.(*cmdtest.Factory)
1254 require.True(t, ok, "expected cmdtest.Factory")
1256 // Mirrors what git.Remotes() returns outside a repo: git's own
1257 // (localized) message, labelled with git.ErrNotAGitRepository.
1258 tf.RemotesStub = func() (glrepo.Remotes, error) {
1259 return nil, fmt.Errorf("%w: fatal: not a git repository (or any of the parent directories): .git", git.ErrNotAGitRepository)
1260 }
1261 tf.BranchStub = func() (string, error) {
1262 return "", errors.New("fatal: not a git repository (or any of the parent directories): .git")
1263 }
1265 return NewCmdCreate(f)
1266 },
1267 false,
1268 cmdtest.WithGitLabClient(testClient.Client),
1269 )
1271 cli := "--source-branch test-branch --target-branch main --title Test --description TestDesc --no-editor --yes --push"
1272 output, err := exec(cli)
1274 require.Error(t, err, "expected error when --push is used outside a git repo")
1275 assert.Contains(t, err.Error(), "not a git repository", "error should mention git repository")
1276 assert.NotContains(t, output.String(), "/-/merge_requests/", "should not have created a merge request")
1277}
1279func TestMRCreate_RemotesResolverError_PropagatesError(t *testing.T) {
1280 t.Parallel()
1282 testClient := gitlabtesting.NewTestClient(t)
1284 testClient.MockProjects.EXPECT().
1285 GetProject("OWNER/REPO", gomock.Any()).
1286 Return(&gitlab.Project{
1287 ID: 1,
1288 DefaultBranch: "main",
1289 WebURL: "http://gitlab.com/OWNER/REPO",
1290 Name: "OWNER",
1291 Path: "REPO",
1292 MergeRequestsEnabled: true,
1293 PathWithNamespace: "OWNER/REPO",
1294 }, nil, nil).AnyTimes()
1296 resolverErr := errors.New("none of the git remotes configured for this repository correspond to the GITLAB_HOST environment variable. Try adding a matching remote or unsetting the variable.")
1298 exec := cmdtest.SetupCmdForTest(t,
1299 func(f cmdutils.Factory) *cobra.Command {
1300 tf, ok := f.(*cmdtest.Factory)
1301 require.True(t, ok, "expected cmdtest.Factory")
1303 tf.RemotesStub = func() (glrepo.Remotes, error) {
1304 return nil, resolverErr
1305 }
1307 return NewCmdCreate(f)
1308 },
1309 false,
1310 cmdtest.WithGitLabClient(testClient.Client),
1311 )
1313 cli := "--source-branch test-branch --target-branch main --title Test --description TestDesc --no-editor --yes"
1314 _, err := exec(cli)
1316 require.Error(t, err, "actionable resolver errors must not be swallowed")
1317 assert.Contains(t, err.Error(), "GITLAB_HOST")
1318}
1320func TestNewCmdCreate_FillPush(t *testing.T) {
1321 tests := []struct {
1322 name string
1323 cli string
1324 wantPushes [][]string
1325 }{
1326 {
1327 name: "fill pushes the branch",
1328 cli: "--fill --yes",
1329 wantPushes: [][]string{{"git", "push", "origin", "HEAD:feat-new-mr"}},
1330 },
1331 {
1332 name: "fill with push pushes the branch",
1333 cli: "--fill --push --yes",
1334 wantPushes: [][]string{{"git", "push", "origin", "HEAD:feat-new-mr"}},
1335 },
1336 {
1337 name: "fill with push=false does not push",
1338 cli: "--fill --push=false --yes",
1339 },
1340 }
1342 for _, tt := range tests {
1343 t.Run(tt.name, func(t *testing.T) {
1344 testClient := gitlabtesting.NewTestClient(t)
1346 testClient.MockProjects.EXPECT().
1347 GetProject("OWNER/REPO", gomock.Any()).
1348 Return(&gitlab.Project{
1349 ID: 1,
1350 DefaultBranch: "main",
1351 WebURL: "https://gitlab.com/OWNER/REPO",
1352 MergeRequestsEnabled: true,
1353 PathWithNamespace: "OWNER/REPO",
1354 }, nil, nil)
1355 testClient.MockProjects.EXPECT().
1356 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
1357 Return([]gitlab.TargetBranchRule{}, nil, nil)
1358 testClient.MockCommits.EXPECT().
1359 GetCommit("OWNER/REPO", "main", gomock.Any()).
1360 Return(&gitlab.Commit{ID: "abc123"}, nil, nil)
1361 testClient.MockMergeRequests.EXPECT().
1362 CreateMergeRequest("OWNER/REPO", gomock.Any()).
1363 Return(&gitlab.MergeRequest{
1364 BasicMergeRequest: gitlab.BasicMergeRequest{
1365 IID: 12,
1366 Title: "feat: add the feature",
1367 State: "opened",
1368 SourceBranch: "feat-new-mr",
1369 TargetBranch: "main",
1370 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
1371 },
1372 }, nil, nil)
1374 cs, csTeardown := test.InitCmdStubber()
1375 defer csTeardown()
1376 cs.Stub("deadbeef,feat: add the feature") // git log
1377 cs.Stub("Body of the commit.") // git show
1378 cs.Stub("") // git status
1379 cs.Stub("") // git push
1380 cs.Stub("") // git config
1381 cs.Stub("") // git branch --set-upstream-to
1383 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
1385 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false,
1386 cmdtest.WithGitLabClient(testClient.Client),
1387 cmdtest.WithBranch("feat-new-mr"),
1388 func(f *cmdtest.Factory) {
1389 f.RemotesStub = func() (glrepo.Remotes, error) {
1390 return glrepo.Remotes{
1391 {
1392 Remote: &git.Remote{
1393 Name: "origin",
1394 Resolved: "head",
1395 PushURL: pu,
1396 },
1397 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
1398 },
1399 }, nil
1400 }
1401 },
1402 )
1404 output, err := exec(tt.cli)
1405 require.NoError(t, err)
1406 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/merge_requests/12")
1408 var pushes [][]string
1409 for _, call := range cs.Calls {
1410 if len(call.Args) > 1 && call.Args[1] == "push" {
1411 pushes = append(pushes, call.Args)
1412 }
1413 }
1414 assert.Equal(t, tt.wantPushes, pushes)
1415 })
1416 }
1417}
1419func TestMRCreate_SquashBeforeMergeFlag(t *testing.T) {
1420 tests := []struct {
1421 name string
1422 flagValue string
1423 flagSet bool
1424 expectedSquashValue *bool
1425 }{
1426 {
1427 name: "flag not set",
1428 flagSet: false,
1429 expectedSquashValue: nil,
1430 },
1431 {
1432 name: "flag set to true",
1433 flagValue: "true",
1434 flagSet: true,
1435 expectedSquashValue: new(true),
1436 },
1437 {
1438 name: "flag set to false",
1439 flagValue: "false",
1440 flagSet: true,
1441 expectedSquashValue: new(false),
1442 },
1443 }
1445 for _, tt := range tests {
1446 t.Run(tt.name, func(t *testing.T) {
1447 // Create a command to test flag parsing
1448 cmd := NewCmdCreate(&cmdtest.Factory{})
1450 // Set up the command line args
1451 args := []string{"--title", "Test", "--description", "Desc"}
1452 if tt.flagSet {
1453 args = append(args, "--squash-before-merge="+tt.flagValue)
1454 }
1456 cmd.SetArgs(args)
1458 err := cmd.ParseFlags(args)
1459 require.NoError(t, err)
1461 // Get the options from the command
1462 opts := &options{}
1464 // Simulate what complete() does
1465 if cmd.Flags().Changed("squash-before-merge") {
1466 squash, _ := cmd.Flags().GetBool("squash-before-merge")
1467 opts.SquashBeforeMerge = &squash
1468 }
1470 // Verify the pointer is set correctly
1471 if tt.expectedSquashValue == nil {
1472 assert.Nil(t, opts.SquashBeforeMerge, "SquashBeforeMerge should be nil when flag is not set")
1473 } else {
1474 require.NotNil(t, opts.SquashBeforeMerge, "SquashBeforeMerge should not be nil when flag is set")
1475 assert.Equal(t, *tt.expectedSquashValue, *opts.SquashBeforeMerge, "SquashBeforeMerge value should match expected")
1476 }
1478 // Test what would be sent to the API
1479 mrCreateOpts := &gitlab.CreateMergeRequestOptions{}
1480 if opts.SquashBeforeMerge != nil {
1481 mrCreateOpts.Squash = opts.SquashBeforeMerge
1482 }
1484 // Verify API options
1485 if tt.expectedSquashValue == nil {
1486 assert.Nil(t, mrCreateOpts.Squash, "Squash should be nil when flag is not set")
1487 } else {
1488 require.NotNil(t, mrCreateOpts.Squash, "Squash should be set when flag is provided")
1489 assert.Equal(t, *tt.expectedSquashValue, *mrCreateOpts.Squash, "Squash API value should match flag value")
1490 }
1491 })
1492 }
1493}
1495func TestMRCreate_BooleanFlags(t *testing.T) {
1496 tests := []struct {
1497 name string
1498 flagName string
1499 flagValue string
1500 flagSet bool
1501 expectedValue *bool
1502 getOptValue func(*options) *bool
1503 getAPIValue func(*gitlab.CreateMergeRequestOptions) *bool
1504 }{
1505 // RemoveSourceBranch tests
1506 {
1507 name: "remove-source-branch not set",
1508 flagName: "remove-source-branch",
1509 flagSet: false,
1510 expectedValue: nil,
1511 getOptValue: func(o *options) *bool { return o.RemoveSourceBranch },
1512 getAPIValue: func(opts *gitlab.CreateMergeRequestOptions) *bool { return opts.RemoveSourceBranch },
1513 },
1514 {
1515 name: "remove-source-branch set to true",
1516 flagName: "remove-source-branch",
1517 flagValue: "true",
1518 flagSet: true,
1519 expectedValue: new(true),
1520 getOptValue: func(o *options) *bool { return o.RemoveSourceBranch },
1521 getAPIValue: func(opts *gitlab.CreateMergeRequestOptions) *bool { return opts.RemoveSourceBranch },
1522 },
1523 {
1524 name: "remove-source-branch set to false",
1525 flagName: "remove-source-branch",
1526 flagValue: "false",
1527 flagSet: true,
1528 expectedValue: new(false),
1529 getOptValue: func(o *options) *bool { return o.RemoveSourceBranch },
1530 getAPIValue: func(opts *gitlab.CreateMergeRequestOptions) *bool { return opts.RemoveSourceBranch },
1531 },
1532 // AllowCollaboration tests
1533 {
1534 name: "allow-collaboration not set",
1535 flagName: "allow-collaboration",
1536 flagSet: false,
1537 expectedValue: nil,
1538 getOptValue: func(o *options) *bool { return o.AllowCollaboration },
1539 getAPIValue: func(opts *gitlab.CreateMergeRequestOptions) *bool { return opts.AllowCollaboration },
1540 },
1541 {
1542 name: "allow-collaboration set to true",
1543 flagName: "allow-collaboration",
1544 flagValue: "true",
1545 flagSet: true,
1546 expectedValue: new(true),
1547 getOptValue: func(o *options) *bool { return o.AllowCollaboration },
1548 getAPIValue: func(opts *gitlab.CreateMergeRequestOptions) *bool { return opts.AllowCollaboration },
1549 },
1550 {
1551 name: "allow-collaboration set to false",
1552 flagName: "allow-collaboration",
1553 flagValue: "false",
1554 flagSet: true,
1555 expectedValue: new(false),
1556 getOptValue: func(o *options) *bool { return o.AllowCollaboration },
1557 getAPIValue: func(opts *gitlab.CreateMergeRequestOptions) *bool { return opts.AllowCollaboration },
1558 },
1559 }
1561 for _, tt := range tests {
1562 t.Run(tt.name, func(t *testing.T) {
1563 // Create a command to test flag parsing
1564 cmd := NewCmdCreate(&cmdtest.Factory{})
1566 // Set up the command line args
1567 args := []string{"--title", "Test", "--description", "Desc"}
1568 if tt.flagSet {
1569 args = append(args, "--"+tt.flagName+"="+tt.flagValue)
1570 }
1572 cmd.SetArgs(args)
1574 err := cmd.ParseFlags(args)
1575 require.NoError(t, err)
1577 // Get the options from the command
1578 opts := &options{}
1580 // Simulate what complete() does
1581 if cmd.Flags().Changed(tt.flagName) {
1582 value, _ := cmd.Flags().GetBool(tt.flagName)
1583 switch tt.flagName {
1584 case "remove-source-branch":
1585 opts.RemoveSourceBranch = &value
1586 case "allow-collaboration":
1587 opts.AllowCollaboration = &value
1588 }
1589 }
1591 // Verify the pointer is set correctly
1592 optValue := tt.getOptValue(opts)
1593 if tt.expectedValue == nil {
1594 assert.Nil(t, optValue, "%s should be nil when flag is not set", tt.flagName)
1595 } else {
1596 require.NotNil(t, optValue, "%s should not be nil when flag is set", tt.flagName)
1597 assert.Equal(t, *tt.expectedValue, *optValue, "%s value should match expected", tt.flagName)
1598 }
1600 // Test what would be sent to the API
1601 mrCreateOpts := &gitlab.CreateMergeRequestOptions{}
1602 if opts.RemoveSourceBranch != nil {
1603 mrCreateOpts.RemoveSourceBranch = opts.RemoveSourceBranch
1604 }
1605 if opts.AllowCollaboration != nil {
1606 mrCreateOpts.AllowCollaboration = opts.AllowCollaboration
1607 }
1609 // Verify API options
1610 apiValue := tt.getAPIValue(mrCreateOpts)
1611 if tt.expectedValue == nil {
1612 assert.Nil(t, apiValue, "%s should be nil in API when flag is not set", tt.flagName)
1613 } else {
1614 require.NotNil(t, apiValue, "%s should be set in API when flag is provided", tt.flagName)
1615 assert.Equal(t, *tt.expectedValue, *apiValue, "%s API value should match flag value", tt.flagName)
1616 }
1617 })
1618 }
1619}
1621func TestNewCmdCreate_WithAutoMerge(t *testing.T) {
1622 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
1623 t.Setenv("NO_COLOR", "true")
1625 testClient := gitlabtesting.NewTestClient(t)
1627 // Mock GetProject
1628 testClient.MockProjects.EXPECT().
1629 GetProject("OWNER/REPO", gomock.Any()).
1630 Return(&gitlab.Project{
1631 ID: 1,
1632 DefaultBranch: "master",
1633 WebURL: "http://gitlab.com/OWNER/REPO",
1634 Name: "OWNER",
1635 Path: "REPO",
1636 MergeRequestsEnabled: true,
1637 PathWithNamespace: "OWNER/REPO",
1638 }, nil, nil)
1640 // Mock ListProjectTargetBranchRules (no rules configured)
1641 testClient.MockProjects.EXPECT().
1642 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
1643 Return([]gitlab.TargetBranchRule{}, nil, nil)
1645 // Mock CreateMergeRequest
1646 testClient.MockMergeRequests.EXPECT().
1647 CreateMergeRequest("OWNER/REPO", gomock.Any()).
1648 Return(&gitlab.MergeRequest{
1649 BasicMergeRequest: gitlab.BasicMergeRequest{
1650 ID: 1,
1651 IID: 12,
1652 ProjectID: 3,
1653 Title: "myMRtitle",
1654 Description: "myMRbody",
1655 State: "opened",
1656 TargetBranch: "master",
1657 SourceBranch: "feat-new-mr",
1658 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
1659 SHA: "abc123",
1660 },
1661 }, nil, nil)
1663 // Mock AcceptMergeRequest for auto-merge
1664 testClient.MockMergeRequests.EXPECT().
1665 AcceptMergeRequest("OWNER/REPO", int64(12), gomock.Any()).
1666 DoAndReturn(func(pid any, mr int64, opts *gitlab.AcceptMergeRequestOptions, options ...gitlab.RequestOptionFunc) (*gitlab.MergeRequest, *gitlab.Response, error) {
1667 // Verify that AutoMerge is set to true and SHA is provided
1668 assert.NotNil(t, opts.AutoMerge)
1669 assert.True(t, *opts.AutoMerge)
1670 assert.NotNil(t, opts.SHA)
1671 assert.Equal(t, "abc123", *opts.SHA)
1673 return &gitlab.MergeRequest{
1674 BasicMergeRequest: gitlab.BasicMergeRequest{
1675 ID: 1,
1676 IID: 12,
1677 ProjectID: 3,
1678 Title: "myMRtitle",
1679 Description: "myMRbody",
1680 State: "opened",
1681 TargetBranch: "master",
1682 SourceBranch: "feat-new-mr",
1683 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
1684 },
1685 }, nil, nil
1686 })
1688 cs, csTeardown := test.InitCmdStubber()
1689 defer csTeardown()
1690 cs.Stub("HEAD branch: master\n")
1691 cs.Stub(heredoc.Doc(`
1692 deadbeef HEAD
1693 deadb00f refs/remotes/upstream/feat-new-mr
1694 deadbeef refs/remotes/origin/feat-new-mr
1695 `))
1697 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
1699 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
1700 cmdtest.WithGitLabClient(testClient.Client),
1701 func(f *cmdtest.Factory) {
1702 f.RemotesStub = func() (glrepo.Remotes, error) {
1703 return glrepo.Remotes{
1704 {
1705 Remote: &git.Remote{
1706 Name: "upstream",
1707 Resolved: "head",
1708 PushURL: pu,
1709 },
1710 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
1711 },
1712 {
1713 Remote: &git.Remote{
1714 Name: "origin",
1715 Resolved: "base",
1716 PushURL: pu,
1717 },
1718 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
1719 },
1720 }, nil
1721 }
1722 f.BranchStub = func() (string, error) {
1723 return "feat-new-mr", nil
1724 }
1725 },
1726 )
1728 cliStr := []string{
1729 "-t", "myMRtitle",
1730 "-d", "myMRbody",
1731 "--auto-merge",
1732 }
1734 cli := strings.Join(cliStr, " ")
1736 output, err := exec(cli)
1737 if err != nil {
1738 if errors.Is(err, cmdutils.SilentError) {
1739 t.Errorf("Unexpected error: %q", output.Stderr())
1740 }
1741 t.Error(err)
1742 return
1743 }
1745 outputLines := strings.Split(output.String(), "\n")
1746 assert.Contains(t, outputLines[0], "!12 myMRtitle (feat-new-mr)")
1747 assert.Contains(t, output.Stderr(), "\nCreating merge request for feat-new-mr into master in OWNER/REPO\n\n")
1748 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/merge_requests/12")
1749 assert.Contains(t, output.String(), "Auto-merge enabled. Will merge when all checks pass.")
1750}
1752func TestNewCmdCreate_WithAutoMergeFailure(t *testing.T) {
1753 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
1754 t.Setenv("NO_COLOR", "true")
1756 testClient := gitlabtesting.NewTestClient(t)
1758 // Mock GetProject
1759 testClient.MockProjects.EXPECT().
1760 GetProject("OWNER/REPO", gomock.Any()).
1761 Return(&gitlab.Project{
1762 ID: 1,
1763 DefaultBranch: "master",
1764 WebURL: "http://gitlab.com/OWNER/REPO",
1765 Name: "OWNER",
1766 Path: "REPO",
1767 MergeRequestsEnabled: true,
1768 PathWithNamespace: "OWNER/REPO",
1769 }, nil, nil)
1771 // Mock ListProjectTargetBranchRules (no rules configured)
1772 testClient.MockProjects.EXPECT().
1773 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
1774 Return([]gitlab.TargetBranchRule{}, nil, nil)
1776 // Mock CreateMergeRequest
1777 testClient.MockMergeRequests.EXPECT().
1778 CreateMergeRequest("OWNER/REPO", gomock.Any()).
1779 Return(&gitlab.MergeRequest{
1780 BasicMergeRequest: gitlab.BasicMergeRequest{
1781 ID: 1,
1782 IID: 12,
1783 ProjectID: 3,
1784 Title: "myMRtitle",
1785 Description: "myMRbody",
1786 State: "opened",
1787 TargetBranch: "master",
1788 SourceBranch: "feat-new-mr",
1789 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
1790 SHA: "abc123",
1791 },
1792 }, nil, nil)
1794 // Mock AcceptMergeRequest to fail
1795 testClient.MockMergeRequests.EXPECT().
1796 AcceptMergeRequest("OWNER/REPO", int64(12), gomock.Any()).
1797 Return(nil, nil, errors.New("405 Method Not Allowed"))
1799 cs, csTeardown := test.InitCmdStubber()
1800 defer csTeardown()
1801 cs.Stub("HEAD branch: master\n")
1802 cs.Stub(heredoc.Doc(`
1803 deadbeef HEAD
1804 deadb00f refs/remotes/upstream/feat-new-mr
1805 deadbeef refs/remotes/origin/feat-new-mr
1806 `))
1808 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
1810 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
1811 cmdtest.WithGitLabClient(testClient.Client),
1812 func(f *cmdtest.Factory) {
1813 f.RemotesStub = func() (glrepo.Remotes, error) {
1814 return glrepo.Remotes{
1815 {
1816 Remote: &git.Remote{
1817 Name: "upstream",
1818 Resolved: "head",
1819 PushURL: pu,
1820 },
1821 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
1822 },
1823 {
1824 Remote: &git.Remote{
1825 Name: "origin",
1826 Resolved: "base",
1827 PushURL: pu,
1828 },
1829 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
1830 },
1831 }, nil
1832 }
1833 f.BranchStub = func() (string, error) {
1834 return "feat-new-mr", nil
1835 }
1836 },
1837 )
1839 cliStr := []string{
1840 "-t", "myMRtitle",
1841 "-d", "myMRbody",
1842 "--auto-merge",
1843 }
1845 cli := strings.Join(cliStr, " ")
1847 output, err := exec(cli)
1849 // Should get an error
1850 require.Error(t, err)
1851 assert.Contains(t, err.Error(), "merge request created but auto-merge could not be enabled")
1852 assert.Contains(t, err.Error(), "405 Method Not Allowed")
1854 // But the MR should still be displayed
1855 assert.Contains(t, output.String(), "!12 myMRtitle (feat-new-mr)")
1856 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/merge_requests/12")
1857}
1859func TestNewCmdCreate_TargetBranchRule(t *testing.T) {
1860 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
1861 t.Setenv("NO_COLOR", "true")
1863 testClient := gitlabtesting.NewTestClient(t)
1865 // Mock GetProject
1866 testClient.MockProjects.EXPECT().
1867 GetProject("OWNER/REPO", gomock.Any()).
1868 Return(&gitlab.Project{
1869 ID: 1,
1870 DefaultBranch: "main",
1871 WebURL: "http://gitlab.com/OWNER/REPO",
1872 Name: "OWNER",
1873 Path: "REPO",
1874 MergeRequestsEnabled: true,
1875 PathWithNamespace: "OWNER/REPO",
1876 }, nil, nil)
1878 // Mock ListProjectTargetBranchRules: "feature/*" → "development"
1879 testClient.MockProjects.EXPECT().
1880 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
1881 Return([]gitlab.TargetBranchRule{
1882 {Name: "feature/*", TargetBranch: "development"},
1883 }, nil, nil)
1885 // Mock CreateMergeRequest: verify target branch is "development", not "main"
1886 testClient.MockMergeRequests.EXPECT().
1887 CreateMergeRequest("OWNER/REPO", gomock.Any()).
1888 DoAndReturn(func(pid any, opts *gitlab.CreateMergeRequestOptions, options ...gitlab.RequestOptionFunc) (*gitlab.MergeRequest, *gitlab.Response, error) {
1889 assert.Equal(t, "development", *opts.TargetBranch)
1890 return &gitlab.MergeRequest{
1891 BasicMergeRequest: gitlab.BasicMergeRequest{
1892 ID: 1,
1893 IID: 12,
1894 ProjectID: 3,
1895 Title: "myMRtitle",
1896 Description: "myMRbody",
1897 State: "opened",
1898 TargetBranch: "development",
1899 SourceBranch: "feature/my-feature",
1900 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
1901 },
1902 }, nil, nil
1903 })
1905 cs, csTeardown := test.InitCmdStubber()
1906 defer csTeardown()
1907 cs.Stub("HEAD branch: main\n")
1908 cs.Stub(heredoc.Doc(`
1909 deadbeef HEAD
1910 deadb00f refs/remotes/upstream/feature/my-feature
1911 deadbeef refs/remotes/origin/feature/my-feature
1912 `))
1914 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
1916 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
1917 cmdtest.WithGitLabClient(testClient.Client),
1918 func(f *cmdtest.Factory) {
1919 f.RemotesStub = func() (glrepo.Remotes, error) {
1920 return glrepo.Remotes{
1921 {
1922 Remote: &git.Remote{
1923 Name: "upstream",
1924 Resolved: "head",
1925 PushURL: pu,
1926 },
1927 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
1928 },
1929 {
1930 Remote: &git.Remote{
1931 Name: "origin",
1932 Resolved: "base",
1933 PushURL: pu,
1934 },
1935 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
1936 },
1937 }, nil
1938 }
1939 f.BranchStub = func() (string, error) {
1940 return "feature/my-feature", nil
1941 }
1942 },
1943 )
1945 output, err := exec("-t myMRtitle -d myMRbody")
1946 require.NoError(t, err)
1947 assert.Contains(t, output.Stderr(), "Creating merge request for feature/my-feature into development in OWNER/REPO")
1948}
1950func TestMRCreate_TemplateDirectoryError(t *testing.T) {
1951 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
1952 root := t.TempDir()
1953 folder := filepath.Join(root, ".gitlab", "merge_request_templates")
1954 require.NoError(t, os.MkdirAll(filepath.Dir(folder), 0o755))
1955 require.NoError(t, os.WriteFile(folder, []byte("not a directory"), 0o644))
1956 originalToplevelDir := git.ToplevelDir
1957 git.ToplevelDir = func() (string, error) { return root, nil }
1958 t.Cleanup(func() { git.ToplevelDir = originalToplevelDir })
1960 ios, _, _, _ := cmdtest.TestIOStreams(cmdtest.WithTestIOStreamsAsTTY(true))
1961 tc := gitlabtesting.NewTestClient(t)
1962 tc.MockProjects.EXPECT().GetProject("OWNER/REPO", gomock.Any()).
1963 DoAndReturn(func(any, *gitlab.GetProjectOptions, ...gitlab.RequestOptionFunc) (*gitlab.Project, *gitlab.Response, error) {
1964 // Keep interactive flag parsing while testing with prompts disabled.
1965 ios.SetPrompt("true")
1966 return &gitlab.Project{ID: 1, PathWithNamespace: "OWNER/REPO", MergeRequestsEnabled: true}, nil, nil
1967 })
1968 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
1969 cmd := NewCmdCreate(f)
1970 // Select does not check PromptEnabled; cancellation prevents a reverted fix from blocking.
1971 ctx, cancel := context.WithCancel(t.Context())
1972 cancel()
1973 cmd.SetContext(ctx)
1974 return cmd
1975 }, true,
1976 cmdtest.WithGitLabClient(tc.Client), cmdtest.WithIOStreamsOverride(ios),
1977 func(f *cmdtest.Factory) {
1978 f.RemotesStub = func() (glrepo.Remotes, error) { return nil, git.ErrNotAGitRepository }
1979 },
1980 )
1981 _, err := exec(`--title "Test MR" --source-branch feature --target-branch main --yes`)
1982 var pathErr *os.PathError
1983 require.ErrorAs(t, err, &pathErr)
1984 assert.Equal(t, folder, pathErr.Path)
1985 assert.ErrorContains(t, err, "error getting templates")
1986}
1988func TestNewCmdCreate_WithTemplate(t *testing.T) {
1989 // Cannot use t.Parallel(): test mutates git.ToplevelDir, a package-level variable.
1990 t.Setenv("NO_COLOR", "true")
1992 tmpDir := t.TempDir()
1993 templateDir := filepath.Join(tmpDir, ".gitlab", "merge_request_templates")
1994 require.NoError(t, os.MkdirAll(templateDir, 0o755))
1995 require.NoError(t, os.WriteFile(filepath.Join(templateDir, "bug_fix.md"), []byte("## What does this MR do?"), 0o644))
1997 origToplevelDir := git.ToplevelDir
1998 git.ToplevelDir = func() (string, error) { return tmpDir, nil }
1999 t.Cleanup(func() { git.ToplevelDir = origToplevelDir })
2001 testClient := gitlabtesting.NewTestClient(t)
2002 testClient.MockProjects.EXPECT().
2003 GetProject("OWNER/REPO", gomock.Any()).
2004 Return(&gitlab.Project{
2005 ID: 1,
2006 DefaultBranch: "master",
2007 WebURL: "http://gitlab.com/OWNER/REPO",
2008 MergeRequestsEnabled: true,
2009 PathWithNamespace: "OWNER/REPO",
2010 }, nil, nil)
2011 testClient.MockProjects.EXPECT().
2012 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
2013 Return([]gitlab.TargetBranchRule{}, nil, nil)
2014 testClient.MockMergeRequests.EXPECT().
2015 CreateMergeRequest("OWNER/REPO", gomock.Any()).
2016 DoAndReturn(func(_ any, opts *gitlab.CreateMergeRequestOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.MergeRequest, *gitlab.Response, error) {
2017 assert.Equal(t, "## What does this MR do?", *opts.Description)
2018 return &gitlab.MergeRequest{
2019 BasicMergeRequest: gitlab.BasicMergeRequest{
2020 IID: 12,
2021 Title: "Fix the bug",
2022 SourceBranch: "feat-new-mr",
2023 TargetBranch: "master",
2024 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
2025 },
2026 }, nil, nil
2027 })
2029 cs, csTeardown := test.InitCmdStubber()
2030 defer csTeardown()
2031 cs.Stub("HEAD branch: master\n")
2032 cs.Stub(heredoc.Doc(`
2033 deadbeef HEAD
2034 deadb00f refs/remotes/upstream/feat-new-mr
2035 deadbeef refs/remotes/origin/feat-new-mr
2036 `))
2038 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
2040 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
2041 cmdtest.WithGitLabClient(testClient.Client),
2042 func(f *cmdtest.Factory) {
2043 f.RemotesStub = func() (glrepo.Remotes, error) {
2044 return glrepo.Remotes{
2045 {
2046 Remote: &git.Remote{Name: "upstream", Resolved: "head", PushURL: pu},
2047 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
2048 },
2049 {
2050 Remote: &git.Remote{Name: "origin", Resolved: "base", PushURL: pu},
2051 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
2052 },
2053 }, nil
2054 }
2055 f.BranchStub = func() (string, error) { return "feat-new-mr", nil }
2056 },
2057 )
2059 output, err := exec(`--title "Fix the bug" --template bug_fix --source-branch feat-new-mr --yes`)
2060 require.NoError(t, err)
2061 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/merge_requests/12")
2062}
2064func TestNewCmdCreate_WithTemplateFilePath(t *testing.T) {
2065 // Cannot use t.Parallel(): test mutates git.ToplevelDir, a package-level variable.
2066 t.Setenv("NO_COLOR", "true")
2068 templateFile := filepath.Join(t.TempDir(), "bug_fix.md")
2069 require.NoError(t, os.WriteFile(templateFile, []byte("## Team MR template"), 0o644))
2071 origToplevelDir := git.ToplevelDir
2072 git.ToplevelDir = func() (string, error) { return "", errors.New("not a git repository") }
2073 t.Cleanup(func() { git.ToplevelDir = origToplevelDir })
2075 testClient := gitlabtesting.NewTestClient(t)
2076 testClient.MockProjects.EXPECT().
2077 GetProject("OWNER/REPO", gomock.Any()).
2078 Return(&gitlab.Project{
2079 ID: 1,
2080 DefaultBranch: "master",
2081 WebURL: "http://gitlab.com/OWNER/REPO",
2082 MergeRequestsEnabled: true,
2083 PathWithNamespace: "OWNER/REPO",
2084 }, nil, nil)
2085 testClient.MockProjects.EXPECT().
2086 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
2087 Return([]gitlab.TargetBranchRule{}, nil, nil)
2088 testClient.MockMergeRequests.EXPECT().
2089 CreateMergeRequest("OWNER/REPO", gomock.Any()).
2090 DoAndReturn(func(_ any, opts *gitlab.CreateMergeRequestOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.MergeRequest, *gitlab.Response, error) {
2091 assert.Equal(t, "## Team MR template", *opts.Description)
2092 return &gitlab.MergeRequest{
2093 BasicMergeRequest: gitlab.BasicMergeRequest{
2094 IID: 12,
2095 Title: "Fix the bug",
2096 SourceBranch: "feat-new-mr",
2097 TargetBranch: "master",
2098 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
2099 },
2100 }, nil, nil
2101 })
2103 cs, csTeardown := test.InitCmdStubber()
2104 defer csTeardown()
2105 cs.Stub("HEAD branch: master\n")
2106 cs.Stub(heredoc.Doc(`
2107 deadbeef HEAD
2108 deadb00f refs/remotes/upstream/feat-new-mr
2109 deadbeef refs/remotes/origin/feat-new-mr
2110 `))
2112 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
2114 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
2115 cmdtest.WithGitLabClient(testClient.Client),
2116 func(f *cmdtest.Factory) {
2117 f.RemotesStub = func() (glrepo.Remotes, error) {
2118 return glrepo.Remotes{
2119 {
2120 Remote: &git.Remote{Name: "upstream", Resolved: "head", PushURL: pu},
2121 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
2122 },
2123 {
2124 Remote: &git.Remote{Name: "origin", Resolved: "base", PushURL: pu},
2125 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
2126 },
2127 }, nil
2128 }
2129 f.BranchStub = func() (string, error) { return "feat-new-mr", nil }
2130 },
2131 )
2133 output, err := exec(fmt.Sprintf(`--title "Fix the bug" --template %q --source-branch feat-new-mr --yes`, templateFile))
2134 require.NoError(t, err)
2135 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/merge_requests/12")
2136}
2138func TestNewCmdCreate_WithTemplateMdExtension(t *testing.T) {
2139 // Cannot use t.Parallel(): test mutates git.ToplevelDir, a package-level variable.
2140 t.Setenv("NO_COLOR", "true")
2142 tmpDir := t.TempDir()
2143 templateDir := filepath.Join(tmpDir, ".gitlab", "merge_request_templates")
2144 require.NoError(t, os.MkdirAll(templateDir, 0o755))
2145 require.NoError(t, os.WriteFile(filepath.Join(templateDir, "bug_fix.md"), []byte("## What does this MR do?"), 0o644))
2147 origToplevelDir := git.ToplevelDir
2148 git.ToplevelDir = func() (string, error) { return tmpDir, nil }
2149 t.Cleanup(func() { git.ToplevelDir = origToplevelDir })
2151 testClient := gitlabtesting.NewTestClient(t)
2152 testClient.MockProjects.EXPECT().
2153 GetProject("OWNER/REPO", gomock.Any()).
2154 Return(&gitlab.Project{
2155 ID: 1,
2156 DefaultBranch: "master",
2157 WebURL: "http://gitlab.com/OWNER/REPO",
2158 MergeRequestsEnabled: true,
2159 PathWithNamespace: "OWNER/REPO",
2160 }, nil, nil)
2161 testClient.MockProjects.EXPECT().
2162 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
2163 Return([]gitlab.TargetBranchRule{}, nil, nil)
2164 testClient.MockMergeRequests.EXPECT().
2165 CreateMergeRequest("OWNER/REPO", gomock.Any()).
2166 DoAndReturn(func(_ any, opts *gitlab.CreateMergeRequestOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.MergeRequest, *gitlab.Response, error) {
2167 assert.Equal(t, "## What does this MR do?", *opts.Description)
2168 return &gitlab.MergeRequest{
2169 BasicMergeRequest: gitlab.BasicMergeRequest{
2170 IID: 12,
2171 Title: "Fix the bug",
2172 SourceBranch: "feat-new-mr",
2173 TargetBranch: "master",
2174 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
2175 },
2176 }, nil, nil
2177 })
2179 cs, csTeardown := test.InitCmdStubber()
2180 defer csTeardown()
2181 cs.Stub("HEAD branch: master\n")
2182 cs.Stub(heredoc.Doc(`
2183 deadbeef HEAD
2184 deadb00f refs/remotes/upstream/feat-new-mr
2185 deadbeef refs/remotes/origin/feat-new-mr
2186 `))
2188 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
2190 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
2191 cmdtest.WithGitLabClient(testClient.Client),
2192 func(f *cmdtest.Factory) {
2193 f.RemotesStub = func() (glrepo.Remotes, error) {
2194 return glrepo.Remotes{
2195 {
2196 Remote: &git.Remote{Name: "upstream", Resolved: "head", PushURL: pu},
2197 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
2198 },
2199 {
2200 Remote: &git.Remote{Name: "origin", Resolved: "base", PushURL: pu},
2201 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
2202 },
2203 }, nil
2204 }
2205 f.BranchStub = func() (string, error) { return "feat-new-mr", nil }
2206 },
2207 )
2209 // Passing "bug_fix.md" should work the same as "bug_fix"
2210 output, err := exec(`--title "Fix the bug" --template bug_fix.md --source-branch feat-new-mr --yes`)
2211 require.NoError(t, err)
2212 assert.Contains(t, output.String(), "https://gitlab.com/OWNER/REPO/-/merge_requests/12")
2213}
2215func TestNewCmdCreate_TemplateNotFound(t *testing.T) {
2216 // Cannot use t.Parallel(): test mutates git.ToplevelDir, a package-level variable.
2217 tmpDir := t.TempDir()
2218 require.NoError(t, os.MkdirAll(filepath.Join(tmpDir, ".gitlab", "merge_request_templates"), 0o755))
2220 origToplevelDir := git.ToplevelDir
2221 git.ToplevelDir = func() (string, error) { return tmpDir, nil }
2222 t.Cleanup(func() { git.ToplevelDir = origToplevelDir })
2224 testClient := gitlabtesting.NewTestClient(t)
2225 testClient.MockProjects.EXPECT().
2226 GetProject("OWNER/REPO", gomock.Any()).
2227 Return(&gitlab.Project{
2228 ID: 1,
2229 DefaultBranch: "master",
2230 MergeRequestsEnabled: true,
2231 PathWithNamespace: "OWNER/REPO",
2232 }, nil, nil)
2233 testClient.MockProjects.EXPECT().
2234 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
2235 Return([]gitlab.TargetBranchRule{}, nil, nil)
2237 cs, csTeardown := test.InitCmdStubber()
2238 defer csTeardown()
2239 cs.Stub("HEAD branch: master\n")
2240 cs.Stub(heredoc.Doc(`
2241 deadbeef HEAD
2242 deadb00f refs/remotes/upstream/feat-new-mr
2243 deadbeef refs/remotes/origin/feat-new-mr
2244 `))
2246 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
2248 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
2249 cmdtest.WithGitLabClient(testClient.Client),
2250 func(f *cmdtest.Factory) {
2251 f.RemotesStub = func() (glrepo.Remotes, error) {
2252 return glrepo.Remotes{
2253 {
2254 Remote: &git.Remote{Name: "upstream", Resolved: "head", PushURL: pu},
2255 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
2256 },
2257 {
2258 Remote: &git.Remote{Name: "origin", Resolved: "base", PushURL: pu},
2259 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
2260 },
2261 }, nil
2262 }
2263 f.BranchStub = func() (string, error) { return "feat-new-mr", nil }
2264 },
2265 )
2267 _, err := exec(`--title "Fix the bug" --template nonexistent --source-branch feat-new-mr --yes`)
2268 assert.ErrorContains(t, err, `template "nonexistent" not found in .gitlab/merge_request_templates/`)
2269}
2271func TestNewCmdCreate_TemplateFilePathNotFound(t *testing.T) {
2272 // Cannot use t.Parallel(): test uses test.InitCmdStubber, which mutates package-level state.
2273 testClient := gitlabtesting.NewTestClient(t)
2274 testClient.MockProjects.EXPECT().
2275 GetProject("OWNER/REPO", gomock.Any()).
2276 Return(&gitlab.Project{
2277 ID: 1,
2278 DefaultBranch: "master",
2279 MergeRequestsEnabled: true,
2280 PathWithNamespace: "OWNER/REPO",
2281 }, nil, nil)
2282 testClient.MockProjects.EXPECT().
2283 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
2284 Return([]gitlab.TargetBranchRule{}, nil, nil)
2286 cs, csTeardown := test.InitCmdStubber()
2287 defer csTeardown()
2288 cs.Stub("HEAD branch: master\n")
2289 cs.Stub(heredoc.Doc(`
2290 deadbeef HEAD
2291 deadb00f refs/remotes/upstream/feat-new-mr
2292 deadbeef refs/remotes/origin/feat-new-mr
2293 `))
2295 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
2297 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, true,
2298 cmdtest.WithGitLabClient(testClient.Client),
2299 func(f *cmdtest.Factory) {
2300 f.RemotesStub = func() (glrepo.Remotes, error) {
2301 return glrepo.Remotes{
2302 {
2303 Remote: &git.Remote{Name: "upstream", Resolved: "head", PushURL: pu},
2304 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
2305 },
2306 {
2307 Remote: &git.Remote{Name: "origin", Resolved: "base", PushURL: pu},
2308 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
2309 },
2310 }, nil
2311 }
2312 f.BranchStub = func() (string, error) { return "feat-new-mr", nil }
2313 },
2314 )
2316 missing := filepath.Join(t.TempDir(), "missing.md")
2317 _, err := exec(fmt.Sprintf(`--title "Fix the bug" --template %q --source-branch feat-new-mr --yes`, missing))
2318 assert.ErrorIs(t, err, fs.ErrNotExist)
2319}
2321func TestNewCmdCreate_TemplateMutuallyExclusiveWithDescription(t *testing.T) {
2322 t.Parallel()
2324 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false)
2326 _, err := exec(`--title "Fix" --template bug_fix --description "my description" --source-branch feat-new-mr`)
2327 assert.Error(t, err)
2328}
2330func TestNewCmdCreate_TemplateMutuallyExclusiveWithFill(t *testing.T) {
2331 t.Parallel()
2333 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false)
2335 _, err := exec(`--title "Fix" --template bug_fix --fill --source-branch feat-new-mr`)
2336 assert.Error(t, err)
2337}
2339func TestMatchBranchPattern(t *testing.T) {
2340 t.Parallel()
2342 tests := []struct {
2343 pattern string
2344 branch string
2345 want bool
2346 }{
2347 {"*", "main", true},
2348 {"*", "feature/foo", true},
2349 {"feature/*", "feature/my-feature", true},
2350 {"feature/*", "feature/foo/bar", true},
2351 {"feature/*", "hotfix/oops", false},
2352 {"hotfix/*", "hotfix/urgent", true},
2353 {"main", "main", true},
2354 {"main", "maintenance", false},
2355 }
2356 for _, tt := range tests {
2357 t.Run(tt.pattern+"/"+tt.branch, func(t *testing.T) {
2358 t.Parallel()
2359 got, err := matchBranchPattern(tt.pattern, tt.branch)
2360 require.NoError(t, err)
2361 assert.Equal(t, tt.want, got)
2362 })
2363 }
2364}
2366func TestNewCmdCreate_DescriptionFile(t *testing.T) {
2367 const body = "# Heading\n\nMulti-line body with \"quotes\", $VARS and `backticks`.\n"
2369 tests := []struct {
2370 name string
2371 useStdin bool
2372 }{
2373 {name: "reads the description from a file"},
2374 {name: "reads the description from standard input", useStdin: true},
2375 }
2377 for _, tt := range tests {
2378 t.Run(tt.name, func(t *testing.T) {
2379 t.Setenv("NO_COLOR", "true")
2381 testClient := gitlabtesting.NewTestClient(t)
2382 testClient.MockProjects.EXPECT().
2383 GetProject("OWNER/REPO", gomock.Any()).
2384 Return(&gitlab.Project{
2385 ID: 1,
2386 DefaultBranch: "master",
2387 WebURL: "http://gitlab.com/OWNER/REPO",
2388 MergeRequestsEnabled: true,
2389 PathWithNamespace: "OWNER/REPO",
2390 }, nil, nil)
2391 testClient.MockProjects.EXPECT().
2392 ListProjectTargetBranchRules("OWNER/REPO", gomock.Any()).
2393 Return([]gitlab.TargetBranchRule{}, nil, nil)
2395 var gotDescription *string
2396 testClient.MockMergeRequests.EXPECT().
2397 CreateMergeRequest("OWNER/REPO", gomock.Any()).
2398 DoAndReturn(func(_ any, opts *gitlab.CreateMergeRequestOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.MergeRequest, *gitlab.Response, error) {
2399 gotDescription = opts.Description
2400 return &gitlab.MergeRequest{
2401 BasicMergeRequest: gitlab.BasicMergeRequest{
2402 IID: 12,
2403 Title: "myMRtitle",
2404 State: "opened",
2405 TargetBranch: "master",
2406 SourceBranch: "feat-new-mr",
2407 WebURL: "https://gitlab.com/OWNER/REPO/-/merge_requests/12",
2408 },
2409 }, nil, nil
2410 })
2412 cs, csTeardown := test.InitCmdStubber()
2413 defer csTeardown()
2414 cs.Stub("HEAD branch: master\n")
2415 cs.Stub(heredoc.Doc(`
2416 deadbeef HEAD
2417 deadb00f refs/remotes/upstream/feat-new-mr
2418 deadbeef refs/remotes/origin/feat-new-mr
2419 `))
2421 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
2423 factoryOpts := []cmdtest.FactoryOption{
2424 cmdtest.WithGitLabClient(testClient.Client),
2425 func(f *cmdtest.Factory) {
2426 f.RemotesStub = func() (glrepo.Remotes, error) {
2427 return glrepo.Remotes{
2428 {
2429 Remote: &git.Remote{Name: "upstream", Resolved: "head", PushURL: pu},
2430 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
2431 },
2432 {
2433 Remote: &git.Remote{Name: "origin", Resolved: "base", PushURL: pu},
2434 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
2435 },
2436 }, nil
2437 }
2438 f.BranchStub = func() (string, error) { return "feat-new-mr", nil }
2439 },
2440 }
2442 path := "-"
2443 if tt.useStdin {
2444 factoryOpts = append(factoryOpts, cmdtest.WithStdin(body))
2445 } else {
2446 path = filepath.Join(t.TempDir(), "description.md")
2447 require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
2448 }
2450 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false, factoryOpts...)
2452 _, err := exec(fmt.Sprintf("-t myMRtitle --description-file %q --yes", path))
2453 require.NoError(t, err)
2455 require.NotNil(t, gotDescription)
2456 assert.Equal(t, body, *gotDescription)
2457 })
2458 }
2459}
2461func TestNewCmdCreate_DescriptionFileConflicts(t *testing.T) {
2462 tests := []struct {
2463 name string
2464 cli string
2465 want string
2466 }{
2467 {
2468 name: "with --description",
2469 cli: `-t title --description inline --description-file some.md`,
2470 want: "[description description-file]",
2471 },
2472 {
2473 name: "with --template",
2474 cli: `-t title --template bug_fix --description-file some.md`,
2475 want: "[template description-file]",
2476 },
2477 }
2479 for _, tt := range tests {
2480 t.Run(tt.name, func(t *testing.T) {
2481 exec := cmdtest.SetupCmdForTest(t, NewCmdCreate, false)
2483 _, err := exec(tt.cli)
2485 require.Error(t, err)
2486 assert.Contains(t, err.Error(), tt.want)
2487 })
2488 }
2489}
Diagnostics8 git calls · 217 ms
CallStatusSizeTime0217 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 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 · hit3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=HIT git.response.duration_ms=3 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=3 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 · 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=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
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=2 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 · 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 · 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=202 git.response.cache=HIT git.response.duration_ms=3 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
fetch2009.8 KiB205 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=205 git.response.bytes=10028 git.response.cache=MISS git.response.duration_ms=205 git.fetch.wants=3994ff5bcd7bfe279806ebad92a8b83da2df7c54 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=10028 git.pkt.payload.max=10001 git.sideband.band1.bytes=10001 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
- a5e2c4c2fa47aedd
- Request
- 612e576a…
- 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