GitLabgitlab-org
cli
main
1package update
3import (
4 "context"
5 "errors"
6 "fmt"
7 "net"
8 "net/http"
9 "os"
10 "strings"
11 "time"
13 "github.com/MakeNowJust/heredoc/v2"
14 "github.com/hashicorp/go-version"
15 "github.com/spf13/cobra"
17 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
19 "gitlab.com/gitlab-org/cli/internal/api"
20 "gitlab.com/gitlab-org/cli/internal/binarymgr"
21 "gitlab.com/gitlab-org/cli/internal/binarymgr/binaries"
22 "gitlab.com/gitlab-org/cli/internal/cmdutils"
23 "gitlab.com/gitlab-org/cli/internal/config"
24 "gitlab.com/gitlab-org/cli/internal/glinstance"
25 "gitlab.com/gitlab-org/cli/internal/iostreams"
26 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
27 "gitlab.com/gitlab-org/cli/internal/utils"
28)
30const (
31 defaultProjectURL = "https://gitlab.com/gitlab-org/cli"
32 commandUse = "check-update"
33)
35var commandAliases = []string{"update"}
37func NewCheckUpdateCmd(f cmdutils.Factory) *cobra.Command {
38 cmd := &cobra.Command{
39 Use: commandUse,
40 Short: "Check for the latest glab version.",
41 Long: heredoc.Docf(`
42 Checks for the latest version of glab available on GitLab.com.
44 When you run this command explicitly, glab always checks for updates,
45 even if the previous check was less than 24 hours ago.
47 When glab runs this check automatically after other commands, it
48 checks for updates at most once every 24 hours.
50 When you run this command, glab also reports updates for the GitLab Duo CLI, GitLab Orbit CLI, and GitLab Endpoint Agent Platform (Linux only) binaries, if they are installed.
52 To turn off the automatic update check, run
53 %[1]sglab config set check_update false%[1]s. To turn it back on,
54 run %[1]sglab config set check_update true%[1]s.
55 `, "`"),
56 Example: heredoc.Doc(`
57 # Check for the latest glab version
58 glab check-update
60 # Check for the latest glab version using the alias
61 glab update
62 `),
63 Aliases: commandAliases,
64 Args: cobra.NoArgs,
65 ValidArgsFunction: cobra.NoFileCompletions,
66 Annotations: map[string]string{
67 mcpannotations.Exclude: "true",
68 },
69 RunE: func(cmd *cobra.Command, args []string) error {
70 return CheckUpdateExplicit(cmd.Context(), f)
71 },
72 }
74 return cmd
75}
77// clientCreator is a variable that can be overridden for testing
78var clientCreator = CreateUnauthenticatedClient
80// installMethodDetector is overridable for tests so we don't depend on the
81// filesystem path of the running test binary.
82var installMethodDetector = DetectInstallMethod
84func CheckUpdate(f cmdutils.Factory, silentSuccess bool) error {
85 return checkUpdate(f, silentSuccess, false)
86}
88// CheckUpdateExplicit performs an update check when explicitly invoked by the user.
89// Unlike automatic checks, this bypasses the 24-hour throttle. Managed binaries
90// are only checked here because each one already checks for updates when it runs.
91func CheckUpdateExplicit(ctx context.Context, f cmdutils.Factory) error {
92 if err := checkUpdate(f, false, true); err != nil {
93 return err
94 }
95 for _, spec := range binaries.All() {
96 runner := &binarymgr.Runner{IO: f.IO(), Cfg: f.Config(), Spec: spec, Manager: binarymgr.NewManager(f.IO(), spec)}
97 if err := runner.ReportUpdate(ctx); err != nil {
98 f.IO().LogErrorf("%s %s\n", f.IO().Color().WarnIcon(), err)
99 }
100 }
101 return nil
102}
104func checkUpdate(f cmdutils.Factory, silentSuccess bool, forceCheck bool) error {
105 moreThan24hAgo, err := checkLastUpdate(f, forceCheck)
106 if err != nil {
107 return err
108 }
109 // if the last update check was less than 24h ago we skip the version check
110 // (unless this is a forced check from explicit command invocation)
111 if !moreThan24hAgo {
112 return nil
113 }
115 // Create an unauthenticated API client to check for updates on the public gitlab.com/gitlab-org/cli project.
116 // We explicitly avoid using user credentials since:
117 // 1. The releases endpoint is public and doesn't require authentication
118 // 2. Using user credentials (especially from GITLAB_TOKEN env var) can cause issues
119 // when users have tokens for self-hosted instances that aren't valid for gitlab.com
120 apiClient, err := clientCreator(f.BuildInfo().UserAgent())
121 if err != nil {
122 return err
123 }
124 gitlabClient := apiClient.Lab()
126 releases, _, err := gitlabClient.Releases.ListReleases(
127 "gitlab-org/cli", &gitlab.ListReleasesOptions{ListOptions: gitlab.ListOptions{Page: 1, PerPage: 1}})
128 if err != nil {
129 // When GitLab is down it answers with an HTML maintenance page, and the API
130 // client's error carries the whole page. The status code says enough.
131 if errResp, ok := errors.AsType[*gitlab.ErrorResponse](err); ok {
132 return fmt.Errorf("failed checking for glab updates: %s responded with HTTP %d", glinstance.DefaultHostname, errResp.StatusCode)
133 }
134 return fmt.Errorf("failed checking for glab updates: %s", err.Error())
135 }
136 if len(releases) < 1 {
137 return errors.New("no release found for glab")
138 }
139 latestRelease := releases[0]
140 releaseURL := fmt.Sprintf("%s/-/releases/%s", defaultProjectURL, latestRelease.TagName)
142 buildInfo := f.BuildInfo()
143 version := buildInfo.Version
145 if isOlderVersion(latestRelease.Name, version) {
146 writeUpdateAvailable(f.IO(), version, latestRelease.TagName, releaseURL, installMethodDetector(), buildInfo.CodingAgent)
147 } else if !silentSuccess {
148 c := f.IO().Color()
149 f.IO().LogErrorf("%v",
150 c.Green("You are using the latest version of glab\n"))
151 }
153 // Piggybacks on the 24h throttle so we don't issue one gitlab.com
154 // request per installed remote skill on every command.
155 writeSkillUpdateBlock(f.IO(), remoteSkillUpdates(f.Config()))
156 return nil
157}
159// writeUpdateAvailable renders the "update available" nudge to stderr. When a
160// coding agent is detected it emits a single bracketed line phrased as a
161// suggestion the agent can relay; otherwise it emits a multi-line, colored
162// notice for humans. When the install method is unknown the upgrade-command
163// segments are dropped and only the release-notes URL is shown.
164func writeUpdateAvailable(io *iostreams.IOStreams, currentVersion, latestVersion, releaseURL string, method InstallMethod, codingAgent string) {
165 if codingAgent != "" {
166 writeAgentUpdateLine(io, currentVersion, latestVersion, releaseURL, method)
167 return
168 }
169 writeHumanUpdateBlock(io, currentVersion, latestVersion, releaseURL, method)
170}
172func writeAgentUpdateLine(io *iostreams.IOStreams, currentVersion, latestVersion, releaseURL string, method InstallMethod) {
173 var b strings.Builder
174 fmt.Fprintf(&b, "[glab] Update available: %s → %s", currentVersion, latestVersion) //nolint:forbidigo // writing to strings.Builder, not stdout/stderr
175 if method.UpgradeCommand != "" {
176 fmt.Fprintf(&b, " (installed via %s). Suggested upgrade command: `%s`.", method.Name, method.UpgradeCommand) //nolint:forbidigo // writing to strings.Builder, not stdout/stderr
177 } else {
178 b.WriteString(".")
179 }
180 fmt.Fprintf(&b, " Release notes: %s\n", releaseURL) //nolint:forbidigo // writing to strings.Builder, not stdout/stderr
181 io.LogErrorf("%s", b.String())
182}
184func writeHumanUpdateBlock(io *iostreams.IOStreams, currentVersion, latestVersion, releaseURL string, method InstallMethod) {
185 c := io.Color()
186 // Leading blank line separates the banner from the preceding command
187 // output so the nudge doesn't cram against e.g. `glab mr list` results.
188 io.LogError("")
189 io.LogError(c.Yellow("A new version of glab is available"))
190 io.LogErrorf(" %s → %s\n", c.Red(currentVersion), c.Green(latestVersion))
191 if method.UpgradeCommand != "" {
192 io.LogErrorf(" Run: %s\n", method.UpgradeCommand)
193 }
194 io.LogErrorf(" Release notes: %s\n", releaseURL)
195}
197// CreateUnauthenticatedClient creates an API client without authentication for accessing
198// public endpoints on gitlab.com. This avoids issues where user credentials (especially
199// from environment variables like GITLAB_TOKEN) might be for self-hosted instances
200// and invalid for gitlab.com.
201func CreateUnauthenticatedClient(userAgent string, options ...api.ClientOption) (*api.Client, error) {
202 // Create a client with an empty token for unauthenticated requests
203 opts := []api.ClientOption{
204 api.WithBaseURL(glinstance.APIEndpoint(glinstance.DefaultHostname, glinstance.DefaultProtocol, "", "")),
205 api.WithUserAgent(userAgent),
206 }
207 opts = append(opts, options...)
209 return api.NewClient(
210 func(c *http.Client) (gitlab.AuthSource, error) {
211 // Use AccessTokenAuthSource with empty token for public API access
212 return gitlab.AccessTokenAuthSource{Token: ""}, nil
213 },
214 opts...,
215 )
216}
218// ShouldSkipUpdate decides whether to suppress the post-command update
219// banner, "what's new" nudge, and skill-update check.
220//
221// previousCommand is the raw first argument from
222// `expand.ExpandAlias(cfg, os.Args, nil)`, i.e. `os.Args[1]` after alias
223// expansion — not a parsed `cobra.Command.Name()`. That means flag forms
224// like `-v` and `--version` arrive verbatim and can be matched here
225// (see cmd/glab/main.go where `argCommand := expandedArgs[0]` is the
226// value passed in).
227//
228// Skip reasons:
229// - check-update / update: would re-run the check we just ran, and
230// adds latency to new shells if users set `check_update=false` to
231// avoid it.
232// - completion: same shell-start latency concern.
233// - git-credential / credential-helper: would interfere with Git's
234// credential protocol on stderr.
235// - whatsnew: the user just read the changelog; don't pitch it back.
236// - version / -v / --version: the user just asked "what version do I
237// have?" — trailing the answer with a "what's new" and skill-updates
238// pitch is noise, and also keeps `2>&1`-style automation clean.
239func ShouldSkipUpdate(previousCommand string) bool {
240 isCheckUpdate := previousCommand == commandUse || utils.PresentInStringSlice(commandAliases, previousCommand)
241 isCompletion := previousCommand == "completion"
242 isGitCredential := previousCommand == "git-credential"
243 isCredentialHelper := previousCommand == "credential-helper"
244 isWhatsNew := previousCommand == "whatsnew"
245 isVersion := previousCommand == "version" || previousCommand == "-v" || previousCommand == "--version"
247 return isCheckUpdate || isCompletion || isGitCredential || isCredentialHelper || isWhatsNew || isVersion
248}
250func isOlderVersion(latestVersion, appVersion string) bool {
251 latestVersion = strings.TrimSpace(latestVersion)
252 appVersion = strings.TrimSpace(appVersion)
254 vv, ve := version.NewVersion(latestVersion)
255 vw, we := version.NewVersion(appVersion)
257 return ve == nil && we == nil && vv.GreaterThan(vw)
258}
260// returns true if we should check for updates
261//
262// returns false if we should skip the update check
263//
264// We only want to check for updates once every 24 hours, unless forceCheck is true
265func checkLastUpdate(f cmdutils.Factory, forceCheck bool) (bool, error) {
266 const updateCheckInterval = 24 * time.Hour
267 cfg := f.Config()
269 // We don't care when the command was run if the environment variable is forcing an update
270 // or if this is an explicit command invocation (forceCheck = true)
271 if isEnvForcingUpdate() || forceCheck {
272 if err := updateLastCheckTimestamp(cfg); err != nil {
273 return false, err
274 }
275 return true, nil
276 }
278 last_update, err := cfg.Get("", "last_update_check_timestamp")
279 if err != nil {
280 return false, err
281 }
283 // this might be the first time running the command, so last_update might be empty
284 // we want to save the current time and check for an update
285 if last_update == "" {
286 if err := updateLastCheckTimestamp(cfg); err != nil {
287 return false, err
288 }
289 return true, nil
290 }
292 last_update_time, err := time.Parse(time.RFC3339, last_update)
293 if err != nil {
294 return false, err
295 }
297 // if the last check was more than 24h ago we check for an update
298 moreThan24hAgo := time.Since(last_update_time) > updateCheckInterval
299 if moreThan24hAgo {
300 if err := updateLastCheckTimestamp(cfg); err != nil {
301 return false, err
302 }
303 }
304 return moreThan24hAgo, nil
305}
307// isEnvForcingUpdate - returns true if the environment variable `GLAB_CHECK_UPDATE` is set to true
308func isEnvForcingUpdate() bool {
309 if envVal, ok := os.LookupEnv("GLAB_CHECK_UPDATE"); ok {
310 switch strings.ToUpper(envVal) {
311 case "TRUE", "YES", "Y", "1":
312 return true
313 case "FALSE", "NO", "N", "0":
314 return false
315 }
316 }
317 // if the value is not set or is not a valid value
318 return false
319}
321// updateLastCheckTimestamp - saves the current time as last_update_check_timestamp to config.yml
322func updateLastCheckTimestamp(cfg config.Config) error {
323 if err := cfg.Set("", "last_update_check_timestamp", time.Now().Format(time.RFC3339)); err != nil {
324 return err
325 }
327 if err := cfg.Write(); err != nil {
328 return err
329 }
331 return nil
332}
334// PrintUpdateError prints update check errors with helpful formatting and context.
335// This is specifically for errors that occur during background update checks,
336// not main command execution errors.
337func PrintUpdateError(streams *iostreams.IOStreams, err error, cmd *cobra.Command, debug bool) {
338 color := streams.Color()
340 var dnsError *net.DNSError
341 if errors.As(err, &dnsError) {
342 streams.LogErrorf("%s error connecting to %s\n", color.FailedIcon(), dnsError.Name)
343 if debug {
344 streams.LogError(color.FailedIcon(), dnsError)
345 }
346 streams.LogInfof("%s Check your internet connection and status.gitlab.com. If on GitLab Self-Managed, run 'sudo gitlab-ctl status' on your server.\n", color.DotWarnIcon())
347 } else {
348 var exitError *cmdutils.ExitError
349 if errors.As(err, &exitError) {
350 streams.LogErrorf("%s %s %s=%s\n", color.FailedIcon(), color.Bold(exitError.Details), color.Red("error"), exitError.Err)
351 } else {
352 streams.LogError("ERROR:", err)
354 var flagError *cmdutils.FlagError
355 if errors.As(err, &flagError) || strings.HasPrefix(err.Error(), "unknown command ") {
356 if cmd != nil {
357 streams.LogInfof("Try '%s --help' for more information.", cmd.CommandPath())
358 } else {
359 streams.LogInfof("Try --help for more information.")
360 }
361 }
362 }
363 }
365 if cmd != nil {
366 streams.LogError()
367 }
368}
Diagnostics7 git calls · 291 ms
CallStatusSizeTime0291 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 · 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=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
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:02001.8 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=1857 git.response.cache=HIT git.response.duration_ms=4 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:0200329 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=329 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=8b36f3db012b2c3ab0120649b10a85336c3bf03e 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=329 git.pkt.payload.max=302 git.sideband.band1.bytes=302 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=302 git.pack.trailer=616b294f8a6e9b6163f51633333a4ad7b16f0d98Open pack map
fetch2004.9 KiB278 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=278 git.response.bytes=5010 git.response.cache=MISS git.response.duration_ms=278 git.fetch.wants=396904a8ce83765b2af212f1263408439129e97a 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=5010 git.pkt.payload.max=4983 git.sideband.band1.bytes=4983 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
- a5ea9607bdd007d6
- Request
- 4d1a2e6e…
- 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