GitLabgitlab-org
cli
main
1//go:build !integration
3package save
5import (
6 "bytes"
7 "net/http"
8 "os"
9 "path"
10 "strings"
11 "testing"
12 "time"
14 "github.com/MakeNowJust/heredoc/v2"
15 "github.com/spf13/cobra"
16 "github.com/stretchr/testify/require"
17 "go.uber.org/mock/gomock"
19 "gitlab.com/gitlab-org/cli/internal/cmdutils"
20 "gitlab.com/gitlab-org/cli/internal/commands/stack/stackutils"
21 "gitlab.com/gitlab-org/cli/internal/config"
22 "gitlab.com/gitlab-org/cli/internal/git"
23 git_testing "gitlab.com/gitlab-org/cli/internal/git/testing"
24 "gitlab.com/gitlab-org/cli/internal/run"
25 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
26)
28// setupTestFactory is used by prompt_test.go to test internal functions.
29func setupTestFactory(t *testing.T, rt http.RoundTripper, isTTY bool) (*bytes.Buffer, *bytes.Buffer, cmdutils.Factory) {
30 t.Helper()
32 ios, _, stdout, stderr := cmdtest.TestIOStreams(cmdtest.WithTestIOStreamsAsTTY(isTTY))
34 factory := cmdtest.NewTestFactory(ios,
35 cmdtest.WithGitLabClient(cmdtest.NewTestApiClient(t, &http.Client{Transport: rt}, "", "gitlab.com").Lab()),
36 )
38 return stdout, stderr, factory
39}
41func TestSaveNewStack(t *testing.T) {
42 // NOTE: we need to force disable colors, otherwise we'd need ANSI sequences in our test output assertions.
43 t.Setenv("NO_COLOR", "true")
45 tests := []struct {
46 desc string
47 args []string
48 files []string
49 trackedFiles []string
50 message string
51 expected string
52 wantErr bool
53 noTTY bool
54 editorMessage string
55 }{
56 {
57 desc: "adding regular files",
58 args: []string{"testfile", "randomfile"},
59 files: []string{"testfile", "randomfile"},
60 message: "this is a commit message",
61 expected: "• cool-test-feature: Saved with message: \"this is a commit message\".\n",
62 },
64 {
65 desc: "adding files with a dot argument",
66 args: []string{"."},
67 files: []string{"testfile", "randomfile"},
68 message: "this is a commit message",
69 expected: "• cool-test-feature: Saved with message: \"this is a commit message\".\n",
70 },
72 {
73 desc: "adding files with no argument and no staged changes",
74 args: []string{""},
75 files: []string{"testfile", "randomfile"},
76 message: "this is a commit message",
77 expected: "no staged changes",
78 wantErr: true,
79 },
81 {
82 desc: "omitting a message",
83 args: []string{"."},
84 files: []string{"testfile"},
85 editorMessage: "oh ok fine how about blah blah",
86 expected: "• cool-test-feature: Saved with message: \"oh ok fine how about blah blah\".\n",
87 },
89 {
90 desc: "with no changed files",
91 args: []string{"."},
92 files: []string{},
93 expected: "could not save: \"no changes to save.\"",
94 wantErr: true,
95 },
97 {
98 desc: "Test with no message and noTTY",
99 args: []string{"."},
100 files: []string{"testfile"},
101 expected: "glab stack save without `-m` and without a TTY should throw an error.",
102 wantErr: true,
103 noTTY: true,
104 },
106 {
107 desc: "adding tracked files with -a flag",
108 args: []string{"-a"},
109 trackedFiles: []string{"trackedfile"},
110 message: "this is a commit message",
111 expected: "• cool-test-feature: Saved with message: \"this is a commit message\".\n",
112 },
114 {
115 desc: "adding with -a flag but only untracked files returns error",
116 args: []string{"-a"},
117 files: []string{"untrackedfile"},
118 message: "this is a commit message",
119 wantErr: true,
120 expected: "glab stack save -a with no tracked changes should return an error",
121 },
123 {
124 desc: "adding regular files with --no-verify",
125 args: []string{"testfile", "--no-verify"},
126 files: []string{"testfile"},
127 message: "commit with no verify",
128 expected: "• cool-test-feature: Saved with message: \"commit with no verify\".\n",
129 },
130 }
132 for _, tc := range tests {
133 isTTY := !tc.noTTY
134 t.Run(tc.desc, func(t *testing.T) {
135 if tc.message != "" && isTTY {
136 tc.args = append(tc.args, "-m")
137 tc.args = append(tc.args, "\""+tc.message+"\"")
138 }
140 dir := git.InitGitRepoWithCommit(t)
141 err := git.SetCurrentStackTitle("cool-test-feature")
142 require.NoError(t, err)
144 createTemporaryFiles(t, dir, tc.files)
146 if len(tc.trackedFiles) > 0 {
147 createTemporaryFiles(t, dir, tc.trackedFiles)
149 gitCmd := git.GitCommand("add", ".")
150 _, err = run.PrepareCmd(gitCmd).Output()
151 require.NoError(t, err)
153 gitCmd = git.GitCommand("commit", "-m", "initial tracked files")
154 _, err = run.PrepareCmd(gitCmd).Output()
155 require.NoError(t, err)
157 for _, file := range tc.trackedFiles {
158 err = os.WriteFile(path.Join(dir, file), []byte("modified content"), 0o644)
159 require.NoError(t, err)
160 }
161 }
163 getText := getMockEditor(tc.editorMessage, &[]string{})
164 args := strings.Join(tc.args, " ")
166 ctrl := gomock.NewController(t)
167 mockCmd := git_testing.NewMockGitRunner(ctrl)
169 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
170 return NewCmdSaveStack(f, mockCmd, getText)
171 }, isTTY,
172 cmdtest.WithGitLabClient(cmdtest.NewTestApiClient(t, nil, "", "gitlab.com").Lab()),
173 )
175 output, err := exec(args)
177 if tc.wantErr {
178 require.Errorf(t, err, tc.expected)
179 } else {
180 require.NoError(t, err)
181 require.Equal(t, tc.expected, output.String())
182 }
183 })
184 }
185}
187func TestSaveStack_WarningWhenNotOnLastEntry(t *testing.T) {
188 t.Setenv("NO_COLOR", "true")
190 firstRef := git.StackRef{
191 SHA: "first123",
192 Branch: "user-test-stack-first123",
193 Description: "first entry",
194 Next: "second456",
195 }
196 secondRef := git.StackRef{
197 SHA: "second456",
198 Branch: "user-test-stack-second456",
199 Description: "second entry",
200 Prev: "first123",
201 }
203 tests := []struct {
204 desc string
205 checkoutRef git.StackRef
206 expectWarning bool
207 }{
208 {
209 desc: "warning when on first entry of stack",
210 checkoutRef: firstRef,
211 expectWarning: true,
212 },
213 {
214 desc: "no warning when on last entry of stack",
215 checkoutRef: secondRef,
216 expectWarning: false,
217 },
218 }
220 for _, tc := range tests {
221 t.Run(tc.desc, func(t *testing.T) {
222 dir := git.InitGitRepoWithCommit(t)
223 stackTitle := "test-stack"
224 err := git.SetCurrentStackTitle(stackTitle)
225 require.NoError(t, err)
227 err = git.AddStackRefFile(stackTitle, firstRef)
228 require.NoError(t, err)
229 err = git.AddStackRefFile(stackTitle, secondRef)
230 require.NoError(t, err)
232 err = git.CheckoutNewBranch(tc.checkoutRef.Branch)
233 require.NoError(t, err)
235 createTemporaryFiles(t, dir, []string{"newfile"})
237 ctrl := gomock.NewController(t)
238 mockCmd := git_testing.NewMockGitRunner(ctrl)
240 exec := cmdtest.SetupCmdForTest(t, func(f cmdutils.Factory) *cobra.Command {
241 return NewCmdSaveStack(f, mockCmd, getMockEditor("", &[]string{}))
242 }, true,
243 cmdtest.WithGitLabClient(cmdtest.NewTestApiClient(t, nil, "", "gitlab.com").Lab()),
244 )
246 output, err := exec(". -m \"new changes\"")
247 require.NoError(t, err)
249 if tc.expectWarning {
250 require.Contains(t, output.Stderr(), "warning: you are not on the last diff of the stack")
251 require.Contains(t, output.Stderr(), "glab stack amend")
252 } else {
253 require.NotContains(t, output.Stderr(), "warning: you are not on the last diff of the stack")
254 }
255 })
256 }
257}
259func Test_addFiles(t *testing.T) {
260 tests := []struct {
261 desc string
262 args []string
263 expected []string
264 untrackedFiles []string
265 stageAll bool
266 wantErr bool
267 errContains string
268 statusPrefix string
269 }{
270 {
271 desc: "adding regular files",
272 args: []string{"file1", "file2"},
273 expected: []string{"file1", "file2"},
274 statusPrefix: "A ",
275 },
276 {
277 desc: "adding files with a dot argument",
278 args: []string{"."},
279 expected: []string{"file1", "file2"},
280 statusPrefix: "A ",
281 },
282 {
283 desc: "with -a flag stages tracked files only",
284 args: []string{},
285 expected: []string{"file1"},
286 stageAll: true,
287 statusPrefix: "M ",
288 },
289 {
290 desc: "with no args and no staged changes returns error",
291 args: []string{},
292 expected: []string{},
293 wantErr: true,
294 errContains: "no staged changes. Stage files manually",
295 },
296 {
297 desc: "with -a flag but no tracked changes returns error",
298 args: []string{""},
299 expected: []string{},
300 wantErr: true,
301 stageAll: true,
302 errContains: "no staged changes after 'git add --update'",
303 },
304 {
305 desc: "with -a flag but only untracked files returns error",
306 args: []string{"-a"},
307 expected: []string{},
308 untrackedFiles: []string{"untracked1", "untracked2"},
309 wantErr: true,
310 stageAll: true,
311 errContains: "no staged changes after 'git add --update'",
312 },
313 }
315 for _, tc := range tests {
316 t.Run(tc.desc, func(t *testing.T) {
317 dir := git.InitGitRepoWithCommit(t)
318 err := git.SetCurrentStackTitle("cool-test-feature")
319 require.NoError(t, err)
321 createTemporaryFiles(t, dir, tc.expected)
322 createTemporaryFiles(t, dir, tc.untrackedFiles)
324 // For the tracked files test, we need to add the expected files to git first
325 if tc.stageAll && len(tc.expected) > 0 {
326 gitCmd := git.GitCommand("add", tc.expected[0])
327 _, err := run.PrepareCmd(gitCmd).Output()
328 require.NoError(t, err)
330 gitCmd = git.GitCommand("commit", "-m", "initial")
331 _, err = run.PrepareCmd(gitCmd).Output()
332 require.NoError(t, err)
334 // Now modify the file so we have a tracked file change
335 err = os.WriteFile(path.Join(dir, tc.expected[0]), []byte("modified"), 0o644)
336 require.NoError(t, err)
337 }
339 err = addFiles(tc.args, tc.stageAll)
341 if tc.wantErr {
342 require.Error(t, err)
343 if tc.errContains != "" {
344 require.ErrorContains(t, err, tc.errContains)
345 }
346 return
347 }
349 require.NoError(t, err)
351 gitCmd := git.GitCommand("status", "--short", "-u")
352 output, err := run.PrepareCmd(gitCmd).Output()
353 require.NoError(t, err)
355 normalizedFiles := []string{}
356 for _, file := range tc.expected {
357 file = tc.statusPrefix + file
359 normalizedFiles = append(normalizedFiles, file)
360 }
362 formattedOutput := strings.ReplaceAll(string(output), "\n", "")
363 require.Equal(t, formattedOutput, strings.Join(normalizedFiles, ""))
364 })
365 }
366}
368func Test_checkForChanges(t *testing.T) {
369 tests := []struct {
370 desc string
371 args []string
372 expected bool
373 }{
374 {
375 desc: "check for changes with modified files",
376 args: []string{"file1", "file2"},
377 expected: true,
378 },
379 {
380 desc: "check for changes without anything",
381 args: []string{},
382 expected: false,
383 },
384 }
386 for _, tc := range tests {
387 t.Run(tc.desc, func(t *testing.T) {
388 dir := git.InitGitRepoWithCommit(t)
389 err := git.SetCurrentStackTitle("cool-test-feature")
390 require.NoError(t, err)
392 createTemporaryFiles(t, dir, tc.args)
394 err = checkForChanges()
395 if tc.expected {
396 require.NoError(t, err)
397 } else {
398 require.Error(t, err)
399 }
400 })
401 }
402}
404func Test_commitFiles(t *testing.T) {
405 tests := []struct {
406 name string
407 want string
408 message string
409 noVerify bool
410 wantErr bool
411 }{
412 {
413 name: "a regular commit message",
414 message: "i am a test message",
415 want: "i am a test message\n 2 files changed, 0 insertions(+), 0 deletions(-)\n create mode 100644 test\n create mode 100644 yo\n",
416 },
417 {
418 name: "a regular commit message, no verify",
419 message: "i am a test message",
420 noVerify: true,
421 want: "i am a test message\n 2 files changed, 0 insertions(+), 0 deletions(-)\n create mode 100644 test\n create mode 100644 yo\n",
422 },
423 {
424 name: "no message",
425 wantErr: true,
426 },
427 }
428 for _, tt := range tests {
429 t.Run(tt.name, func(t *testing.T) {
430 dir := git.InitGitRepoWithCommit(t)
432 createTemporaryFiles(t, dir, []string{"yo", "test"})
433 err := addFiles([]string{"."}, false)
434 require.NoError(t, err)
436 got, err := commitFiles(tt.message, tt.noVerify)
438 if tt.wantErr {
439 require.Error(t, err)
440 } else {
441 require.NoError(t, err)
442 require.Contains(t, got, tt.want)
443 }
444 })
445 }
446}
448func Test_generateStackSha(t *testing.T) {
449 type args struct {
450 message string
451 title string
452 author string
453 timestamp time.Time
454 }
455 tests := []struct {
456 name string
457 args args
458 want string
459 wantErr bool
460 }{
461 {
462 name: "basic test",
463 args: args{message: "hello", title: "supercool stack title", author: "norm maclean", timestamp: time.Date(1998, time.July, 6, 1, 3, 3, 7, time.UTC)},
464 want: "e062296a",
465 },
466 }
467 for _, tt := range tests {
468 t.Run(tt.name, func(t *testing.T) {
469 git.InitGitRepo(t)
471 got, err := stackutils.GenerateStackSha(tt.args.message, tt.args.title, tt.args.author, tt.args.timestamp)
473 if tt.wantErr {
474 require.Error(t, err)
475 } else {
476 require.NoError(t, err)
477 require.Equal(t, tt.want, got)
478 }
479 })
480 }
481}
483func Test_createShaBranch(t *testing.T) {
484 type args struct {
485 sha string
486 title string
487 }
488 tests := []struct {
489 name string
490 args args
491 prefix string
492 want string
493 wantErr bool
494 }{
495 {
496 name: "standard test case",
497 args: args{sha: "237ec83c", title: "cool-change"},
498 prefix: "asdf",
499 want: "asdf-cool-change-237ec83c",
500 },
501 }
503 for _, tt := range tests {
504 t.Run(tt.name, func(t *testing.T) {
505 git.InitGitRepo(t)
507 factory := createFactoryWithConfig("branch_prefix", tt.prefix)
509 got, err := stackutils.CreateShaBranch(factory, tt.args.sha, tt.args.title)
510 require.NoError(t, err)
512 if tt.wantErr {
513 require.Error(t, err)
514 } else {
515 require.NoError(t, err)
516 require.Equal(t, tt.want, got)
517 }
518 })
519 }
520}
522func createTemporaryFiles(t *testing.T, dir string, files []string) {
523 t.Helper()
525 for _, file := range files {
526 file = path.Join(dir, file)
527 _, err := os.Create(file)
529 require.NoError(t, err)
530 }
531}
533func createFactoryWithConfig(key string, value string) cmdutils.Factory {
534 strconfig := heredoc.Doc(`
535 ` + key + `: ` + value + `
536 `)
538 cfg := config.NewFromString(strconfig)
540 ios, _, _, _ := cmdtest.TestIOStreams()
542 return cmdtest.NewTestFactory(ios, cmdtest.WithConfig(cfg))
543}
Diagnostics8 git calls · 321 ms
CallStatusSizeTime0321 ms
discover200185 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB · hit2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=59849 git.response.cache=HIT git.response.duration_ms=2 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=44Open pack map
fetchtree:02001.8 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=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:0200432 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=432 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=ff2d1e7abc74964e5679ebdb51f1ac0d0dc3aff0 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=432 git.pkt.payload.max=405 git.sideband.band1.bytes=405 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=405 git.pack.trailer=8f3029a269217d94d12d0671e0490fe3d5506303Open pack map
fetchtree:0200254 B · hit13 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=13 git.response.bytes=254 git.response.cache=HIT git.response.duration_ms=13 git.fetch.filter=tree:0 git.fetch.wants=1bddb68dc447e75c7fc2f3cd02e93e572448d630 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=254 git.pkt.payload.max=227 git.sideband.band1.bytes=227 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=227 git.pack.trailer=5113828f2359f89a3269ef1119ad801c584c57a8Open pack map
fetch2003.4 KiB298 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=298 git.response.bytes=3468 git.response.cache=MISS git.response.duration_ms=298 git.fetch.wants=813c0807f9b89f09fcfc80129fd5e39aa5ba7c6e 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=3468 git.pkt.payload.max=3441 git.sideband.band1.bytes=3441 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
- a5e18a34d9cb5e37
- Request
- a64c8f00…
- 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