GitLabgitlab-org

cli

main
ply6 git calls28 ms99 KiB5 cachedprotocol v2
430 lines14 KiBRaw
1package binarymgr
3import (
4 "context"
5 "errors"
6 "fmt"
7 "os"
8 "time"
10 "github.com/hashicorp/go-version"
12 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
14 "gitlab.com/gitlab-org/cli/internal/config"
15 "gitlab.com/gitlab-org/cli/internal/iostreams"
18// Executor runs the resolved binary with the given args. The binarymgr
19// package leaves this to consumers because the right strategy is
20// platform-specific (syscall.Exec on Unix, subprocess on Windows) and may
21// also need to inject distribution-specific environment variables.
22type Executor func(ctx context.Context, binaryPath string, args []string) error
24// Runner orchestrates the per-invocation lifecycle: ensure the binary is
25// installed, prompt for run consent, save metadata, schedule a background
26// update check, then hand off to Executor.
27type Runner struct {
28 IO *iostreams.IOStreams
29 Cfg config.Config
30 Spec Spec
31 Manager *Manager
32 Executor Executor
34 // Update / Install / Yes mirror the glab-owned flags after the
35 // caller has parsed them out of the cobra args. Args holds the
36 // remaining pass-through args destined for the managed binary.
37 Update bool
38 Install bool
39 Yes bool
40 Args []string
43// updateCheckResult is the outcome of an update check.
44type updateCheckResult struct {
45 hasUpdate bool
46 currentVersion string
47 latestVersion string
48 newMajorVersion string
51// Run executes the default flow: ensure installed, prompt for consent (when
52// needed), and exec the binary with Args.
53func (r *Runner) Run(ctx context.Context) error {
54 managedPath, err := ManagedBinaryPath(r.Spec)
55 if err != nil {
56 return err
57 }
59 installedPath, _ := r.Cfg.Get("", r.Spec.configKey("binary_path"))
61 if installedPath != "" && installedPath != managedPath && r.Update {
62 color := r.IO.Color()
63 r.IO.LogInfof("%s Updates are not applicable when using a custom binary path (%s).\n", color.DotWarnIcon(), installedPath)
64 return nil
65 }
67 if r.Update {
68 return r.HandleUpdate(ctx)
69 }
71 installedVersion, _ := r.Cfg.Get("", r.Spec.configKey("binary_version"))
72 installedVersion = r.versionAfterFloor(installedVersion, installedPath, managedPath)
73 autoDownload, _ := r.Cfg.Get("", r.Spec.configKey("auto_download"))
74 if r.Yes {
75 autoDownload = "true"
76 }
78 result, err := r.Manager.EnsureInstalled(ctx, installedVersion, installedPath, autoDownload)
79 if err != nil {
80 return err
81 }
82 info := result.Info
84 if info.Path == managedPath {
85 r.saveAutoDownloadPreference(result.AutoDownloadPreference)
86 if result.Downloaded {
87 r.saveLastUpdateCheck(time.Now())
88 }
89 if err := r.SaveBinaryInfo(info); err != nil {
90 r.warnf("Failed to save binary metadata: %v", err)
91 }
92 r.checkForUpdates(ctx)
93 } else {
94 color := r.IO.Color()
95 r.IO.LogErrorf("%s Using custom %s binary: %s\n", color.DotWarnIcon(), r.Spec.DisplayName, info.Path)
96 }
98 if !r.Yes {
99 if err := r.checkAutoRun(ctx); err != nil {
100 return err
101 }
102 }
104 return r.Executor(ctx, info.Path, r.Args)
107// HandleInstall installs (or refreshes) the managed binary without running
108// it. If the user has configured a custom path, the path is reported and
109// nothing is downloaded.
110func (r *Runner) HandleInstall(ctx context.Context) error {
111 managedPath, err := ManagedBinaryPath(r.Spec)
112 if err != nil {
113 return err
114 }
116 installedVersion, _ := r.Cfg.Get("", r.Spec.configKey("binary_version"))
117 installedPath, _ := r.Cfg.Get("", r.Spec.configKey("binary_path"))
118 installedVersion = r.versionAfterFloor(installedVersion, installedPath, managedPath)
119 autoDownload, _ := r.Cfg.Get("", r.Spec.configKey("auto_download"))
120 if r.Yes {
121 autoDownload = "true"
122 }
124 result, err := r.Manager.EnsureInstalled(ctx, installedVersion, installedPath, autoDownload)
125 if err != nil {
126 return err
127 }
128 info := result.Info
130 if info.Path != managedPath {
131 color := r.IO.Color()
132 r.IO.LogInfof("%s Using custom %s binary: %s\n", color.DotWarnIcon(), r.Spec.DisplayName, info.Path)
133 return nil
134 }
136 if installedVersion != "" && info.Version == installedVersion {
137 color := r.IO.Color()
138 r.IO.LogInfof("%s %s version %s is already installed.\n", color.GreenCheck(), r.Spec.DisplayName, installedVersion)
139 return nil
140 }
142 r.saveAutoDownloadPreference(result.AutoDownloadPreference)
143 r.saveLastUpdateCheck(time.Now())
144 return r.SaveBinaryInfo(info)
147// HandleUpdate forces an update check and applies any newer compatible
148// version. If nothing is installed yet, it falls back to a fresh install.
149func (r *Runner) HandleUpdate(ctx context.Context) error {
150 result, err := r.performUpdateCheck(ctx, true)
151 if err != nil {
152 return fmt.Errorf("failed to check for updates: %w", err)
153 }
155 if result == nil {
156 r.IO.LogError("No version installed, downloading latest...")
157 installedVersion, _ := r.Cfg.Get("", r.Spec.configKey("binary_version"))
158 installedPath, _ := r.Cfg.Get("", r.Spec.configKey("binary_path"))
159 autoDownload, _ := r.Cfg.Get("", r.Spec.configKey("auto_download"))
160 if r.Yes {
161 autoDownload = "true"
162 }
163 result, err := r.Manager.EnsureInstalled(ctx, installedVersion, installedPath, autoDownload)
164 if err != nil {
165 return err
166 }
167 r.saveAutoDownloadPreference(result.AutoDownloadPreference)
168 r.saveLastUpdateCheck(time.Now())
169 return r.SaveBinaryInfo(result.Info)
170 }
172 if !result.hasUpdate {
173 color := r.IO.Color()
174 r.IO.LogInfof("%s You are already using the latest compatible version (%s)\n", color.GreenCheck(), result.currentVersion)
175 if result.newMajorVersion != "" {
176 r.IO.LogInfof("%s %s %s is available but requires a newer version of glab.\n", color.DotWarnIcon(), r.Spec.DisplayName, result.newMajorVersion)
177 r.IO.LogInfof("Run 'glab check-update' to check for the latest glab version.\n")
178 }
179 return nil
180 }
182 r.IO.LogInfof("Update available: %s → %s\n", result.currentVersion, result.latestVersion)
184 info, err := r.Manager.Update(ctx)
185 if err != nil {
186 return fmt.Errorf("failed to update: %w", err)
187 }
189 if err := r.SaveBinaryInfo(info); err != nil {
190 r.warnf("Failed to save binary metadata: %v", err)
191 }
193 color := r.IO.Color()
194 r.IO.LogInfof("%s Successfully updated to version %s\n", color.GreenCheck(), result.latestVersion)
195 return nil
198// SaveBinaryInfo writes path/version/checksum to config and persists.
199func (r *Runner) SaveBinaryInfo(info *BinaryInfo) error {
200 if err := r.Cfg.Set("", r.Spec.configKey("binary_path"), info.Path); err != nil {
201 return err
202 }
203 if err := r.Cfg.Set("", r.Spec.configKey("binary_version"), info.Version); err != nil {
204 return err
205 }
206 if err := r.Cfg.Set("", r.Spec.configKey("binary_checksum"), info.Checksum); err != nil {
207 return err
208 }
209 return r.Cfg.Write()
212// ShouldForceUpdateCheck returns true when the spec's force-update env var
213// is "true". Useful for tests and CI that want to bypass the 24h cache.
214func (r *Runner) ShouldForceUpdateCheck() bool {
215 return os.Getenv(r.Spec.envVar("CHECK_UPDATE")) == "true"
218// InstallStatus describes the binary Run would exec without a download.
219type InstallStatus struct {
220 Path string
221 Version string
222 Installed bool
225// InstalledBinary resolves the binary the way Run does, but never prompts, downloads, or logs.
226// Config read errors are returned together with a best-effort status so the caller picks the fallback.
227func InstalledBinary(cfg config.Config, spec Spec) (InstallStatus, error) {
228 var errs []error
229 read := func(suffix string) string {
230 value, err := cfg.Get("", spec.configKey(suffix))
231 if err != nil {
232 errs = append(errs, fmt.Errorf("reading %s: %w", spec.configKey(suffix), err))
233 }
234 return value
235 }
236 path := read("binary_path")
237 version := read("binary_version")
238 managedPath, managedErr := ManagedBinaryPath(spec)
240 status := InstallStatus{Path: path, Version: version}
241 if path != "" && path != managedPath {
242 status.Installed = validateBinaryPath(path, spec) == nil
243 return status, errors.Join(errs...)
244 }
245 status.Path = managedPath
246 status.Installed = version != "" && !spec.belowFloor(version) && isBinaryValid(managedPath)
247 return status, errors.Join(append(errs, managedErr)...)
250func (s Spec) belowFloor(installedVersion string) bool {
251 if s.MinVersion == "" || installedVersion == "" {
252 return false
253 }
254 floor, err := version.NewVersion(s.MinVersion)
255 if err != nil {
256 return false
257 }
258 installed, err := version.NewVersion(installedVersion)
259 return err == nil && installed.LessThan(floor)
262func (r *Runner) versionAfterFloor(installedVersion, installedPath, managedPath string) string {
263 if installedPath != "" && installedPath != managedPath {
264 return installedVersion
265 }
266 if !r.Spec.belowFloor(installedVersion) {
267 return installedVersion
268 }
269 color := r.IO.Color()
270 r.IO.LogErrorf("%s Installed %s version %s is older than the required %s\n", color.DotWarnIcon(), r.Spec.DisplayName, installedVersion, r.Spec.MinVersion)
271 return ""
274func (r *Runner) performUpdateCheck(ctx context.Context, forceCheck bool) (*updateCheckResult, error) {
275 currentVersion, _ := r.Cfg.Get("", r.Spec.configKey("binary_version"))
276 if currentVersion == "" {
277 return nil, nil
278 }
280 lastCheckStr, _ := r.Cfg.Get("", r.Spec.configKey("last_update_check"))
281 var lastCheckTime time.Time
282 if lastCheckStr != "" {
283 lastCheckTime, _ = time.Parse(time.RFC3339, lastCheckStr)
284 }
286 check, err := r.Manager.CheckForUpdate(ctx, currentVersion, lastCheckTime, forceCheck)
287 // A failed check is stamped too, so an unreachable registry costs one timeout per day, not one per run.
288 if !check.NewCheckTime.IsZero() {
289 if err := r.Cfg.Set("", r.Spec.configKey("last_update_check"), check.NewCheckTime.Format(time.RFC3339)); err != nil {
290 r.warnf("Failed to save update check time: %v", err)
291 }
292 if err := r.Cfg.Write(); err != nil {
293 r.warnf("Failed to write config: %v", err)
294 }
295 }
297 if err != nil {
298 return nil, err
299 }
301 return &updateCheckResult{
302 hasUpdate: check.HasUpdate,
303 currentVersion: currentVersion,
304 latestVersion: check.LatestVersion,
305 newMajorVersion: check.NewMajorVersion,
306 }, nil
309func (r *Runner) checkAutoRun(ctx context.Context) error {
310 autoRun, _ := r.Cfg.Get("", r.Spec.configKey("auto_run"))
311 if autoRun == "true" {
312 return nil
313 }
315 if !r.IO.CanPrompt() {
316 return nil
317 }
319 confirm := true
320 if err := r.IO.Confirm(ctx, &confirm, fmt.Sprintf("Run the %s?", r.Spec.DisplayName)); err != nil {
321 return err
322 }
323 if !confirm {
324 return errors.New("execution cancelled")
325 }
327 var always bool
328 if err := r.IO.Confirm(ctx, &always, "Always run without prompting?"); err != nil {
329 r.warnf("Failed to get auto-run preference: %v", err)
330 return nil
331 }
333 if always {
334 if err := r.Cfg.Set("", r.Spec.configKey("auto_run"), "true"); err != nil {
335 r.warnf("Failed to save preference: %v", err)
336 }
337 if err := r.Cfg.Write(); err != nil {
338 r.warnf("Failed to write config: %v", err)
339 }
340 }
341 return nil
344// ReportUpdate prints the update notice for the managed binary without the
345// 24-hour throttle. It stays silent on an unsupported platform and for a
346// binary that is not installed or is custom, since glab updates none of them.
347// Unlike InstalledBinary, it reports a binary below Spec.MinVersion, since
348// that user needs the update most.
349func (r *Runner) ReportUpdate(ctx context.Context) error {
350 managedPath, err := ManagedBinaryPath(r.Spec)
351 if errors.Is(err, ErrUnsupportedPlatform) {
352 return nil
353 }
354 if err != nil {
355 return fmt.Errorf("failed checking for %s updates: %w", r.Spec.DisplayName, err)
356 }
357 installedPath, _ := r.Cfg.Get("", r.Spec.configKey("binary_path"))
358 installedVersion, _ := r.Cfg.Get("", r.Spec.configKey("binary_version"))
359 if installedPath != "" && installedPath != managedPath {
360 return nil
361 }
362 if installedVersion == "" || !isBinaryValid(managedPath) {
363 return nil
364 }
366 result, err := r.performUpdateCheck(ctx, true)
367 if err != nil {
368 // An outage answers with an HTML page that the error carries in full.
369 if errResp, ok := errors.AsType[*gitlab.ErrorResponse](err); ok {
370 return fmt.Errorf("failed checking for %s updates: the package registry responded with HTTP %d", r.Spec.DisplayName, errResp.StatusCode)
371 }
372 return fmt.Errorf("failed checking for %s updates: %w", r.Spec.DisplayName, err)
373 }
374 r.printUpdateNotice(result)
375 return nil
378func (r *Runner) checkForUpdates(ctx context.Context) {
379 result, err := r.performUpdateCheck(ctx, r.ShouldForceUpdateCheck())
380 if err != nil || result == nil {
381 return
382 }
383 r.printUpdateNotice(result)
386func (r *Runner) printUpdateNotice(result *updateCheckResult) {
387 color := r.IO.Color()
388 if result.hasUpdate {
389 r.IO.LogErrorf("\n%s New %s version available: %s → %s\n", color.DotWarnIcon(), r.Spec.DisplayName, result.currentVersion, result.latestVersion)
390 r.IO.LogErrorf("Run 'glab %s update' to update to the latest version\n", r.Spec.Command)
391 }
392 if result.newMajorVersion != "" {
393 r.IO.LogErrorf("\n%s %s %s is available but requires a newer version of glab.\n", color.DotWarnIcon(), r.Spec.DisplayName, result.newMajorVersion)
394 r.IO.LogErrorf("Run 'glab check-update' to check for the latest glab version.\n")
395 }
398// saveAutoDownloadPreference persists the user's "always download updates"
399// choice. EnsureInstalled returns "true" when the user opted in during the
400// follow-up prompt and "" otherwise; we only write on opt-in so this is a
401// no-op for the common case.
402func (r *Runner) saveAutoDownloadPreference(pref string) {
403 if pref == "" {
404 return
405 }
406 if err := r.Cfg.Set("", r.Spec.configKey("auto_download"), pref); err != nil {
407 r.warnf("Failed to save preference: %v", err)
408 return
409 }
410 if err := r.Cfg.Write(); err != nil {
411 r.warnf("Failed to write config: %v", err)
412 }
415// saveLastUpdateCheck stamps the moment a known-current install was placed
416// on disk so the next interactive run skips the redundant registry hit.
417func (r *Runner) saveLastUpdateCheck(t time.Time) {
418 if err := r.Cfg.Set("", r.Spec.configKey("last_update_check"), t.Format(time.RFC3339)); err != nil {
419 r.warnf("Failed to save update check time: %v", err)
420 return
421 }
422 if err := r.Cfg.Write(); err != nil {
423 r.warnf("Failed to write config: %v", err)
424 }
427func (r *Runner) warnf(format string, args ...any) {
428 color := r.IO.Color()
429 r.IO.LogErrorf("%s "+format+"\n", append([]any{color.DotWarnIcon()}, args...)...)
Diagnostics6 git calls · 28 ms
CallStatusSizeTime028 ms
discover200185 B1 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=1
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 · hit1 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=1
git.response.bytes=59849
git.response.cache=HIT
git.response.duration_ms=1
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=2
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=4
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:0200528 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=528
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=6f25b436c20690dd9e61e310cecb2c93d3671017
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=528
git.pkt.payload.max=501
git.sideband.band1.bytes=501
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=501
git.pack.trailer=3f78362ab585c40c9cff18b66b4df6f87bfba2d8
Open pack map
fetch2003.8 KiB · hit21 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=21
git.response.bytes=3888
git.response.cache=HIT
git.response.duration_ms=21
git.fetch.wants=97e7edfb8c9759268d929214f98553593efff2af
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=3888
git.pkt.payload.max=3861
git.sideband.band1.bytes=3861
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
a5e1300acbada9fe
Request
5958011f…
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