GitLabgitlab-org

cli

main
ply8 git calls220 ms105 KiB5 cachedprotocol v2
1829 lines79 KiBRaw
1//go:build !integration
3package checkout
5import (
6 "errors"
7 "fmt"
8 "io"
9 "net/url"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "strings"
14 "testing"
16 "github.com/stretchr/testify/assert"
17 "github.com/stretchr/testify/require"
18 "go.uber.org/mock/gomock"
20 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
21 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
23 "gitlab.com/gitlab-org/cli/internal/api"
24 "gitlab.com/gitlab-org/cli/internal/cmdutils"
25 "gitlab.com/gitlab-org/cli/internal/config"
26 "gitlab.com/gitlab-org/cli/internal/git"
27 git_testing "gitlab.com/gitlab-org/cli/internal/git/testing"
28 "gitlab.com/gitlab-org/cli/internal/glinstance"
29 "gitlab.com/gitlab-org/cli/internal/glrepo"
30 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
31 "gitlab.com/gitlab-org/cli/test"
34func setupTest(t *testing.T, testClient *gitlabtesting.TestClient, opts ...cmdtest.FactoryOption) func(string) (*test.CmdOut, error) {
35 t.Helper()
37 pu, _ := url.Parse("https://gitlab.com/OWNER/REPO.git")
39 defaultOpts := []cmdtest.FactoryOption{
40 cmdtest.WithGitLabClient(testClient.Client),
41 cmdtest.WithBranch("main"),
42 func(f *cmdtest.Factory) {
43 f.RemotesStub = func() (glrepo.Remotes, error) {
44 return glrepo.Remotes{
45 {
46 Remote: &git.Remote{
47 Name: "upstream",
48 Resolved: "base",
49 PushURL: pu,
50 },
51 Repo: glrepo.New("OWNER", "REPO", glinstance.DefaultHostname),
52 },
53 {
54 Remote: &git.Remote{
55 Name: "origin",
56 Resolved: "base",
57 PushURL: pu,
58 },
59 Repo: glrepo.New("monalisa", "REPO", glinstance.DefaultHostname),
60 },
61 }, nil
62 }
63 },
64 }
66 return cmdtest.SetupCmdForTest(t, NewCmdCheckout, false, append(defaultOpts, opts...)...)
69func TestMrCheckout(t *testing.T) {
70 t.Parallel()
71 t.Run("when a valid MR is checked out using MR id", func(t *testing.T) {
72 t.Parallel()
73 testClient := gitlabtesting.NewTestClient(t)
75 testClient.MockMergeRequests.EXPECT().
76 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
77 Return(&gitlab.MergeRequest{
78 BasicMergeRequest: gitlab.BasicMergeRequest{
79 ID: 123,
80 IID: 123,
81 ProjectID: 3,
82 SourceProjectID: 3,
83 SourceBranch: "feat-new-mr",
84 Title: "test mr title",
85 Description: "test mr description",
86 AllowCollaboration: false,
87 State: "opened",
88 SHA: "abc123",
89 },
90 }, nil, nil)
92 testClient.MockProjects.EXPECT().
93 GetProject(gomock.Any(), gomock.Any()).
94 Return(&gitlab.Project{
95 ID: 3,
96 PathWithNamespace: "OWNER/REPO",
97 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
98 }, nil, nil)
100 ctrl := gomock.NewController(t)
101 mockGit := git_testing.NewMockGitRunner(ctrl)
102 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
103 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
104 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
105 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
106 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
107 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
108 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
109 DoAndReturn(git.CheckoutStub("feat-new-mr"))
111 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
112 output, err := exec("123")
114 require.NoError(t, err)
115 assert.Contains(t, output.Stderr(), "Counting objects")
116 assert.Contains(t, output.Stderr(), "[new branch] refs/heads/feat-new-mr:feat-new-mr")
117 assert.Contains(t, output.Stderr(), "Switched to a new branch 'feat-new-mr'")
118 })
120 t.Run("when the API returns a repository URL that is not a valid remote", func(t *testing.T) {
121 t.Parallel()
122 testClient := gitlabtesting.NewTestClient(t)
124 testClient.MockMergeRequests.EXPECT().
125 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
126 Return(&gitlab.MergeRequest{
127 BasicMergeRequest: gitlab.BasicMergeRequest{
128 ID: 123,
129 IID: 123,
130 ProjectID: 3,
131 SourceProjectID: 3,
132 SourceBranch: "feat-new-mr",
133 State: "opened",
134 SHA: "abc123",
135 },
136 }, nil, nil)
138 testClient.MockProjects.EXPECT().
139 GetProject(gomock.Any(), gomock.Any()).
140 Return(&gitlab.Project{
141 ID: 3,
142 SSHURLToRepo: "--upload-pack=touch x",
143 HTTPURLToRepo: "--upload-pack=touch x",
144 }, nil, nil)
146 // No git expectations: any fetch or config call fails the test.
147 mockGit := git_testing.NewMockGitRunner(gomock.NewController(t))
149 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
150 _, err := exec("123")
152 require.Error(t, err)
153 assert.Contains(t, err.Error(), "--upload-pack=touch x")
154 })
156 t.Run("when the API returns a source branch that looks like a git option", func(t *testing.T) {
157 t.Parallel()
158 testClient := gitlabtesting.NewTestClient(t)
160 testClient.MockMergeRequests.EXPECT().
161 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
162 Return(&gitlab.MergeRequest{
163 BasicMergeRequest: gitlab.BasicMergeRequest{
164 ID: 123,
165 IID: 123,
166 ProjectID: 3,
167 SourceProjectID: 3,
168 SourceBranch: "--orphan=x",
169 State: "opened",
170 SHA: "abc123",
171 },
172 }, nil, nil)
174 mockGit := git_testing.NewMockGitRunner(gomock.NewController(t))
176 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
177 _, err := exec("123")
179 require.EqualError(t, err, `invalid branch name "--orphan=x"`)
180 })
182 t.Run("when a remote matches the MR project, its name is used for the fetch and the branch remote", func(t *testing.T) {
183 t.Parallel()
184 testClient := gitlabtesting.NewTestClient(t)
186 testClient.MockMergeRequests.EXPECT().
187 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
188 Return(&gitlab.MergeRequest{
189 BasicMergeRequest: gitlab.BasicMergeRequest{
190 ID: 123,
191 IID: 123,
192 ProjectID: 3,
193 SourceProjectID: 3,
194 SourceBranch: "feat-new-mr",
195 State: "opened",
196 SHA: "abc123",
197 },
198 }, nil, nil)
200 testClient.MockProjects.EXPECT().
201 GetProject(gomock.Any(), gomock.Any()).
202 Return(&gitlab.Project{
203 ID: 3,
204 PathWithNamespace: "monalisa/REPO",
205 SSHURLToRepo: "git@gitlab.com:monalisa/REPO.git",
206 }, nil, nil)
208 ctrl := gomock.NewController(t)
209 mockGit := git_testing.NewMockGitRunner(ctrl)
210 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
211 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
212 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "origin", "refs/heads/feat-new-mr:feat-new-mr").
213 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
214 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "origin").Return("", nil)
215 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
216 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
217 DoAndReturn(git.CheckoutStub("feat-new-mr"))
219 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
220 _, err := exec("123")
222 require.NoError(t, err)
223 })
225 t.Run("when no remote matches the MR project, the project URL is used for the fetch and the branch remote", func(t *testing.T) {
226 t.Parallel()
227 testClient := gitlabtesting.NewTestClient(t)
229 testClient.MockMergeRequests.EXPECT().
230 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
231 Return(&gitlab.MergeRequest{
232 BasicMergeRequest: gitlab.BasicMergeRequest{
233 ID: 123,
234 IID: 123,
235 ProjectID: 3,
236 SourceProjectID: 3,
237 SourceBranch: "feat-new-mr",
238 State: "opened",
239 SHA: "abc123",
240 },
241 }, nil, nil)
243 testClient.MockProjects.EXPECT().
244 GetProject(gomock.Any(), gomock.Any()).
245 Return(&gitlab.Project{
246 ID: 3,
247 PathWithNamespace: "contributor/REPO",
248 SSHURLToRepo: "git@gitlab.com:contributor/REPO.git",
249 }, nil, nil)
251 ctrl := gomock.NewController(t)
252 mockGit := git_testing.NewMockGitRunner(ctrl)
253 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
254 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
255 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "git@gitlab.com:contributor/REPO.git", "refs/heads/feat-new-mr:feat-new-mr").
256 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
257 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "git@gitlab.com:contributor/REPO.git").Return("", nil)
258 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
259 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
260 DoAndReturn(git.CheckoutStub("feat-new-mr"))
262 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
263 _, err := exec("123")
265 require.NoError(t, err)
266 })
268 t.Run("when the remotes cannot be read, the project URL is used for the fetch and the branch remote", func(t *testing.T) {
269 t.Parallel()
270 testClient := gitlabtesting.NewTestClient(t)
272 testClient.MockMergeRequests.EXPECT().
273 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
274 Return(&gitlab.MergeRequest{
275 BasicMergeRequest: gitlab.BasicMergeRequest{
276 ID: 123,
277 IID: 123,
278 ProjectID: 3,
279 SourceProjectID: 3,
280 SourceBranch: "feat-new-mr",
281 State: "opened",
282 SHA: "abc123",
283 },
284 }, nil, nil)
286 testClient.MockProjects.EXPECT().
287 GetProject(gomock.Any(), gomock.Any()).
288 Return(&gitlab.Project{
289 ID: 3,
290 PathWithNamespace: "OWNER/REPO",
291 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
292 }, nil, nil)
294 ctrl := gomock.NewController(t)
295 mockGit := git_testing.NewMockGitRunner(ctrl)
296 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
297 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
298 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "git@gitlab.com:OWNER/REPO.git", "refs/heads/feat-new-mr:feat-new-mr").
299 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
300 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "git@gitlab.com:OWNER/REPO.git").Return("", nil)
301 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
302 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
303 DoAndReturn(git.CheckoutStub("feat-new-mr"))
305 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit), func(f *cmdtest.Factory) {
306 f.RemotesStub = func() (glrepo.Remotes, error) {
307 return nil, errors.New("not a git repository")
308 }
309 })
310 _, err := exec("123")
312 require.NoError(t, err)
313 })
315 t.Run("when a valid MR comes from a forked private project", func(t *testing.T) {
316 t.Parallel()
317 testClient := gitlabtesting.NewTestClient(t)
319 testClient.MockMergeRequests.EXPECT().
320 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
321 Return(&gitlab.MergeRequest{
322 BasicMergeRequest: gitlab.BasicMergeRequest{
323 ID: 123,
324 IID: 123,
325 ProjectID: 3,
326 SourceProjectID: 3,
327 TargetProjectID: 4,
328 SourceBranch: "feat-new-mr",
329 Title: "test mr title",
330 Description: "test mr description",
331 AllowCollaboration: false,
332 State: "opened",
333 SHA: "abc123",
334 },
335 }, nil, nil)
337 testClient.MockProjects.EXPECT().
338 GetProject(gomock.Any(), gomock.Any()).
339 Return(nil, nil, &gitlab.ErrorResponse{Message: "404 Project Not Found"})
341 testClient.MockProjects.EXPECT().
342 GetProject(gomock.Any(), gomock.Any()).
343 Return(&gitlab.Project{
344 ID: 4,
345 PathWithNamespace: "OWNER/REPO",
346 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
347 }, nil, nil)
349 ctrl := gomock.NewController(t)
350 mockGit := git_testing.NewMockGitRunner(ctrl)
351 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
352 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
353 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "git@gitlab.com:OWNER/REPO.git", "refs/merge-requests/123/head:feat-new-mr").
354 DoAndReturn(git.FetchStub("refs/merge-requests/123/head:feat-new-mr"))
355 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "git@gitlab.com:OWNER/REPO.git").Return("", nil)
356 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/merge-requests/123/head").Return("", nil)
357 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
358 DoAndReturn(git.CheckoutStub("feat-new-mr"))
360 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
361 output, err := exec("123")
363 require.NoError(t, err)
364 assert.Contains(t, output.Stderr(), "[new branch] refs/merge-requests/123/head:feat-new-mr")
365 assert.Contains(t, output.Stderr(), "Switched to a new branch 'feat-new-mr'")
366 })
368 t.Run("when a valid MR is checked out using MR id and specifying branch", func(t *testing.T) {
369 t.Parallel()
370 testClient := gitlabtesting.NewTestClient(t)
372 testClient.MockMergeRequests.EXPECT().
373 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
374 Return(&gitlab.MergeRequest{
375 BasicMergeRequest: gitlab.BasicMergeRequest{
376 ID: 123,
377 IID: 123,
378 ProjectID: 3,
379 SourceProjectID: 4,
380 SourceBranch: "feat-new-mr",
381 Title: "test mr title",
382 Description: "test mr description",
383 AllowCollaboration: true,
384 State: "opened",
385 SHA: "abc123",
386 },
387 }, nil, nil)
389 testClient.MockProjects.EXPECT().
390 GetProject(gomock.Any(), gomock.Any()).
391 Return(&gitlab.Project{
392 ID: 3,
393 PathWithNamespace: "FORK_OWNER/REPO",
394 SSHURLToRepo: "git@gitlab.com:FORK_OWNER/REPO.git",
395 }, nil, nil)
397 ctrl := gomock.NewController(t)
398 mockGit := git_testing.NewMockGitRunner(ctrl)
399 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/foo").Return("", errors.New("not found"))
400 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
401 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "git@gitlab.com:FORK_OWNER/REPO.git", "refs/heads/feat-new-mr:foo").
402 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:foo"))
403 mockGit.EXPECT().Git("config", "branch.foo.remote", "git@gitlab.com:FORK_OWNER/REPO.git").Return("", nil)
404 mockGit.EXPECT().Git("config", "branch.foo.pushRemote", "git@gitlab.com:FORK_OWNER/REPO.git").Return("", nil)
405 mockGit.EXPECT().Git("config", "branch.foo.merge", "refs/heads/feat-new-mr").Return("", nil)
406 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "foo").
407 DoAndReturn(git.CheckoutStub("foo"))
409 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
410 output, err := exec("123 --branch foo")
412 require.NoError(t, err)
413 assert.Contains(t, output.Stderr(), "[new branch] refs/heads/feat-new-mr:foo")
414 assert.Contains(t, output.Stderr(), "Switched to a new branch 'foo'")
415 })
417 t.Run("when initial fetch fails but retry succeeds", func(t *testing.T) {
418 t.Parallel()
419 testClient := gitlabtesting.NewTestClient(t)
421 testClient.MockMergeRequests.EXPECT().
422 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
423 Return(&gitlab.MergeRequest{
424 BasicMergeRequest: gitlab.BasicMergeRequest{
425 ID: 123,
426 IID: 123,
427 ProjectID: 3,
428 SourceProjectID: 3,
429 SourceBranch: "feat-new-mr",
430 State: "opened",
431 SHA: "abc123",
432 },
433 }, nil, nil)
435 testClient.MockProjects.EXPECT().
436 GetProject(gomock.Any(), gomock.Any()).
437 Return(&gitlab.Project{
438 ID: 3,
439 PathWithNamespace: "OWNER/REPO",
440 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
441 }, nil, nil)
443 ctrl := gomock.NewController(t)
444 mockGit := git_testing.NewMockGitRunner(ctrl)
445 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
446 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "couldn't find remote ref"))
447 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
448 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
449 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found")).Times(2)
450 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
451 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
452 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
453 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
454 DoAndReturn(git.CheckoutStub("feat-new-mr"))
456 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
457 output, err := exec("123")
459 require.NoError(t, err)
460 assert.Contains(t, output.Stderr(), "fetch attempt refs/heads/feat-new-mr:feat-new-mr failed")
461 assert.Contains(t, output.Stderr(), "[new branch] refs/heads/feat-new-mr")
462 assert.Contains(t, output.Stderr(), "Switched to a new branch 'feat-new-mr'")
463 })
465 t.Run("when fetch fails completely", func(t *testing.T) {
466 t.Parallel()
467 testClient := gitlabtesting.NewTestClient(t)
469 testClient.MockMergeRequests.EXPECT().
470 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
471 Return(&gitlab.MergeRequest{
472 BasicMergeRequest: gitlab.BasicMergeRequest{
473 ID: 123,
474 IID: 123,
475 ProjectID: 3,
476 SourceProjectID: 3,
477 SourceBranch: "feat-new-mr",
478 State: "opened",
479 SHA: "abc123",
480 },
481 }, nil, nil)
483 testClient.MockProjects.EXPECT().
484 GetProject(gomock.Any(), gomock.Any()).
485 Return(&gitlab.Project{
486 ID: 3,
487 PathWithNamespace: "OWNER/REPO",
488 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
489 }, nil, nil)
491 ctrl := gomock.NewController(t)
492 mockGit := git_testing.NewMockGitRunner(ctrl)
493 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
494 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
495 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
496 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "fetch failed"))
497 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
498 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr", "fetch failed"))
500 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
501 output, err := exec("123")
503 require.Error(t, err)
504 assert.Contains(t, err.Error(), "fetch failed")
505 assert.Contains(t, output.Stderr(), "fetch attempt refs/heads/feat-new-mr:feat-new-mr failed")
506 assert.Contains(t, output.Stderr(), "fetch attempt refs/heads/feat-new-mr failed")
507 assert.Empty(t, output.String())
508 })
510 t.Run("when checkout fails", func(t *testing.T) {
511 t.Parallel()
512 testClient := gitlabtesting.NewTestClient(t)
514 testClient.MockMergeRequests.EXPECT().
515 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
516 Return(&gitlab.MergeRequest{
517 BasicMergeRequest: gitlab.BasicMergeRequest{
518 ID: 123,
519 IID: 123,
520 ProjectID: 3,
521 SourceProjectID: 3,
522 SourceBranch: "feat-new-mr",
523 State: "opened",
524 SHA: "abc123",
525 },
526 }, nil, nil)
528 testClient.MockProjects.EXPECT().
529 GetProject(gomock.Any(), gomock.Any()).
530 Return(&gitlab.Project{
531 ID: 3,
532 PathWithNamespace: "OWNER/REPO",
533 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
534 }, nil, nil)
536 ctrl := gomock.NewController(t)
537 mockGit := git_testing.NewMockGitRunner(ctrl)
538 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
539 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
540 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
541 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
542 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
543 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
544 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
545 DoAndReturn(git.FailingCheckoutStub("feat-new-mr", "pathspec 'feat-new-mr' did not match"))
547 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
548 output, err := exec("123")
550 require.Error(t, err)
551 assert.Contains(t, err.Error(), "could not checkout branch")
552 assert.Contains(t, output.Stderr(), "[new branch] refs/heads/feat-new-mr:feat-new-mr")
553 assert.Contains(t, output.Stderr(), "error: pathspec 'feat-new-mr' did not match")
554 assert.Empty(t, output.String())
555 })
557 t.Run("when git config fails", func(t *testing.T) {
558 t.Parallel()
559 testClient := gitlabtesting.NewTestClient(t)
561 testClient.MockMergeRequests.EXPECT().
562 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
563 Return(&gitlab.MergeRequest{
564 BasicMergeRequest: gitlab.BasicMergeRequest{
565 ID: 123,
566 IID: 123,
567 ProjectID: 3,
568 SourceProjectID: 3,
569 SourceBranch: "feat-new-mr",
570 State: "opened",
571 SHA: "abc123",
572 },
573 }, nil, nil)
575 testClient.MockProjects.EXPECT().
576 GetProject(gomock.Any(), gomock.Any()).
577 Return(&gitlab.Project{
578 ID: 3,
579 PathWithNamespace: "OWNER/REPO",
580 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
581 }, nil, nil)
583 ctrl := gomock.NewController(t)
584 mockGit := git_testing.NewMockGitRunner(ctrl)
585 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
586 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
587 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
588 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
589 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").
590 Return("", errors.New("could not set config"))
592 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
593 output, err := exec("123")
595 require.Error(t, err)
596 assert.Contains(t, err.Error(), "could not set config")
597 assert.Contains(t, output.Stderr(), "[new branch] refs/heads/feat-new-mr:feat-new-mr")
598 assert.Empty(t, output.String())
599 })
601 t.Run("when the checked-out branch is behind the merge request, fast-forwards", func(t *testing.T) {
602 t.Parallel()
603 testClient := newDivergenceTestClient(t)
605 ctrl := gomock.NewController(t)
606 mockGit := git_testing.NewMockGitRunner(ctrl)
607 // git refuses to fetch into the branch that is checked out, whatever the history.
608 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
609 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "refusing to fetch into branch 'refs/heads/feat-new-mr' checked out at '/repo'"))
610 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
611 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
612 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old\n", nil).Times(2)
613 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new\n", nil)
614 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", nil)
615 mockGit.EXPECT().Git("symbolic-ref", "--quiet", "--short", "HEAD").Return("feat-new-mr\n", nil)
616 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "merge", "--ff-only", "FETCH_HEAD").Return(nil)
617 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
618 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
619 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
620 DoAndReturn(git.CheckoutStub("feat-new-mr"))
622 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
623 _, err := exec("123")
625 require.NoError(t, err)
626 })
628 t.Run("when another branch is checked out and the local branch is behind, moves it", func(t *testing.T) {
629 t.Parallel()
630 testClient := newDivergenceTestClient(t)
632 ctrl := gomock.NewController(t)
633 mockGit := git_testing.NewMockGitRunner(ctrl)
634 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
635 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "non-fast-forward"))
636 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
637 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
638 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old\n", nil).Times(2)
639 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new\n", nil)
640 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", nil)
641 mockGit.EXPECT().Git("symbolic-ref", "--quiet", "--short", "HEAD").Return("main\n", nil)
642 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "branch", "-f", "feat-new-mr", "FETCH_HEAD").Return(nil)
643 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
644 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
645 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
646 DoAndReturn(git.CheckoutStub("feat-new-mr"))
648 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
649 _, err := exec("123")
651 require.NoError(t, err)
652 })
654 t.Run("when the checked-out branch is behind but the working tree blocks the fast-forward, fails", func(t *testing.T) {
655 t.Parallel()
656 testClient := newDivergenceTestClient(t)
658 ctrl := gomock.NewController(t)
659 mockGit := git_testing.NewMockGitRunner(ctrl)
660 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
661 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "refusing to fetch into branch 'refs/heads/feat-new-mr' checked out at '/repo'"))
662 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
663 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
664 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old\n", nil).Times(2)
665 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new\n", nil)
666 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", nil)
667 mockGit.EXPECT().Git("symbolic-ref", "--quiet", "--short", "HEAD").Return("feat-new-mr\n", nil)
668 // git refuses the merge because a local modification would be overwritten;
669 // the mock is strict, so no config or checkout call may follow.
670 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "merge", "--ff-only", "FETCH_HEAD").
671 DoAndReturn(func(_, stderr io.Writer, _ ...string) error {
672 fmt.Fprintln(stderr, "error: Your local changes to the following files would be overwritten by merge:\n\tfile.go")
673 return errors.New("exit status 1")
674 })
676 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
677 _, err := exec("123")
679 require.Error(t, err)
680 assert.Contains(t, err.Error(), `could not fast-forward local branch "feat-new-mr"`)
681 assert.ErrorContains(t, err, "exit status 1")
682 })
684 t.Run("when another branch is checked out and moving the local branch fails", func(t *testing.T) {
685 t.Parallel()
686 testClient := newDivergenceTestClient(t)
688 ctrl := gomock.NewController(t)
689 mockGit := git_testing.NewMockGitRunner(ctrl)
690 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
691 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "non-fast-forward"))
692 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
693 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
694 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old\n", nil).Times(2)
695 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new\n", nil)
696 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", nil)
697 mockGit.EXPECT().Git("symbolic-ref", "--quiet", "--short", "HEAD").Return("main\n", nil)
698 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "branch", "-f", "feat-new-mr", "FETCH_HEAD").
699 Return(errors.New("exit status 128"))
701 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
702 _, err := exec("123")
704 require.Error(t, err)
705 assert.Contains(t, err.Error(), `could not fast-forward local branch "feat-new-mr"`)
706 assert.ErrorContains(t, err, "exit status 128")
707 })
709 t.Run("when diverged without --force and non-interactive", func(t *testing.T) {
710 t.Parallel()
711 testClient := newDivergenceTestClient(t)
713 ctrl := gomock.NewController(t)
714 mockGit := git_testing.NewMockGitRunner(ctrl)
715 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
716 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "non-fast-forward"))
717 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
718 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
719 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old\n", nil).Times(2)
720 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new\n", nil)
721 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", errors.New("exit status 1"))
722 mockGit.EXPECT().Git("symbolic-ref", "--quiet", "--short", "HEAD").Return("main\n", nil)
724 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
725 _, err := exec("123")
727 require.Error(t, err)
728 assert.Contains(t, err.Error(), "--force")
729 var fe cmdutils.FlagError
730 require.ErrorAs(t, err, &fe)
731 })
733 t.Run("when --force, on target, clean", func(t *testing.T) {
734 t.Parallel()
735 testClient := newDivergenceTestClient(t)
737 ctrl := gomock.NewController(t)
738 mockGit := git_testing.NewMockGitRunner(ctrl)
739 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
740 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "non-fast-forward"))
741 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
742 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
743 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old\n", nil).Times(2)
744 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new\n", nil)
745 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", errors.New("exit status 1"))
746 mockGit.EXPECT().Git("symbolic-ref", "--quiet", "--short", "HEAD").Return("feat-new-mr\n", nil)
747 mockGit.EXPECT().Git("diff", "--name-only", "HEAD").Return("", nil)
748 mockGit.EXPECT().Git("ls-files", "--others", "--exclude-standard").Return("", nil)
749 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "reset", "--hard", "FETCH_HEAD").Return(nil)
750 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
751 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
752 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
753 DoAndReturn(git.CheckoutStub("feat-new-mr"))
755 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
756 _, err := exec("123 --force")
758 require.NoError(t, err)
759 })
761 t.Run("when --force, on target, tracked modifications refuse", func(t *testing.T) {
762 t.Parallel()
763 testClient := newDivergenceTestClient(t)
765 ctrl := gomock.NewController(t)
766 mockGit := git_testing.NewMockGitRunner(ctrl)
767 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
768 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "non-fast-forward"))
769 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
770 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
771 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old\n", nil).Times(2)
772 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new\n", nil)
773 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", errors.New("exit status 1"))
774 mockGit.EXPECT().Git("symbolic-ref", "--quiet", "--short", "HEAD").Return("feat-new-mr\n", nil)
775 mockGit.EXPECT().Git("diff", "--name-only", "HEAD").Return("file.go\n", nil)
777 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
778 _, err := exec("123 --force")
780 require.Error(t, err)
781 assert.Contains(t, err.Error(), "changes that would be lost")
782 })
784 t.Run("when --force, on target, untracked file conflicts with incoming", func(t *testing.T) {
785 t.Parallel()
786 testClient := newDivergenceTestClient(t)
788 ctrl := gomock.NewController(t)
789 mockGit := git_testing.NewMockGitRunner(ctrl)
790 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
791 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "non-fast-forward"))
792 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
793 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
794 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old\n", nil).Times(2)
795 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new\n", nil)
796 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", errors.New("exit status 1"))
797 mockGit.EXPECT().Git("symbolic-ref", "--quiet", "--short", "HEAD").Return("feat-new-mr\n", nil)
798 mockGit.EXPECT().Git("diff", "--name-only", "HEAD").Return("", nil)
799 mockGit.EXPECT().Git("ls-files", "--others", "--exclude-standard").Return("local.txt\n", nil)
800 mockGit.EXPECT().Git("ls-tree", "-r", "--name-only", "new").Return("main.txt\nlocal.txt\n", nil)
802 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
803 _, err := exec("123 --force")
805 require.Error(t, err)
806 assert.Contains(t, err.Error(), "changes that would be lost")
807 })
809 t.Run("when --force, on target, unrelated untracked file allowed", func(t *testing.T) {
810 t.Parallel()
811 testClient := newDivergenceTestClient(t)
813 ctrl := gomock.NewController(t)
814 mockGit := git_testing.NewMockGitRunner(ctrl)
815 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
816 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "non-fast-forward"))
817 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
818 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
819 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old\n", nil).Times(2)
820 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new\n", nil)
821 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", errors.New("exit status 1"))
822 mockGit.EXPECT().Git("symbolic-ref", "--quiet", "--short", "HEAD").Return("feat-new-mr\n", nil)
823 mockGit.EXPECT().Git("diff", "--name-only", "HEAD").Return("", nil)
824 mockGit.EXPECT().Git("ls-files", "--others", "--exclude-standard").Return("notes.txt\n", nil)
825 mockGit.EXPECT().Git("ls-tree", "-r", "--name-only", "new").Return("main.txt\nfeature.go\n", nil)
826 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "reset", "--hard", "FETCH_HEAD").Return(nil)
827 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
828 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
829 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
830 DoAndReturn(git.CheckoutStub("feat-new-mr"))
832 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
833 _, err := exec("123 --force")
835 require.NoError(t, err)
836 })
838 t.Run("when --force, not on target", func(t *testing.T) {
839 t.Parallel()
840 testClient := newDivergenceTestClient(t)
842 ctrl := gomock.NewController(t)
843 mockGit := git_testing.NewMockGitRunner(ctrl)
844 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
845 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "non-fast-forward"))
846 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr").
847 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
848 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old\n", nil).Times(2)
849 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new\n", nil)
850 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", errors.New("exit status 1"))
851 mockGit.EXPECT().Git("symbolic-ref", "--quiet", "--short", "HEAD").Return("main\n", nil)
852 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "branch", "-f", "feat-new-mr", "FETCH_HEAD").Return(nil)
853 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
854 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
855 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
856 DoAndReturn(git.CheckoutStub("feat-new-mr"))
858 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
859 _, err := exec("123 --force")
861 require.NoError(t, err)
862 })
864 t.Run("when local branch already matches MR head, fetch is skipped", func(t *testing.T) {
865 t.Parallel()
866 testClient := gitlabtesting.NewTestClient(t)
868 testClient.MockMergeRequests.EXPECT().
869 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
870 Return(&gitlab.MergeRequest{
871 BasicMergeRequest: gitlab.BasicMergeRequest{
872 ID: 123,
873 IID: 123,
874 ProjectID: 3,
875 SourceProjectID: 3,
876 SourceBranch: "feat-new-mr",
877 State: "opened",
878 SHA: "abc123",
879 },
880 }, nil, nil)
882 testClient.MockProjects.EXPECT().
883 GetProject(gomock.Any(), gomock.Any()).
884 Return(&gitlab.Project{
885 ID: 3,
886 PathWithNamespace: "OWNER/REPO",
887 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
888 }, nil, nil)
890 ctrl := gomock.NewController(t)
891 mockGit := git_testing.NewMockGitRunner(ctrl)
892 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("abc123\n", nil)
893 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", gomock.Any(), gomock.Any()).Times(0)
894 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
895 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
896 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
897 DoAndReturn(git.CheckoutStub("feat-new-mr"))
899 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
900 output, err := exec("123")
902 require.NoError(t, err)
903 assert.Contains(t, output.String(), "already at merge request head")
904 assert.Contains(t, output.Stderr(), "Switched to a new branch 'feat-new-mr'")
905 })
907 t.Run("when local branch exists but at a different SHA, fetch still happens", func(t *testing.T) {
908 t.Parallel()
909 testClient := gitlabtesting.NewTestClient(t)
911 testClient.MockMergeRequests.EXPECT().
912 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
913 Return(&gitlab.MergeRequest{
914 BasicMergeRequest: gitlab.BasicMergeRequest{
915 ID: 123,
916 IID: 123,
917 ProjectID: 3,
918 SourceProjectID: 3,
919 SourceBranch: "feat-new-mr",
920 State: "opened",
921 SHA: "abc123",
922 },
923 }, nil, nil)
925 testClient.MockProjects.EXPECT().
926 GetProject(gomock.Any(), gomock.Any()).
927 Return(&gitlab.Project{
928 ID: 3,
929 PathWithNamespace: "OWNER/REPO",
930 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
931 }, nil, nil)
933 ctrl := gomock.NewController(t)
934 mockGit := git_testing.NewMockGitRunner(ctrl)
935 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("stale000\n", nil)
936 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
937 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
938 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
939 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
940 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
941 DoAndReturn(git.CheckoutStub("feat-new-mr"))
943 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
944 output, err := exec("123")
946 require.NoError(t, err)
947 assert.Contains(t, output.Stderr(), "[new branch] refs/heads/feat-new-mr:feat-new-mr")
948 assert.NotContains(t, output.String(), "skipping fetch")
949 })
951 t.Run("when commit is already local but branch is missing, branch is created and fetch is skipped", func(t *testing.T) {
952 t.Parallel()
953 testClient := gitlabtesting.NewTestClient(t)
955 testClient.MockMergeRequests.EXPECT().
956 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
957 Return(&gitlab.MergeRequest{
958 BasicMergeRequest: gitlab.BasicMergeRequest{
959 ID: 123,
960 IID: 123,
961 ProjectID: 3,
962 SourceProjectID: 3,
963 SourceBranch: "feat-new-mr",
964 State: "opened",
965 SHA: "abc123",
966 },
967 }, nil, nil)
969 testClient.MockProjects.EXPECT().
970 GetProject(gomock.Any(), gomock.Any()).
971 Return(&gitlab.Project{
972 ID: 3,
973 PathWithNamespace: "OWNER/REPO",
974 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
975 }, nil, nil)
977 ctrl := gomock.NewController(t)
978 mockGit := git_testing.NewMockGitRunner(ctrl)
979 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
980 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("abc123\n", nil)
981 mockGit.EXPECT().Git("branch", "feat-new-mr", "abc123").Return("", nil)
982 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", gomock.Any(), gomock.Any()).Times(0)
983 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
984 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
985 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
986 DoAndReturn(git.CheckoutStub("feat-new-mr"))
988 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
989 output, err := exec("123")
991 require.NoError(t, err)
992 assert.Contains(t, output.String(), "Created branch")
993 assert.Contains(t, output.Stderr(), "Switched to a new branch 'feat-new-mr'")
994 })
996 t.Run("when branch and commit are both missing, fetch happens", func(t *testing.T) {
997 t.Parallel()
998 testClient := gitlabtesting.NewTestClient(t)
1000 testClient.MockMergeRequests.EXPECT().
1001 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
1002 Return(&gitlab.MergeRequest{
1003 BasicMergeRequest: gitlab.BasicMergeRequest{
1004 ID: 123,
1005 IID: 123,
1006 ProjectID: 3,
1007 SourceProjectID: 3,
1008 SourceBranch: "feat-new-mr",
1009 State: "opened",
1010 SHA: "abc123",
1011 },
1012 }, nil, nil)
1014 testClient.MockProjects.EXPECT().
1015 GetProject(gomock.Any(), gomock.Any()).
1016 Return(&gitlab.Project{
1017 ID: 3,
1018 PathWithNamespace: "OWNER/REPO",
1019 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
1020 }, nil, nil)
1022 ctrl := gomock.NewController(t)
1023 mockGit := git_testing.NewMockGitRunner(ctrl)
1024 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
1025 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
1026 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
1027 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
1028 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
1029 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
1030 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
1031 DoAndReturn(git.CheckoutStub("feat-new-mr"))
1033 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1034 output, err := exec("123")
1036 require.NoError(t, err)
1037 assert.Contains(t, output.Stderr(), "[new branch] refs/heads/feat-new-mr:feat-new-mr")
1038 assert.NotContains(t, output.String(), "skipping fetch")
1039 })
1041 t.Run("when merge request has no head SHA", func(t *testing.T) {
1042 t.Parallel()
1043 testClient := gitlabtesting.NewTestClient(t)
1045 testClient.MockMergeRequests.EXPECT().
1046 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
1047 Return(&gitlab.MergeRequest{
1048 BasicMergeRequest: gitlab.BasicMergeRequest{
1049 ID: 123,
1050 IID: 123,
1051 SourceBranch: "feat-new-mr",
1052 State: "opened",
1053 },
1054 }, nil, nil)
1056 ctrl := gomock.NewController(t)
1057 mockGit := git_testing.NewMockGitRunner(ctrl)
1059 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1060 _, err := exec("123")
1062 require.Error(t, err)
1063 assert.Contains(t, err.Error(), "has no head commit")
1064 })
1067func newDivergenceTestClient(t *testing.T) *gitlabtesting.TestClient {
1068 t.Helper()
1069 testClient := gitlabtesting.NewTestClient(t)
1070 testClient.MockMergeRequests.EXPECT().
1071 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
1072 Return(&gitlab.MergeRequest{
1073 BasicMergeRequest: gitlab.BasicMergeRequest{
1074 ID: 123,
1075 IID: 123,
1076 ProjectID: 3,
1077 SourceProjectID: 3,
1078 SourceBranch: "feat-new-mr",
1079 State: "opened",
1080 SHA: "abc123",
1081 },
1082 }, nil, nil)
1083 testClient.MockProjects.EXPECT().
1084 GetProject(gomock.Any(), gomock.Any()).
1085 Return(&gitlab.Project{
1086 ID: 3,
1087 PathWithNamespace: "OWNER/REPO",
1088 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
1089 }, nil, nil)
1090 return testClient
1093func TestUnsafeToReset(t *testing.T) {
1094 t.Parallel()
1095 boom := errors.New("boom")
1096 cases := []struct {
1097 name string
1098 mocks func(m *git_testing.MockGitRunnerMockRecorder)
1099 wantBlocked bool
1100 wantErr error
1101 }{
1103 name: "clean tree",
1104 mocks: func(m *git_testing.MockGitRunnerMockRecorder) {
1105 m.Git("diff", "--name-only", "HEAD").Return("", nil)
1106 m.Git("ls-files", "--others", "--exclude-standard").Return("", nil)
1107 },
1108 },
1110 name: "tracked diff single file",
1111 mocks: func(m *git_testing.MockGitRunnerMockRecorder) {
1112 m.Git("diff", "--name-only", "HEAD").Return("file.go\n", nil)
1113 },
1114 wantBlocked: true,
1115 },
1117 name: "tracked diff multiple files",
1118 mocks: func(m *git_testing.MockGitRunnerMockRecorder) {
1119 m.Git("diff", "--name-only", "HEAD").Return("a.go\nb.go\n", nil)
1120 },
1121 wantBlocked: true,
1122 },
1124 name: "unrelated untracked only",
1125 mocks: func(m *git_testing.MockGitRunnerMockRecorder) {
1126 m.Git("diff", "--name-only", "HEAD").Return("", nil)
1127 m.Git("ls-files", "--others", "--exclude-standard").Return("notes.txt\n", nil)
1128 m.Git("ls-tree", "-r", "--name-only", "new").Return("main.txt\nfeature.go\n", nil)
1129 },
1130 },
1132 name: "conflicting untracked",
1133 mocks: func(m *git_testing.MockGitRunnerMockRecorder) {
1134 m.Git("diff", "--name-only", "HEAD").Return("", nil)
1135 m.Git("ls-files", "--others", "--exclude-standard").Return("conflict.txt\n", nil)
1136 m.Git("ls-tree", "-r", "--name-only", "new").Return("main.txt\nconflict.txt\n", nil)
1137 },
1138 wantBlocked: true,
1139 },
1141 name: "multiple untracked one conflicts",
1142 mocks: func(m *git_testing.MockGitRunnerMockRecorder) {
1143 m.Git("diff", "--name-only", "HEAD").Return("", nil)
1144 m.Git("ls-files", "--others", "--exclude-standard").Return("notes.txt\nconflict.txt\n", nil)
1145 m.Git("ls-tree", "-r", "--name-only", "new").Return("main.txt\nconflict.txt\n", nil)
1146 },
1147 wantBlocked: true,
1148 },
1150 name: "trailing blank lines parsed",
1151 mocks: func(m *git_testing.MockGitRunnerMockRecorder) {
1152 m.Git("diff", "--name-only", "HEAD").Return("", nil)
1153 m.Git("ls-files", "--others", "--exclude-standard").Return("notes.txt\n\n", nil)
1154 m.Git("ls-tree", "-r", "--name-only", "new").Return("main.txt\n\n", nil)
1155 },
1156 },
1158 name: "diff errors propagate",
1159 mocks: func(m *git_testing.MockGitRunnerMockRecorder) {
1160 m.Git("diff", "--name-only", "HEAD").Return("", boom)
1161 },
1162 wantErr: boom,
1163 },
1165 name: "ls-files errors propagate",
1166 mocks: func(m *git_testing.MockGitRunnerMockRecorder) {
1167 m.Git("diff", "--name-only", "HEAD").Return("", nil)
1168 m.Git("ls-files", "--others", "--exclude-standard").Return("", boom)
1169 },
1170 wantErr: boom,
1171 },
1173 name: "ls-tree errors propagate",
1174 mocks: func(m *git_testing.MockGitRunnerMockRecorder) {
1175 m.Git("diff", "--name-only", "HEAD").Return("", nil)
1176 m.Git("ls-files", "--others", "--exclude-standard").Return("foo.txt\n", nil)
1177 m.Git("ls-tree", "-r", "--name-only", "new").Return("", boom)
1178 },
1179 wantErr: boom,
1180 },
1183 for _, tc := range cases {
1184 t.Run(tc.name, func(t *testing.T) {
1185 t.Parallel()
1186 ctrl := gomock.NewController(t)
1187 mockGit := git_testing.NewMockGitRunner(ctrl)
1188 tc.mocks(mockGit.EXPECT())
1190 o := &options{gr: mockGit}
1191 got, err := o.unsafeToReset("", "new")
1193 if tc.wantErr != nil {
1194 require.ErrorIs(t, err, tc.wantErr)
1195 } else {
1196 require.NoError(t, err)
1198 assert.Equal(t, tc.wantBlocked, got)
1199 })
1203func TestMrCheckout_SetUpstreamTo(t *testing.T) {
1204 t.Parallel()
1205 testClient := gitlabtesting.NewTestClient(t)
1207 testClient.MockMergeRequests.EXPECT().
1208 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
1209 Return(&gitlab.MergeRequest{
1210 BasicMergeRequest: gitlab.BasicMergeRequest{
1211 ID: 123,
1212 IID: 123,
1213 ProjectID: 3,
1214 SourceProjectID: 3,
1215 SourceBranch: "feat-new-mr",
1216 State: "opened",
1217 SHA: "abc123",
1218 },
1219 }, nil, nil)
1221 testClient.MockProjects.EXPECT().
1222 GetProject(gomock.Any(), gomock.Any()).
1223 Return(&gitlab.Project{
1224 ID: 3,
1225 PathWithNamespace: "OWNER/REPO",
1226 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
1227 }, nil, nil)
1229 ctrl := gomock.NewController(t)
1230 mockGit := git_testing.NewMockGitRunner(ctrl)
1231 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
1232 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
1233 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "upstream", "refs/heads/feat-new-mr:feat-new-mr").
1234 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
1235 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "upstream").Return("", nil)
1236 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
1237 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
1238 DoAndReturn(git.CheckoutStub("feat-new-mr"))
1239 mockGit.EXPECT().Git("branch", "--set-upstream-to", "upstream/main", "feat-new-mr").Return("", nil)
1241 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1242 output, err := exec("123 --set-upstream-to upstream/main")
1244 require.NoError(t, err)
1245 assert.Contains(t, output.Stderr(), "[new branch] refs/heads/feat-new-mr:feat-new-mr")
1246 assert.Contains(t, output.Stderr(), "Switched to a new branch 'feat-new-mr'")
1249func TestMrCheckout_Worktree(t *testing.T) {
1250 t.Parallel()
1252 newTestClient := func(t *testing.T) *gitlabtesting.TestClient {
1253 t.Helper()
1254 testClient := gitlabtesting.NewTestClient(t)
1256 testClient.MockMergeRequests.EXPECT().
1257 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
1258 Return(&gitlab.MergeRequest{
1259 BasicMergeRequest: gitlab.BasicMergeRequest{
1260 ID: 123,
1261 IID: 123,
1262 ProjectID: 3,
1263 SourceProjectID: 3,
1264 SourceBranch: "feat-new-mr",
1265 State: "opened",
1266 SHA: "abc123",
1267 },
1268 }, nil, nil)
1270 testClient.MockProjects.EXPECT().
1271 GetProject(gomock.Any(), gomock.Any()).
1272 Return(&gitlab.Project{
1273 ID: 3,
1274 SSHURLToRepo: "git@gitlab.com:OWNER/REPO.git",
1275 }, nil, nil)
1277 return testClient
1280 // validate() consults this before any side effects, so every --worktree
1281 // subtest has to answer it.
1282 worktreeList := func(entries string) string {
1283 return "worktree /repo" + "\n" + "HEAD aaa000" + "\n" + "branch refs/heads/main" + "\n" + entries
1286 expectNoOtherWorktree := func(mockGit *git_testing.MockGitRunner) {
1287 mockGit.EXPECT().Git("worktree", "list", "--porcelain").Return(worktreeList(""), nil)
1290 expectFetchAndConfig := func(mockGit *git_testing.MockGitRunner) {
1291 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
1292 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
1293 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "git@gitlab.com:OWNER/REPO.git", "refs/heads/feat-new-mr:feat-new-mr").
1294 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
1295 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "git@gitlab.com:OWNER/REPO.git").Return("", nil)
1296 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
1299 t.Run("adds a worktree instead of checking out the branch", func(t *testing.T) {
1300 t.Parallel()
1301 testClient := newTestClient(t)
1303 ctrl := gomock.NewController(t)
1304 mockGit := git_testing.NewMockGitRunner(ctrl)
1305 expectNoOtherWorktree(mockGit)
1306 expectFetchAndConfig(mockGit)
1307 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "worktree", "add", "--", "../review-mr-123", "feat-new-mr").Return(nil)
1309 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1310 output, err := exec("123 --worktree ../review-mr-123")
1312 require.NoError(t, err)
1313 assert.Contains(t, output.Stderr(), "[new branch] refs/heads/feat-new-mr:feat-new-mr")
1314 })
1316 t.Run("passes a worktree path after -- so a leading dash is not an option", func(t *testing.T) {
1317 t.Parallel()
1318 testClient := newTestClient(t)
1320 ctrl := gomock.NewController(t)
1321 mockGit := git_testing.NewMockGitRunner(ctrl)
1322 expectNoOtherWorktree(mockGit)
1323 expectFetchAndConfig(mockGit)
1324 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "worktree", "add", "--", "-review-mr-123", "feat-new-mr").Return(nil)
1326 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1327 _, err := exec("123 --worktree=-review-mr-123")
1329 require.NoError(t, err)
1330 })
1332 t.Run("sets the upstream of the worktree branch by name", func(t *testing.T) {
1333 t.Parallel()
1334 testClient := newTestClient(t)
1336 ctrl := gomock.NewController(t)
1337 mockGit := git_testing.NewMockGitRunner(ctrl)
1338 expectNoOtherWorktree(mockGit)
1339 expectFetchAndConfig(mockGit)
1340 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "worktree", "add", "--", "../review-mr-123", "feat-new-mr").Return(nil)
1341 mockGit.EXPECT().Git("branch", "--set-upstream-to", "upstream/main", "feat-new-mr").Return("", nil)
1343 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1344 _, err := exec("123 --worktree ../review-mr-123 --set-upstream-to upstream/main")
1346 require.NoError(t, err)
1347 })
1349 t.Run("reports a failure to add the worktree", func(t *testing.T) {
1350 t.Parallel()
1351 testClient := newTestClient(t)
1353 ctrl := gomock.NewController(t)
1354 mockGit := git_testing.NewMockGitRunner(ctrl)
1355 expectNoOtherWorktree(mockGit)
1356 expectFetchAndConfig(mockGit)
1357 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "worktree", "add", "--", "../review-mr-123", "feat-new-mr").
1358 Return(errors.New("fatal: '../review-mr-123' already exists"))
1360 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1361 _, err := exec("123 --worktree ../review-mr-123")
1363 require.ErrorContains(t, err, `could not add worktree "../review-mr-123" for branch "feat-new-mr"`)
1364 })
1366 t.Run("skips the fetch when the branch is already at the merge request head", func(t *testing.T) {
1367 t.Parallel()
1368 testClient := newTestClient(t)
1370 ctrl := gomock.NewController(t)
1371 mockGit := git_testing.NewMockGitRunner(ctrl)
1372 expectNoOtherWorktree(mockGit)
1373 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("abc123"+"\n", nil)
1374 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "git@gitlab.com:OWNER/REPO.git").Return("", nil)
1375 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
1376 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "worktree", "add", "--", "../review-mr-123", "feat-new-mr").Return(nil)
1378 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1379 output, err := exec("123 --worktree ../review-mr-123")
1381 require.NoError(t, err)
1382 assert.Contains(t, output.String(), "skipping fetch")
1383 })
1385 // gomock is strict, so the absence of fetch and config expectations here is
1386 // the assertion that the guard runs before any side effects.
1387 t.Run("fails early when the branch is checked out in another worktree", func(t *testing.T) {
1388 t.Parallel()
1389 testClient := gitlabtesting.NewTestClient(t)
1390 testClient.MockMergeRequests.EXPECT().
1391 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
1392 Return(&gitlab.MergeRequest{
1393 BasicMergeRequest: gitlab.BasicMergeRequest{
1394 ID: 123,
1395 IID: 123,
1396 ProjectID: 3,
1397 SourceProjectID: 3,
1398 SourceBranch: "feat-new-mr",
1399 State: "opened",
1400 SHA: "abc123",
1401 },
1402 }, nil, nil)
1404 ctrl := gomock.NewController(t)
1405 mockGit := git_testing.NewMockGitRunner(ctrl)
1406 mockGit.EXPECT().Git("worktree", "list", "--porcelain").
1407 Return(worktreeList("worktree /elsewhere/review"+"\n"+"HEAD abc123"+"\n"+"branch refs/heads/feat-new-mr"+"\n"), nil)
1409 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1410 _, err := exec("123 --worktree ../review-mr-123")
1412 require.ErrorContains(t, err, `branch "feat-new-mr" is already checked out at "/elsewhere/review"`)
1413 require.ErrorContains(t, err, "--branch")
1414 })
1416 // A repeat review of the same merge request lands here. Returning early would
1417 // leave the reviewer on stale code while reporting success, so the branch is
1418 // brought up to date inside the worktree that holds it.
1419 expectBranchInRequestedWorktree := func(mockGit *git_testing.MockGitRunner, requested string) {
1420 abs, err := filepath.Abs(requested)
1421 require.NoError(t, err)
1422 mockGit.EXPECT().Git("worktree", "list", "--porcelain").
1423 Return(worktreeList("worktree "+abs+"\n"+"HEAD old"+"\n"+"branch refs/heads/feat-new-mr"+"\n"), nil)
1426 // No `refs/heads/x:refs/heads/x` fetch here: git always refuses that for a branch
1427 // a worktree holds, so an in-place update goes straight to the FETCH_HEAD fetch.
1428 expectFetchIntoExistingWorktree := func(mockGit *git_testing.MockGitRunner) {
1429 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "git@gitlab.com:OWNER/REPO.git", "refs/heads/feat-new-mr").
1430 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
1431 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old"+"\n", nil).Times(2)
1432 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new"+"\n", nil)
1433 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", nil)
1434 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "git@gitlab.com:OWNER/REPO.git").Return("", nil)
1435 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
1438 t.Run("updates the branch in place when it is already in the requested worktree", func(t *testing.T) {
1439 t.Parallel()
1440 requested := "../review-mr-123"
1441 testClient := newTestClient(t)
1443 ctrl := gomock.NewController(t)
1444 mockGit := git_testing.NewMockGitRunner(ctrl)
1445 expectBranchInRequestedWorktree(mockGit, requested)
1446 expectFetchIntoExistingWorktree(mockGit)
1447 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "-C", requested, "merge", "--ff-only", "new").Return(nil)
1449 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1450 output, err := exec("123 --worktree " + requested)
1452 require.NoError(t, err)
1453 assert.Contains(t, output.String(), "already checked out at")
1454 })
1456 t.Run("still applies --set-upstream-to when the worktree already exists", func(t *testing.T) {
1457 t.Parallel()
1458 requested := "../review-mr-123"
1459 testClient := newTestClient(t)
1461 ctrl := gomock.NewController(t)
1462 mockGit := git_testing.NewMockGitRunner(ctrl)
1463 expectBranchInRequestedWorktree(mockGit, requested)
1464 expectFetchIntoExistingWorktree(mockGit)
1465 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "-C", requested, "merge", "--ff-only", "new").Return(nil)
1466 mockGit.EXPECT().Git("branch", "--set-upstream-to", "upstream/main", "feat-new-mr").Return("", nil)
1468 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1469 _, err := exec("123 --worktree " + requested + " --set-upstream-to upstream/main")
1471 require.NoError(t, err)
1472 })
1474 // The reset lands in the review worktree, so --force must not discard work
1475 // there without looking, which is what the flag's own help promises.
1476 expectDivergedInPlace := func(mockGit *git_testing.MockGitRunner) {
1477 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "git@gitlab.com:OWNER/REPO.git", "refs/heads/feat-new-mr").
1478 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
1479 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old"+"\n", nil).Times(2)
1480 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new"+"\n", nil)
1481 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").
1482 Return("", errors.New("not an ancestor"))
1485 t.Run("refuses --force when the existing worktree has uncommitted work", func(t *testing.T) {
1486 t.Parallel()
1487 requested := "../review-mr-123"
1488 testClient := newTestClient(t)
1490 ctrl := gomock.NewController(t)
1491 mockGit := git_testing.NewMockGitRunner(ctrl)
1492 expectBranchInRequestedWorktree(mockGit, requested)
1493 expectDivergedInPlace(mockGit)
1494 mockGit.EXPECT().Git("-C", requested, "diff", "--name-only", "HEAD").Return("dirty.go\n", nil)
1496 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1497 _, err := exec("123 --worktree " + requested + " --force")
1499 require.ErrorContains(t, err, requested)
1500 require.ErrorContains(t, err, "would be lost by reset")
1501 })
1503 t.Run("resets inside the existing worktree when it is clean", func(t *testing.T) {
1504 t.Parallel()
1505 requested := "../review-mr-123"
1506 testClient := newTestClient(t)
1508 ctrl := gomock.NewController(t)
1509 mockGit := git_testing.NewMockGitRunner(ctrl)
1510 expectBranchInRequestedWorktree(mockGit, requested)
1511 expectDivergedInPlace(mockGit)
1512 mockGit.EXPECT().Git("-C", requested, "diff", "--name-only", "HEAD").Return("", nil)
1513 mockGit.EXPECT().Git("-C", requested, "ls-files", "--others", "--exclude-standard").Return("", nil)
1514 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "-C", requested, "reset", "--hard", "new").Return(nil)
1515 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "git@gitlab.com:OWNER/REPO.git").Return("", nil)
1516 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
1518 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1519 _, err := exec("123 --worktree " + requested + " --force")
1521 require.NoError(t, err)
1522 })
1524 // A worktree whose directory was deleted is still listed, marked prunable, and
1525 // git keeps counting it as holding the branch, so `worktree add` would refuse.
1526 // The guard fails here, before the fetch, with a `git worktree prune` hint
1527 // rather than letting the add fail later with git's own wording. The absence of
1528 // fetch and add expectations under strict gomock asserts nothing runs first.
1529 t.Run("fails early with a prune hint when the branch's worktree is prunable", func(t *testing.T) {
1530 t.Parallel()
1531 testClient := gitlabtesting.NewTestClient(t)
1532 testClient.MockMergeRequests.EXPECT().
1533 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
1534 Return(&gitlab.MergeRequest{
1535 BasicMergeRequest: gitlab.BasicMergeRequest{
1536 ID: 123,
1537 IID: 123,
1538 ProjectID: 3,
1539 SourceProjectID: 3,
1540 SourceBranch: "feat-new-mr",
1541 State: "opened",
1542 SHA: "abc123",
1543 },
1544 }, nil, nil)
1546 ctrl := gomock.NewController(t)
1547 mockGit := git_testing.NewMockGitRunner(ctrl)
1548 mockGit.EXPECT().Git("worktree", "list", "--porcelain").
1549 Return(worktreeList("worktree /gone"+"\n"+"HEAD old"+"\n"+"branch refs/heads/feat-new-mr"+"\n"+"prunable gitdir file points to non-existent location"+"\n"), nil)
1551 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1552 _, err := exec("123 --worktree ../review-mr-123")
1554 require.ErrorContains(t, err, `branch "feat-new-mr" is held by a worktree at "/gone"`)
1555 require.ErrorContains(t, err, "git worktree prune")
1556 })
1558 // Worktree mode touches no working tree, so the diverged branch ref is moved
1559 // with `git branch -f`. A `reset --hard` here would hit the current directory,
1560 // which is the thing --worktree exists to avoid.
1561 t.Run("moves the ref instead of resetting when the branch has diverged", func(t *testing.T) {
1562 t.Parallel()
1563 testClient := newTestClient(t)
1565 ctrl := gomock.NewController(t)
1566 mockGit := git_testing.NewMockGitRunner(ctrl)
1567 expectNoOtherWorktree(mockGit)
1568 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "git@gitlab.com:OWNER/REPO.git", "refs/heads/feat-new-mr:feat-new-mr").
1569 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "non-fast-forward"))
1570 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "git@gitlab.com:OWNER/REPO.git", "refs/heads/feat-new-mr").
1571 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
1572 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old"+"\n", nil).Times(2)
1573 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new"+"\n", nil)
1574 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").
1575 Return("", errors.New("not an ancestor"))
1576 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "branch", "-f", "feat-new-mr", "FETCH_HEAD").Return(nil)
1577 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "git@gitlab.com:OWNER/REPO.git").Return("", nil)
1578 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
1579 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "worktree", "add", "--", "../review-mr-123", "feat-new-mr").Return(nil)
1581 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1582 _, err := exec("123 --worktree ../review-mr-123 --force")
1584 require.NoError(t, err)
1585 })
1587 // A branch that is merely behind reaches fastForward() rather than the reset
1588 // path. The branch is checked out nowhere, so the ref moves with `branch -f`;
1589 // `merge --ff-only` would act on the current directory.
1590 t.Run("fast-forwards a behind branch with branch -f rather than merging", func(t *testing.T) {
1591 t.Parallel()
1592 testClient := newTestClient(t)
1594 ctrl := gomock.NewController(t)
1595 mockGit := git_testing.NewMockGitRunner(ctrl)
1596 expectNoOtherWorktree(mockGit)
1597 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "git@gitlab.com:OWNER/REPO.git", "refs/heads/feat-new-mr:feat-new-mr").
1598 DoAndReturn(git.FailingFetchStub("refs/heads/feat-new-mr:feat-new-mr", "non-fast-forward"))
1599 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "git@gitlab.com:OWNER/REPO.git", "refs/heads/feat-new-mr").
1600 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr"))
1601 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("old"+"\n", nil).Times(2)
1602 mockGit.EXPECT().Git("rev-parse", "FETCH_HEAD^{commit}").Return("new"+"\n", nil)
1603 mockGit.EXPECT().Git("merge-base", "--is-ancestor", "refs/heads/feat-new-mr", "FETCH_HEAD").Return("", nil)
1604 mockGit.EXPECT().Git("symbolic-ref", "--quiet", "--short", "HEAD").Return("main"+"\n", nil)
1605 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "branch", "-f", "feat-new-mr", "FETCH_HEAD").Return(nil)
1606 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "git@gitlab.com:OWNER/REPO.git").Return("", nil)
1607 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
1608 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "worktree", "add", "--", "../review-mr-123", "feat-new-mr").Return(nil)
1610 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit))
1611 _, err := exec("123 --worktree ../review-mr-123")
1613 require.NoError(t, err)
1614 })
1617func gitIn(t *testing.T, dir string, args ...string) string {
1618 t.Helper()
1620 cmd := exec.Command("git", args...)
1621 cmd.Dir = dir
1622 out, err := cmd.CombinedOutput()
1623 require.NoError(t, err, string(out))
1624 return strings.TrimSpace(string(out))
1627func clientForSHA(t *testing.T, sha, remoteURL string) *gitlabtesting.TestClient {
1628 t.Helper()
1630 testClient := gitlabtesting.NewTestClient(t)
1631 testClient.MockMergeRequests.EXPECT().
1632 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
1633 Return(&gitlab.MergeRequest{
1634 BasicMergeRequest: gitlab.BasicMergeRequest{
1635 ID: 123,
1636 IID: 123,
1637 ProjectID: 3,
1638 SourceProjectID: 3,
1639 SourceBranch: "feat-new-mr",
1640 State: "opened",
1641 SHA: sha,
1642 },
1643 }, nil, nil).AnyTimes()
1644 testClient.MockProjects.EXPECT().
1645 GetProject(gomock.Any(), gomock.Any()).
1646 Return(&gitlab.Project{
1647 ID: 3,
1648 SSHURLToRepo: remoteURL,
1649 HTTPURLToRepo: remoteURL,
1650 }, nil, nil).AnyTimes()
1652 return testClient
1655// The mocked subtests above stub the very commands that behave differently against
1656// real git, so the repeat review is driven end to end instead. FETCH_HEAD is
1657// per-worktree, and a merge that reads the review worktree's own copy either fails
1658// or silently leaves it on the old commit.
1660// No t.Parallel(): InitGitRepoWithCommit calls t.Chdir.
1661func TestMrCheckout_WorktreeRepeatReviewRealGit(t *testing.T) {
1662 repo := git.InitGitRepoWithCommit(t)
1663 remote := filepath.Join(t.TempDir(), "remote.git")
1664 gitIn(t, repo, "init", "--bare", remote)
1665 gitIn(t, repo, "push", remote, "HEAD:refs/heads/feat-new-mr")
1666 c1 := gitIn(t, repo, "rev-parse", "HEAD")
1668 // RemoteURL now rejects a bare filesystem path, so the project advertises a valid
1669 // URL and insteadOf rewrites it back to the local bare repo used as the transport.
1670 const remoteURL = "https://gitlab.example.com/OWNER/REPO.git"
1671 gitIn(t, repo, "config", "url."+filepath.ToSlash(remote)+".insteadOf", remoteURL)
1673 // Forward slashes keep the argument intact when the command string is split.
1674 worktree := filepath.ToSlash(filepath.Join(t.TempDir(), "review"))
1676 _, err := setupTest(t, clientForSHA(t, c1, remoteURL))("123 --worktree " + worktree)
1677 require.NoError(t, err)
1678 assert.Equal(t, c1, gitIn(t, worktree, "rev-parse", "HEAD"))
1680 other := filepath.Join(t.TempDir(), "other")
1681 gitIn(t, repo, "clone", "-q", "-b", "feat-new-mr", remote, other)
1682 gitIn(t, other, "-c", "user.name=x", "-c", "user.email=x@x", "-c", "commit.gpgsign=false", "commit", "-q", "--allow-empty", "-m", "c2")
1683 gitIn(t, other, "push", "-q", "origin", "feat-new-mr")
1684 c2 := gitIn(t, other, "rev-parse", "HEAD")
1686 _, err = setupTest(t, clientForSHA(t, c2, remoteURL))("123 --worktree " + worktree)
1687 require.NoError(t, err)
1688 assert.Equal(t, c2, gitIn(t, worktree, "rev-parse", "HEAD"))
1691func TestSameWorktreePath(t *testing.T) {
1692 t.Parallel()
1694 dir := t.TempDir()
1695 link := filepath.Join(t.TempDir(), "link")
1696 if err := os.Symlink(dir, link); err != nil {
1697 t.Skipf("cannot create a symlink on this platform: %v", err)
1699 resolved, err := filepath.EvalSymlinks(dir)
1700 require.NoError(t, err)
1702 // git reports a resolved path, so a request made through a symlink, such as
1703 // /tmp on macOS or a symlinked home directory, has to resolve to the same place.
1704 assert.True(t, sameWorktreePath(resolved, link))
1705 assert.True(t, sameWorktreePath(link, resolved))
1706 assert.True(t, sameWorktreePath(resolved, dir))
1707 assert.False(t, sameWorktreePath(resolved, filepath.Join(dir, "elsewhere")))
1709 // A path that does not exist yet is the ordinary first-run case: EvalSymlinks
1710 // fails there, so the fallback has to clean the two spellings to the same place.
1711 missing := filepath.Join(dir, "not-created-yet")
1712 assert.True(t, sameWorktreePath(missing, filepath.Join(dir, "sub", "..", "not-created-yet")))
1713 assert.False(t, sameWorktreePath(missing, filepath.Join(dir, "sub", "not-created-yet")))
1716func TestMrCheckout_HTTPSProtocolConfiguration(t *testing.T) {
1717 t.Parallel()
1718 testClient := gitlabtesting.NewTestClient(t)
1720 testClient.MockMergeRequests.EXPECT().
1721 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
1722 Return(&gitlab.MergeRequest{
1723 BasicMergeRequest: gitlab.BasicMergeRequest{
1724 ID: 123,
1725 IID: 123,
1726 ProjectID: 3,
1727 SourceProjectID: 3,
1728 SourceBranch: "feat-new-mr",
1729 Title: "test mr title",
1730 Description: "test mr description",
1731 AllowCollaboration: false,
1732 State: "opened",
1733 SHA: "abc123",
1734 },
1735 }, nil, nil)
1737 testClient.MockProjects.EXPECT().
1738 GetProject(gomock.Any(), gomock.Any()).
1739 Return(&gitlab.Project{
1740 ID: 3,
1741 PathWithNamespace: "contributor/REPO",
1742 HTTPURLToRepo: "https://gitlab.com/contributor/REPO.git",
1743 SSHURLToRepo: "git@gitlab.com:contributor/REPO.git",
1744 }, nil, nil)
1746 ctrl := gomock.NewController(t)
1747 mockGit := git_testing.NewMockGitRunner(ctrl)
1748 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
1749 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
1750 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "https://gitlab.com/contributor/REPO.git", "refs/heads/feat-new-mr:feat-new-mr").
1751 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
1752 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "https://gitlab.com/contributor/REPO.git").Return("", nil)
1753 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
1754 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
1755 DoAndReturn(git.CheckoutStub("feat-new-mr"))
1757 cfg := config.NewBlankConfig()
1758 err := cfg.Set("gitlab.com", "git_protocol", "https")
1759 require.NoError(t, err)
1761 exec := setupTest(t, testClient, cmdtest.WithGitRunner(mockGit), cmdtest.WithConfig(cfg))
1762 output, err := exec("123")
1764 require.NoError(t, err)
1765 assert.Contains(t, output.Stderr(), "[new branch] refs/heads/feat-new-mr:feat-new-mr")
1766 assert.Contains(t, output.Stderr(), "Switched to a new branch 'feat-new-mr'")
1769// TestMrCheckout_CrossHostURLUsesURLHostProtocol verifies that when an MR URL pointing at a
1770// different host is given, the git_protocol lookup uses the URL's host (not the local repo's
1771// host). Before the refactor, baseRepo came from f.BaseRepo(); now it comes from MRFromArgs,
1772// which overrides baseRepo with the URL repo for cross-host URLs.
1773func TestMrCheckout_CrossHostURLUsesURLHostProtocol(t *testing.T) {
1774 t.Parallel()
1775 testClient := gitlabtesting.NewTestClient(t)
1777 testClient.MockMergeRequests.EXPECT().
1778 GetMergeRequest("OWNER/REPO", int64(123), gomock.Any(), gomock.Any()).
1779 Return(&gitlab.MergeRequest{
1780 BasicMergeRequest: gitlab.BasicMergeRequest{
1781 ID: 123,
1782 IID: 123,
1783 ProjectID: 3,
1784 SourceProjectID: 3,
1785 SourceBranch: "feat-new-mr",
1786 Title: "test mr title",
1787 Description: "test mr description",
1788 State: "opened",
1789 SHA: "abc123",
1790 },
1791 }, nil, nil)
1793 testClient.MockProjects.EXPECT().
1794 GetProject(gomock.Any(), gomock.Any()).
1795 Return(&gitlab.Project{
1796 ID: 3,
1797 HTTPURLToRepo: "https://custom.host.com/OWNER/REPO.git",
1798 PathWithNamespace: "OWNER/REPO",
1799 SSHURLToRepo: "git@custom.host.com:OWNER/REPO.git",
1800 }, nil, nil)
1802 ctrl := gomock.NewController(t)
1803 mockGit := git_testing.NewMockGitRunner(ctrl)
1804 mockGit.EXPECT().Git("rev-parse", "--verify", "refs/heads/feat-new-mr").Return("", errors.New("not found"))
1805 mockGit.EXPECT().Git("rev-parse", "--verify", "abc123^{commit}").Return("", errors.New("not found"))
1806 // The fetch URL must use HTTPS (from custom.host.com's config), not SSH (from gitlab.com's config).
1807 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "fetch", "--", "https://custom.host.com/OWNER/REPO.git", "refs/heads/feat-new-mr:feat-new-mr").
1808 DoAndReturn(git.FetchStub("refs/heads/feat-new-mr:feat-new-mr"))
1809 mockGit.EXPECT().Git("config", "branch.feat-new-mr.remote", "https://custom.host.com/OWNER/REPO.git").Return("", nil)
1810 mockGit.EXPECT().Git("config", "branch.feat-new-mr.merge", "refs/heads/feat-new-mr").Return("", nil)
1811 mockGit.EXPECT().GitWithIO(gomock.Any(), gomock.Any(), "checkout", "feat-new-mr").
1812 DoAndReturn(git.CheckoutStub("feat-new-mr"))
1814 cfg := config.NewBlankConfig()
1815 err := cfg.Set("custom.host.com", "git_protocol", "https")
1816 require.NoError(t, err)
1817 // gitlab.com intentionally left with default (ssh) to distinguish the two hosts.
1819 exec := setupTest(t, testClient,
1820 cmdtest.WithGitRunner(mockGit),
1821 cmdtest.WithConfig(cfg),
1822 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
1824 output, err := exec("https://custom.host.com/OWNER/REPO/-/merge_requests/123")
1826 require.NoError(t, err)
1827 assert.Contains(t, output.Stderr(), "[new branch] refs/heads/feat-new-mr:feat-new-mr")
1828 assert.Contains(t, output.Stderr(), "Switched to a new branch 'feat-new-mr'")
Diagnostics8 git calls · 220 ms
CallStatusSizeTime0220 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 KiB3 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=UPDATING
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=44
Open pack map
fetchtree:02001.8 KiB · hit1 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=1
git.response.bytes=1857
git.response.cache=HIT
git.response.duration_ms=1
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=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200746 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=746
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=f3d413a22af5a9c2fe9aa49709b1cb36d1351a7f
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=746
git.pkt.payload.max=719
git.sideband.band1.bytes=719
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=719
git.pack.trailer=330baf80c59a4208b55120dff7dd824b7952b790
Open pack map
fetchtree:0200180 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=180
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=798b94905ec5caf72269567e97fe6dba32b63a3c
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=180
git.pkt.payload.max=153
git.sideband.band1.bytes=153
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=153
git.pack.trailer=0357626d2605d28d1849d8be9216332c1b4ca495
Open pack map
fetch2007.7 KiB209 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=209
git.response.bytes=7878
git.response.cache=MISS
git.response.duration_ms=209
git.fetch.wants=8dbe6194cd90b4ae28e567199cc1bd3060caf187
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=7878
git.pkt.payload.max=7851
git.sideband.band1.bytes=7851
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
a5e302157e207929
Request
8a94e582…
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