GitLabgitlab-org

cli

main
ply6 git calls27 ms98 KiB4 cachedprotocol v2
348 lines9.7 KiBRaw
1package git
3import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
12 "gitlab.com/gitlab-org/cli/internal/config"
13 "gitlab.com/gitlab-org/cli/internal/run"
16// StackLocation returns the path to the stacked metadata directory.
17// It uses git rev-parse --git-common-dir so stacks are shared across all worktrees.
18func StackLocation() (string, error) {
19 commonDir, err := GitCommonDir()
20 if err != nil {
21 return "", fmt.Errorf("finding git common directory: %w", err)
22 }
23 return filepath.Join(commonDir, "stacked"), nil
26const (
27 BaseBranchFile = "BASE_BRANCH"
28 ReorderStateFile = "REORDER_STATE"
31// ReorderState tracks the progress of an in-flight stack reorder so it can
32// be resumed with --continue or rolled back with --abort.
33type ReorderState struct {
34 NewOrder []string `json:"new_order"`
35 NextIndex int `json:"next_index"`
36 OldTips map[string]string `json:"old_tips"`
37 OldParent map[string]string `json:"old_parent"`
38 BaseBranch string `json:"base_branch"`
39 OriginalBranch string `json:"original_branch"`
40 OldRefs map[string]StackRef `json:"old_refs"`
41 NewRefs map[string]StackRef `json:"new_refs"`
44func SetLocalConfig(key, value string) error {
45 found, err := configValueExists(key, value)
46 if err != nil {
47 return fmt.Errorf("Git config value exists: %w", err)
48 }
50 if found {
51 return nil
52 }
54 addCmd := GitCommand("config", "--local", key, value)
55 _, err = run.PrepareCmd(addCmd).Output()
56 if err != nil {
57 return fmt.Errorf("setting local Git config: %w", err)
58 }
59 return nil
62// UnsetLocalConfig removes a key from the repository-local Git config.
63// Git exits with a non-zero status when the key is not set, so check that it
64// has a value before calling this.
65func UnsetLocalConfig(key string) error {
66 unsetCmd := GitCommand("config", "--local", "--unset", key)
67 _, err := run.PrepareCmd(unsetCmd).Output()
68 if err != nil {
69 return fmt.Errorf("unsetting local Git config: %w", err)
70 }
71 return nil
74// The current stack is stored in the per-worktree Git directory because
75// `git config --local` is shared by every linked worktree. The legacy config
76// key is still read as a fallback for repositories set up by older versions.
77const (
78 currentStackFile = "GLAB_CURRENT_STACK"
79 legacyCurrentStackKey = "glab.currentstack"
82// ErrNoCurrentStack is returned when no stack is selected in the current worktree.
83var ErrNoCurrentStack = errors.New("no current stack")
85func currentStackPath() (string, error) {
86 gitDir, err := GitDir()
87 if err != nil {
88 return "", fmt.Errorf("finding Git directory: %w", err)
89 }
90 return filepath.Join(gitDir, currentStackFile), nil
93// GetCurrentStackTitle returns the stack selected in the current worktree.
94func GetCurrentStackTitle() (string, error) {
95 path, err := currentStackPath()
96 if err != nil {
97 return "", err
98 }
100 data, err := os.ReadFile(path)
101 if errors.Is(err, os.ErrNotExist) {
102 return legacyCurrentStackTitle()
103 }
104 if err != nil {
105 return "", fmt.Errorf("reading current stack: %w", err)
106 }
108 title := strings.TrimSpace(string(data))
109 if title == "" {
110 return "", ErrNoCurrentStack
111 }
112 return title, nil
115func legacyCurrentStackTitle() (string, error) {
116 output, err := run.PrepareCmd(GitCommand("config", legacyCurrentStackKey)).Output()
117 if isUnsetConfigKey(err) {
118 return "", ErrNoCurrentStack
119 }
120 if err != nil {
121 return "", fmt.Errorf("reading legacy current stack: %w", err)
122 }
123 return firstLine(output), nil
126// isUnsetConfigKey reports whether `git config <key>` failed only because the
127// key has no value, which Git signals with exit status 1.
128func isUnsetConfigKey(err error) bool {
129 var cmdErr *run.CmdError
130 var exitErr *exec.ExitError
131 return errors.As(err, &cmdErr) && errors.As(cmdErr.Err, &exitErr) && exitErr.ExitCode() == 1
134// SetCurrentStackTitle selects a stack in the current worktree only.
135func SetCurrentStackTitle(title string) error {
136 path, err := currentStackPath()
137 if err != nil {
138 return err
139 }
141 if err := os.WriteFile(path, []byte(title+"\n"), 0o600); err != nil {
142 return fmt.Errorf("writing current stack: %w", err)
143 }
144 return nil
147// ClearCurrentStackTitle leaves the current worktree without a stack. The
148// file is emptied rather than removed so the worktree does not fall back to
149// the legacy config value, which is unset too when it still names title.
150func ClearCurrentStackTitle(title string) error {
151 if err := SetCurrentStackTitle(""); err != nil {
152 return err
153 }
155 legacy, err := run.PrepareCmd(GitCommand("config", "--local", "--get", legacyCurrentStackKey)).Output()
156 if err == nil && firstLine(legacy) == title {
157 return UnsetLocalConfig(legacyCurrentStackKey)
158 }
159 return nil
162func AddStackRefDir(dir string) (string, error) {
163 stackLoc, err := StackLocation()
164 if err != nil {
165 return "", fmt.Errorf("finding stack location: %w", err)
166 }
168 createdDir := filepath.Join(stackLoc, dir)
170 err = os.MkdirAll(createdDir, 0o755)
171 if err != nil {
172 return "", fmt.Errorf("creating stacked diff directory: %w", err)
173 }
175 return createdDir, nil
178// RemoveStackRefDir deletes a stack's metadata directory and everything in it,
179// including the BASE_BRANCH file that remains after the last ref file is gone.
180func RemoveStackRefDir(title string) error {
181 // filepath.Base returns "." and ".." unchanged, so they are rejected explicitly.
182 if title == "" || title == "." || title == ".." || title != filepath.Base(title) {
183 return fmt.Errorf("invalid stack name: %q", title)
184 }
186 stackDir, err := StackRootDir(title)
187 if err != nil {
188 return fmt.Errorf("finding stack location: %w", err)
189 }
191 if err := os.RemoveAll(stackDir); err != nil {
192 return fmt.Errorf("removing stacked diff directory: %w", err)
193 }
195 return nil
198func StackRootDir(title string) (string, error) {
199 stackLoc, err := StackLocation()
200 if err != nil {
201 return "", err
202 }
204 return filepath.Join(stackLoc, title), nil
207func AddStackRefFile(title string, stackRef StackRef) error {
208 refDir, err := StackRootDir(title)
209 if err != nil {
210 return fmt.Errorf("error determining Git root: %w", err)
211 }
213 initialJsonData, err := json.Marshal(stackRef) //nolint:forbidigo // stack reference is written to disk, not stdout
214 if err != nil {
215 return fmt.Errorf("error marshaling data: %w", err)
216 }
218 if _, err = os.Stat(refDir); os.IsNotExist(err) {
219 err = os.MkdirAll(refDir, 0o700) // create directory if it doesn't exist
220 if err != nil {
221 return fmt.Errorf("error creating directory: %w", err)
222 }
223 }
225 fullPath := filepath.Join(refDir, stackRef.SHA+".json")
227 err = os.WriteFile(fullPath, initialJsonData, 0o644)
228 if err != nil {
229 return fmt.Errorf("error running writing file: %w", err)
230 }
232 return nil
235func DeleteStackRefFile(title string, stackRef StackRef) error {
236 refDir, err := StackRootDir(title)
237 if err != nil {
238 return fmt.Errorf("error determining Git root: %w", err)
239 }
241 fullPath := filepath.Join(refDir, stackRef.SHA+".json")
243 err = os.Remove(fullPath)
244 if err != nil {
245 return fmt.Errorf("error removing stack file: %w", err)
246 }
248 return nil
251func UpdateStackRefFile(title string, s StackRef) error {
252 refDir, err := StackRootDir(title)
253 if err != nil {
254 return fmt.Errorf("error determining Git root: %w", err)
255 }
257 fullPath := filepath.Join(refDir, s.SHA+".json")
259 initialJsonData, err := json.Marshal(s) //nolint:forbidigo // stack ref file is written to disk, not stdout
260 if err != nil {
261 return fmt.Errorf("error marshaling data: %w", err)
262 }
264 err = os.WriteFile(fullPath, initialJsonData, 0o644)
265 if err != nil {
266 return fmt.Errorf("error writing file: %w", err)
267 }
269 return nil
272// WriteReorderState persists the reorder state for the given stack to the
273// REORDER_STATE file.
274func WriteReorderState(title string, state ReorderState) error {
275 root, err := StackRootDir(title)
276 if err != nil {
277 return fmt.Errorf("could not determine stack root: %w", err)
278 }
279 data, err := json.MarshalIndent(state, "", " ") //nolint:forbidigo // reorder state is written to disk, not stdout
280 if err != nil {
281 return fmt.Errorf("could not marshal reorder state: %w", err)
282 }
283 return config.WriteFile(filepath.Join(root, ReorderStateFile), data, 0o644)
286// ReadReorderState loads the reorder state for the given stack. It returns an
287// error satisfying errors.Is(err, os.ErrNotExist) when no reorder is in progress.
288func ReadReorderState(title string) (ReorderState, error) {
289 root, err := StackRootDir(title)
290 if err != nil {
291 return ReorderState{}, err
292 }
293 data, err := os.ReadFile(filepath.Join(root, ReorderStateFile))
294 if err != nil {
295 return ReorderState{}, err
296 }
297 var state ReorderState
298 if err := json.Unmarshal(data, &state); err != nil {
299 return ReorderState{}, fmt.Errorf("could not parse reorder state: %w", err)
300 }
301 return state, nil
304// DeleteReorderState removes the REORDER_STATE file for the given stack.
305func DeleteReorderState(title string) error {
306 root, err := StackRootDir(title)
307 if err != nil {
308 return err
309 }
310 return os.Remove(filepath.Join(root, ReorderStateFile))
313// ReorderInProgress returns true if a REORDER_STATE file exists for the
314// given stack title. Other stack commands should call this to block
315// operations while a reorder is in progress.
316func ReorderInProgress(title string) (bool, error) {
317 root, err := StackRootDir(title)
318 if err != nil {
319 return false, err
320 }
321 _, err = os.Stat(filepath.Join(root, ReorderStateFile))
322 if err == nil {
323 return true, nil
324 }
325 if errors.Is(err, os.ErrNotExist) {
326 return false, nil
327 }
328 return false, err
331func GetStacks() ([]Stack, error) {
332 stackLocationDir, err := StackLocation()
333 if err != nil {
334 return nil, err
335 }
336 entries, err := os.ReadDir(stackLocationDir)
337 if err != nil {
338 return nil, err
339 }
340 var stacks []Stack
341 for _, v := range entries {
342 if !v.IsDir() {
343 continue
344 }
345 stacks = append(stacks, Stack{Title: v.Name()})
346 }
347 return stacks, nil
Diagnostics6 git calls · 27 ms
CallStatusSizeTime027 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=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 KiB2 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=UPDATING
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 · hit2 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=32926
git.response.cache=HIT
git.response.duration_ms=2
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
fetchcombine:blob:none+tree:2 · deepen 12004.2 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=4273
git.response.cache=HIT
git.response.duration_ms=4
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=17
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=4ef234d86a93490a6a3da3549aa13a474a5c9eac
Open pack map
fetch2002.7 KiB · hit17 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=2787
git.response.cache=HIT
git.response.duration_ms=17
git.fetch.wants=a0632feb28279bb6cde4391418b49df19fcd00dc
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=2787
git.pkt.payload.max=2760
git.sideband.band1.bytes=2760
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
a5e19b73bdebb86e
Request
5e014bda…
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