GitLabgitlab-org
cli
main
1package git
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "regexp"
13 "strings"
15 "gitlab.com/gitlab-org/cli/internal/run"
16)
18type GitRunner interface {
19 Git(args ...string) (string, error)
20 // GitWithIO runs git with the provided stdout and stderr writers attached
21 // directly to the subprocess, allowing live output (progress bars, errors)
22 // to reach the user during long-running operations like fetch and checkout.
23 GitWithIO(stdout, stderr io.Writer, args ...string) error
24}
26// Executor is a subset of cmdutils.Executor defined here to avoid a circular
27// import: the cmdutils package already imports the git package.
28type Executor interface {
29 ExecWithIO(ctx context.Context, name string, args []string, env []string, stdin io.Reader, stdout, stderr io.Writer) error
30}
32type StandardGitCommand struct {
33 executor Executor
34}
36func NewGitCommand(executor Executor) StandardGitCommand {
37 return StandardGitCommand{executor: executor}
38}
40func (gitc StandardGitCommand) Git(args ...string) (string, error) {
41 env := append(os.Environ(), "LC_ALL=C")
43 if gitc.executor == nil {
44 cmd := GitCommand(args...)
45 cmd.Env = env
46 output, err := run.PrepareCmd(cmd).Output()
47 if err != nil {
48 return "", err
49 }
50 return string(output), nil
51 }
53 var stdout, stderr bytes.Buffer
54 err := gitc.executor.ExecWithIO(context.Background(), "git", args, env, nil, &stdout, &stderr)
55 if err != nil {
56 errMsg := strings.TrimSpace(stderr.String())
57 if errMsg != "" {
58 return "", fmt.Errorf("%s: %w", errMsg, err)
59 }
60 return "", err
61 }
62 return stdout.String(), nil
63}
65func (gitc StandardGitCommand) GitWithIO(stdout, stderr io.Writer, args ...string) error {
66 env := append(os.Environ(), "LC_ALL=C")
68 if gitc.executor == nil {
69 var stderrBuf bytes.Buffer
70 cmd := GitCommand(args...)
71 cmd.Env = env
72 cmd.Stdout = stdout
73 cmd.Stderr = io.MultiWriter(stderr, &stderrBuf)
74 if err := cmd.Run(); err != nil {
75 if msg := strings.TrimSpace(stderrBuf.String()); msg != "" {
76 return fmt.Errorf("%s: %w", msg, err)
77 }
78 return err
79 }
80 return nil
81 }
83 return gitc.executor.ExecWithIO(context.Background(), "git", args, env, nil, stdout, stderr)
84}
86const (
87 DefaultBranchName = "main"
88)
90// headBranchRegex is used to parse the default branch from git remote output
91var headBranchRegex = regexp.MustCompile(`HEAD branch:\s+(.+)`)
93type (
94 Git interface {
95 CheckoutBranch(branch string) error
96 CheckoutNewBranch(branch string) error
97 CurrentBranch() (string, error)
98 DeleteLocalBranch(branch string) error
99 DefaultBranch(remote string) (string, error)
100 RemoteBranchExists(remote string, branch string) (bool, error)
101 UncommittedChangeCount() (int, error)
102 UserName() (string, error)
103 LatestCommit(ref string) (*Commit, error)
104 Commits(baseRef, headRef string) ([]*Commit, error)
105 CommitBody(sha string) (string, error)
106 Push(remote string, ref string) error
107 HasLocalBranch(branch string) (bool, error)
108 }
110 StandardGitRunner struct {
111 gitBinary string
112 }
113)
115var _ Git = (*StandardGitRunner)(nil)
117func NewStandardGitRunner(gitBinary string) *StandardGitRunner {
118 if gitBinary == "" {
119 gitBinary = "git" // default to using "git" from PATH
120 }
121 return &StandardGitRunner{gitBinary: gitBinary}
122}
124// CurrentBranch reads the checked-out branch for the git repository
125func (g *StandardGitRunner) CurrentBranch() (string, error) {
126 stdout, stderr, err := g.runGitCommand("symbolic-ref", "--quiet", "--short", "HEAD")
127 if err == nil {
128 before, _ := bytes.CutSuffix(stdout, []byte("\n"))
129 return string(before), nil
130 }
131 var cmdErr *run.CmdError
132 if errors.As(err, &cmdErr) {
133 if cmdErr.Stderr.Len() == 0 {
134 return "", ErrNotOnAnyBranch // Detached HEAD error
135 }
136 }
137 return "", fmt.Errorf("unknown error getting current branch: %w - %s", err, stderr)
138}
140// DefaultBranch gets the default branch for a remote
141func (g *StandardGitRunner) DefaultBranch(remote string) (string, error) {
142 stdout, stderr, err := g.runGitCommand("remote", "show", remote)
143 if err != nil {
144 return DefaultBranchName, fmt.Errorf("could not get default branch for remote %s: %w - %s", remote, err, stderr)
145 }
147 defaultBranch, err := parseDefaultBranch(stdout)
148 if err != nil {
149 return DefaultBranchName, fmt.Errorf("could not parse default branch for remote %s: %w", remote, err)
150 }
152 return defaultBranch, nil
153}
155// DeleteLocalBranch deletes a local git branch
156func (g *StandardGitRunner) DeleteLocalBranch(branch string) error {
157 _, stderr, err := g.runGitCommand("branch", "-D", branch)
158 if err != nil {
159 return fmt.Errorf("could not delete local branch %s: %w - %s", branch, err, stderr)
160 }
161 return nil
162}
164// CheckoutBranch switches to an existing branch
165func (g *StandardGitRunner) CheckoutBranch(branch string) error {
166 _, stderr, err := g.runGitCommand("checkout", branch)
167 if err != nil {
168 return fmt.Errorf("could not checkout branch %s: %w - %s", branch, err, stderr)
169 }
170 return nil
171}
173// RemoteBranchExists checks if a remote branch exists
174func (g *StandardGitRunner) RemoteBranchExists(remote string, branch string) (bool, error) {
175 _, _, err := g.runGitCommand("ls-remote", "--exit-code", "--heads", remote, branch)
176 return err == nil, nil // this is either true or false, really
177}
179// CheckoutNewBranch creates and checks out a new branch
180func (g *StandardGitRunner) CheckoutNewBranch(branch string) error {
181 _, stderr, err := g.runGitCommand("checkout", "-b", branch)
182 if err != nil {
183 return fmt.Errorf("could not create new branch: %w - %s", err, stderr)
184 }
185 return nil
186}
188// UncommittedChangeCount returns the number of uncommitted changes
189func (g *StandardGitRunner) UncommittedChangeCount() (int, error) {
190 stdout, stderr, err := g.runGitCommand("status", "--porcelain")
191 if err != nil {
192 return 0, fmt.Errorf("could not get status: %w - %s", err, stderr)
193 }
195 lines := strings.Split(string(stdout), "\n")
196 count := 0
197 for _, l := range lines {
198 if l != "" {
199 count++
200 }
201 }
202 return count, nil
203}
205// UserName gets the git user name
206func (g *StandardGitRunner) UserName() (string, error) {
207 stdout, stderr, err := g.runGitCommand("config", "user.name")
208 if err != nil {
209 return "", fmt.Errorf("could not get user name: %w - %s", err, stderr)
210 }
211 return string(stdout), nil
212}
214// LatestCommit gets the latest commit for a ref
215func (g *StandardGitRunner) LatestCommit(ref string) (*Commit, error) {
216 stdout, stderr, err := g.runGitCommand("show", "-s", "--format=%h %s", ref)
217 if err != nil {
218 return &Commit{}, fmt.Errorf("could not get latest commit: %w - %s", err, stderr)
219 }
221 output := strings.TrimSpace(string(stdout))
222 sha, title, ok := strings.Cut(output, " ")
223 if !ok || sha == "" || title == "" {
224 return &Commit{}, fmt.Errorf("could not parse commit for %s: unexpected format %q", ref, string(stdout))
225 }
227 return &Commit{
228 Sha: sha,
229 Title: title,
230 }, nil
231}
233// Commits gets commits between two refs
234func (g *StandardGitRunner) Commits(baseRef, headRef string) ([]*Commit, error) {
235 stdout, stderr, err := g.runGitCommand(
236 "-c", "log.ShowSignature=false",
237 "log", "--pretty=format:%H,%s",
238 "--cherry", fmt.Sprintf("%s...%s", baseRef, headRef))
239 if err != nil {
240 return nil, fmt.Errorf("could not get commits: %w - %s", err, stderr)
241 }
243 var commits []*Commit
244 for _, line := range outputLines(stdout) {
245 split := strings.SplitN(line, ",", 2)
246 if len(split) != 2 {
247 continue
248 }
249 commits = append(commits, &Commit{
250 Sha: split[0],
251 Title: split[1],
252 })
253 }
255 if len(commits) == 0 {
256 return commits, fmt.Errorf("could not find any commits between %s and %s", baseRef, headRef)
257 }
259 return commits, nil
260}
262// CommitBody gets the body of a commit
263func (g *StandardGitRunner) CommitBody(sha string) (string, error) {
264 stdout, stderr, err := g.runGitCommand("-c", "log.ShowSignature=false", "show", "-s", "--pretty=format:%b", sha)
265 if err != nil {
266 return "", fmt.Errorf("could not get commit body: %w - %s", err, stderr)
267 }
268 return string(stdout), nil
269}
271// Push publishes a git ref to a remote
272func (g *StandardGitRunner) Push(remote string, ref string) error {
273 _, stderr, err := g.runGitCommand("push", remote, ref)
274 if err != nil {
275 return fmt.Errorf("could not push: %w - %s", err, stderr)
276 }
277 return nil
278}
280// HasLocalBranch checks if a local branch exists
281func (g *StandardGitRunner) HasLocalBranch(branch string) (bool, error) {
282 _, stderr, err := g.runGitCommand("rev-parse", "--verify", "refs/heads/"+branch)
283 if err == nil {
284 return true, nil
285 }
287 // git rev-parse exits with code 128 when the ref doesn't exist
288 var cmdErr *run.CmdError
289 if errors.As(err, &cmdErr) {
290 // if stderr contains "fatal: Needed a single revision", it means the branch doesn't exist
291 // this is expected behavior, not an error
292 if strings.Contains(stderr, "fatal: Needed a single revision") ||
293 strings.Contains(stderr, "fatal: ambiguous argument") {
294 return false, nil
295 }
296 }
298 // otherwise, this is an actual error
299 return false, fmt.Errorf("failed to check if branch %s exists: %w - %s", branch, err, stderr)
300}
302// runGitCommand executes a git command with proper environment setup and returns stdout/stderr
303func (g *StandardGitRunner) runGitCommand(args ...string) ([]byte, string, error) {
304 cmd := exec.Command(g.gitBinary, args...)
306 var stdout, stderr bytes.Buffer
307 cmd.Stdout = &stdout
308 cmd.Stderr = &stderr
310 // ensure output from git is in English for string matching
311 cmd.Env = os.Environ()
312 cmd.Env = append(cmd.Env, "LC_ALL=C")
314 err := cmd.Run()
315 return stdout.Bytes(), stderr.String(), err
316}
318// parseDefaultBranch parses the default branch from git remote output
319func parseDefaultBranch(output []byte) (string, error) {
320 scanner := bufio.NewScanner(bytes.NewReader(output))
322 // try to find "HEAD branch:" line
323 for scanner.Scan() {
324 line := scanner.Text()
325 if matches := headBranchRegex.FindStringSubmatch(line); len(matches) > 1 {
326 return strings.TrimSpace(matches[1]), nil
327 }
328 }
330 // if scanner encountered an error
331 if err := scanner.Err(); err != nil {
332 return "", fmt.Errorf("error scanning output: %w", err)
333 }
335 // reset scanner to look for branch marked with (HEAD)
336 scanner = bufio.NewScanner(bytes.NewReader(output))
337 for scanner.Scan() {
338 line := strings.TrimSpace(scanner.Text())
339 if strings.Contains(line, "(HEAD)") {
340 parts := strings.Fields(line)
341 if len(parts) > 0 {
342 return parts[0], nil
343 }
344 }
345 }
347 // couldn't find HEAD branch(?)
348 return "", errors.New("could not determine default branch from remote output")
349}
Diagnostics6 git calls · 261 ms
CallStatusSizeTime0261 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
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=3 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
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit5 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=5 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=5 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:0200510 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=510 git.response.cache=HIT git.response.duration_ms=3 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
fetch2003.1 KiB251 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=251 git.response.bytes=3127 git.response.cache=MISS git.response.duration_ms=251 git.fetch.wants=ae85c800dd31869b7ea53625594adcf883a6552d 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=3127 git.pkt.payload.max=3100 git.sideband.band1.bytes=3100 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
- a5e122301b687fd8
- Request
- 0ee407e7…
- 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