GitLabgitlab-org
cli
main
1package git
3import (
4 "errors"
5 "fmt"
6 "io"
7 "os"
8 "os/exec"
9 "sync/atomic"
10 "testing"
12 "github.com/stretchr/testify/require"
14 "gitlab.com/gitlab-org/cli/internal/run"
15)
17// unsetGitHookEnv removes git hook environment variables (GIT_DIR,
18// GIT_WORK_TREE, GIT_INDEX_FILE) that leak when tests run inside a git
19// hook (e.g., pre-push via lefthook). Without this, child git processes
20// in test temp directories operate against the parent repository.
21// The original values are restored when the test completes.
22func unsetGitHookEnv(t *testing.T) {
23 t.Helper()
25 for _, key := range []string{"GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"} {
26 if _, ok := os.LookupEnv(key); ok {
27 // t.Setenv saves the original value and restores it on cleanup.
28 // We then unset the variable so git commands in temp repos don't
29 // inherit hook environment from the parent process.
30 t.Setenv(key, "")
31 require.NoError(t, os.Unsetenv(key))
32 }
33 }
34}
36func InitGitRepo(t *testing.T) string {
37 t.Helper()
39 unsetGitHookEnv(t)
41 tempDir := t.TempDir()
43 t.Chdir(tempDir)
45 gitInit := GitCommand("init")
46 _, err := run.PrepareCmd(gitInit).Output()
47 require.NoError(t, err)
49 return tempDir
50}
52func InitGitRepoWithCommit(t *testing.T) string {
53 t.Helper()
55 tempDir := InitGitRepo(t)
57 configureGitConfig(t)
59 err := exec.Command("touch", "randomfile").Run()
60 require.NoError(t, err)
62 gitAdd := GitCommand("add", "randomfile")
63 _, err = run.PrepareCmd(gitAdd).Output()
64 require.NoError(t, err)
66 gitCommit := GitCommand("commit", "-m", "\"commit\"")
67 _, err = run.PrepareCmd(gitCommit).Output()
68 require.NoError(t, err)
70 return tempDir
71}
73func configureGitConfig(t *testing.T) {
74 t.Helper()
76 // CI will throw errors using a git command without a configuration
77 nameConfig := GitCommand("config", "user.name", "glab test bot")
78 _, err := run.PrepareCmd(nameConfig).Output()
79 require.NoError(t, err)
81 emailConfig := GitCommand("config", "user.email", "no-reply+cli-tests@gitlab.com")
82 _, err = run.PrepareCmd(emailConfig).Output()
83 require.NoError(t, err)
85 gpgConfig := GitCommand("config", "commit.gpgsign", "false")
86 _, err = run.PrepareCmd(gpgConfig).Output()
87 require.NoError(t, err)
88}
90// testRepo scaffolds a git repo and its worktrees for tests. It owns its root
91// directory and an auto-incrementing counter so every worktree it creates gets
92// a unique branch name without any hardcoding.
93type testRepo struct {
94 rootDir string
95 worktreeCount atomic.Int32
96}
98// NewTestRepo initializes a new git repo with a single commit (so worktrees can
99// be created from it) and returns a testRepo for scaffolding worktrees.
100func NewTestRepo(t *testing.T) *testRepo {
101 t.Helper()
102 return &testRepo{rootDir: InitGitRepoWithCommit(t)}
103}
105// addWorktree creates a new worktree from the repo with an auto-incremented
106// branch name, chdir's into it, and returns the new worktree path.
107func (tr *testRepo) addWorktree(t *testing.T) string {
108 t.Helper()
110 worktreeDir := t.TempDir()
111 branch := fmt.Sprintf("worktree-branch-%d", tr.worktreeCount.Add(1))
113 addCmd := GitCommand("worktree", "add", worktreeDir, "-b", branch)
114 addCmd.Dir = tr.rootDir
115 _, err := run.PrepareCmd(addCmd).Output()
116 require.NoError(t, err)
118 t.Chdir(worktreeDir)
120 return worktreeDir
121}
123// InitGitWorktree creates a git worktree from a new repo (which gets one
124// commit) and chdir's into it. Returns the worktree path.
125func InitGitWorktree(t *testing.T) string {
126 t.Helper()
128 return NewTestRepo(t).addWorktree(t)
129}
131// InitGitRepoOrWorktree initializes a git repo or worktree based on the
132// worktree flag. Returns the directory path.
133func InitGitRepoOrWorktree(t *testing.T, worktree bool) string {
134 t.Helper()
135 if worktree {
136 return InitGitWorktree(t)
137 }
138 return InitGitRepo(t)
139}
141func CreateRefFiles(refs map[string]StackRef, title string) error {
142 for _, ref := range refs {
143 err := AddStackRefFile(title, ref)
144 if err != nil {
145 return err
146 }
147 }
149 return nil
150}
152func CreateBranches(t *testing.T, branches []string) {
153 t.Helper()
155 // older versions of git could default to a different branch,
156 // so making sure this one exists.
157 _ = CheckoutNewBranch("main")
159 for _, branch := range branches {
160 err := CheckoutNewBranch(branch)
161 require.NoError(t, err)
162 }
163}
165// FetchStub returns a closure for MockGitRunner.GitWithIO's DoAndReturn that
166// writes a simulated `git fetch` progress line to the stderr writer the
167// caller supplies, then returns nil. Use in tests that verify a command
168// pipes its stderr writer through to GitWithIO end-to-end.
169func FetchStub(refspec string) func(stdout, stderr io.Writer, args ...string) error {
170 return func(_, stderr io.Writer, _ ...string) error {
171 fmt.Fprintf(stderr, "remote: Counting objects: 100%% (10/10), done.\n* [new branch] %s\n", refspec)
172 return nil
173 }
174}
176// FailingFetchStub is the failure variant of FetchStub: writes a stderr line,
177// then returns the supplied error message.
178func FailingFetchStub(refspec, msg string) func(stdout, stderr io.Writer, args ...string) error {
179 return func(_, stderr io.Writer, _ ...string) error {
180 fmt.Fprintf(stderr, "fetch attempt %s failed\n", refspec)
181 return errors.New(msg)
182 }
183}
185// CheckoutStub returns a closure for MockGitRunner.GitWithIO's DoAndReturn
186// that writes a simulated `git checkout` line to the stderr writer the
187// caller supplies, then returns nil.
188func CheckoutStub(branch string) func(stdout, stderr io.Writer, args ...string) error {
189 return func(_, stderr io.Writer, _ ...string) error {
190 fmt.Fprintf(stderr, "Switched to a new branch '%s'\n", branch)
191 return nil
192 }
193}
195// FailingCheckoutStub is the failure variant of CheckoutStub.
196func FailingCheckoutStub(branch, msg string) func(stdout, stderr io.Writer, args ...string) error {
197 return func(_, stderr io.Writer, _ ...string) error {
198 fmt.Fprintf(stderr, "error: pathspec '%s' did not match\n", branch)
199 return errors.New(msg)
200 }
201}
Diagnostics6 git calls · 211 ms
CallStatusSizeTime0211 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB · 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 · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=44Open pack map
fetchtree:0200510 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=204 git.response.bytes=510 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=a3147172443266d011121808a125248c5c915972 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=510 git.pkt.payload.max=483 git.sideband.band1.bytes=483 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=483 git.pack.trailer=4ef234d86a93490a6a3da3549aa13a474a5c9eacOpen pack map
fetch2002.0 KiB204 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2077 git.response.cache=MISS git.response.duration_ms=204 git.fetch.wants=672880aa483a985de63653b3c748f51eb904e605 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=2077 git.pkt.payload.max=2050 git.sideband.band1.bytes=2050 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
- a5e13661b8dd18aa
- Request
- f63e05cc…
- 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