GitLabgitlab-org
cli
main
1package status
3import (
4 "fmt"
5 "time"
7 "charm.land/huh/v2"
8 "github.com/MakeNowJust/heredoc/v2"
9 "github.com/gosuri/uilive"
10 "github.com/spf13/cobra"
12 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
14 "gitlab.com/gitlab-org/cli/internal/cmdutils"
15 "gitlab.com/gitlab-org/cli/internal/commands/ci/ciutils"
16 "gitlab.com/gitlab-org/cli/internal/dbg"
17 "gitlab.com/gitlab-org/cli/internal/glrepo"
18 "gitlab.com/gitlab-org/cli/internal/iostreams"
19 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
20 "gitlab.com/gitlab-org/cli/internal/utils"
21)
23type options struct {
24 outputFormat string
26 io *iostreams.IOStreams
27 gitlabClient func() (*gitlab.Client, error)
28 baseRepo func() (glrepo.Interface, error)
29 branch func() (string, error)
30}
32func NewCmdStatus(f cmdutils.Factory) *cobra.Command {
33 opts := &options{
34 io: f.IO(),
35 gitlabClient: f.GitLabClient,
36 baseRepo: f.BaseRepo,
37 branch: f.Branch,
38 }
40 pipelineStatusCmd := &cobra.Command{
41 Use: "status [flags]",
42 Short: `View CI/CD pipeline status.`,
43 Aliases: []string{"stats"},
44 Long: heredoc.Docf(`
45 Defaults to the current branch.
47 Use %[1]s--live%[1]s for real-time updates. Use %[1]s--compact%[1]s for a condensed view.
48 `, "`"),
49 Example: heredoc.Doc(`
50 # View the pipeline status in real time
51 glab ci status --live
53 # Wait to return until the pipeline is finished, and provide output without a prompt.
54 glab ci status --wait
56 # A more compact view
57 glab ci status --compact
59 # Get the pipeline for the main branch
60 glab ci status --branch=main
62 # Get the pipeline for the current branch
63 glab ci status`),
64 Args: cobra.NoArgs,
65 ValidArgsFunction: cobra.NoFileCompletions,
66 Annotations: map[string]string{
67 mcpannotations.Safe: "true",
68 },
69 RunE: func(cmd *cobra.Command, args []string) error {
70 var err error
71 c := opts.io.Color()
73 client, err := opts.gitlabClient()
74 if err != nil {
75 return err
76 }
78 branch, _ := cmd.Flags().GetString("branch")
79 live, _ := cmd.Flags().GetBool("live")
80 compact, _ := cmd.Flags().GetBool("compact")
81 wait, _ := cmd.Flags().GetBool("wait")
83 if opts.outputFormat == "json" && (live || compact || wait) {
84 return fmt.Errorf("--output json cannot be used with --live, --wait, or --compact flags")
85 }
87 if wait {
88 live = true
89 opts.io.SetPrompt("true")
90 }
92 repo, err := opts.baseRepo()
93 if err != nil {
94 return err
95 }
96 repoName := repo.FullName()
97 dbg.Debug("Repository:", repoName)
99 // Get the correct branch name using the utility function
100 branch = ciutils.GetBranch(branch, func() (string, error) {
101 return opts.branch()
102 }, repo, client)
103 dbg.Debug("Using branch:", branch)
105 // Use fallback logic for robust pipeline lookup
106 runningPipeline, err := ciutils.GetPipelineWithFallback(cmd.Context(), client, repoName, branch, opts.io)
107 if err != nil {
108 if opts.outputFormat != "json" {
109 redCheck := c.Red("✘")
110 opts.io.LogInfof("%s %v\n", redCheck, err)
111 }
112 return err
113 }
115 // For JSON output, fetch jobs once and return the data
116 if opts.outputFormat == "json" {
117 jobs, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.Job, *gitlab.Response, error) {
118 return client.Jobs.ListPipelineJobs(repoName, runningPipeline.ID, &gitlab.ListJobsOptions{ListOptions: gitlab.ListOptions{PerPage: 100}}, p, gitlab.WithContext(cmd.Context()))
119 })
120 if err != nil {
121 return err
122 }
123 output := map[string]any{
124 "pipeline": runningPipeline,
125 "jobs": jobs,
126 }
127 return opts.io.PrintJSON(output)
128 }
130 writer := uilive.New()
132 ctx := cmd.Context()
134 // Set up ticker for live updates if needed
135 var ticker *time.Ticker
136 if live {
137 ticker = time.NewTicker(3 * time.Second)
138 defer ticker.Stop()
139 }
141 // start listening for updates and render
142 writer.Start()
143 defer writer.Stop()
144 loop:
145 for {
146 jobs, err := gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.Job, *gitlab.Response, error) {
147 return client.Jobs.ListPipelineJobs(repoName, runningPipeline.ID, &gitlab.ListJobsOptions{ListOptions: gitlab.ListOptions{PerPage: 100}}, p, gitlab.WithContext(ctx))
148 })
149 if err != nil {
150 if ctx.Err() != nil {
151 break
152 }
153 return err
154 }
155 for _, job := range jobs {
156 end := time.Now()
157 if job.FinishedAt != nil {
158 end = *job.FinishedAt
159 }
160 var duration string
161 if job.StartedAt != nil {
162 duration = utils.FmtDuration(end.Sub(*job.StartedAt))
163 } else {
164 duration = "not started"
165 }
166 var status string
167 switch s := job.Status; s {
168 case string(gitlab.Failed):
169 if job.AllowFailure {
170 status = c.Yellow(s)
171 } else {
172 status = c.Red(s)
173 }
174 case string(gitlab.Success):
175 status = c.Green(s)
176 default:
177 status = c.Gray(s)
178 }
179 if compact {
180 fmt.Fprintf(writer, "(%s) • %s [%s]\n", status, job.Name, job.Stage) //nolint:forbidigo // writer is a uilive live-updating writer, not IOStreams
181 } else {
182 fmt.Fprintf(writer, "(%s) • %s\t%s\t\t%s\n", status, c.Gray(duration), job.Stage, job.Name) //nolint:forbidigo // writer is a uilive live-updating writer, not IOStreams
183 }
184 }
186 if !compact {
187 fmt.Fprintf(writer.Newline(), "\n%s\n", runningPipeline.WebURL) //nolint:forbidigo // writer is a uilive live-updating writer, not IOStreams
188 fmt.Fprintf(writer.Newline(), "SHA: %s\n", runningPipeline.SHA) //nolint:forbidigo // writer is a uilive live-updating writer, not IOStreams
189 }
190 fmt.Fprintf(writer.Newline(), "Pipeline state: %s\n\n", runningPipeline.Status) //nolint:forbidigo // writer is a uilive live-updating writer, not IOStreams
192 inProgress := isLivePollableStatus(runningPipeline.Status)
194 // When the current pipeline is canceled (e.g. auto-canceled because a
195 // rebase triggered a new pipeline), check whether a newer pipeline now
196 // exists for the branch and continue monitoring it instead of exiting.
197 if !inProgress && runningPipeline.Status == string(gitlab.Canceled) && live {
198 if latest, lookupErr := ciutils.GetPipelineWithFallback(ctx, client, repoName, branch, opts.io); lookupErr == nil && latest != nil && latest.ID != runningPipeline.ID {
199 runningPipeline = latest
200 inProgress = isLivePollableStatus(latest.Status)
201 // Skip the redundant refresh below by waiting for the next
202 // tick and restarting the loop, which will re-render jobs
203 // for the new pipeline and then fall into the normal
204 // live-update path.
205 if inProgress {
206 select {
207 case <-ctx.Done():
208 break loop
209 case <-ticker.C:
210 }
211 continue
212 }
213 }
214 }
216 switch {
217 case inProgress && live:
218 updatedPipeline, err := ciutils.GetPipelineWithFallback(ctx, client, repoName, branch, opts.io)
219 if err != nil {
220 // Final fallback: refresh current pipeline by ID
221 updatedPipeline, _, err = client.Pipelines.GetPipeline(repoName, runningPipeline.ID, gitlab.WithContext(ctx))
222 if err != nil {
223 if ctx.Err() != nil {
224 break loop
225 }
226 return err
227 }
228 }
229 runningPipeline = updatedPipeline
231 // Wait between updates, but allow cancellation
232 select {
233 case <-ctx.Done():
234 break loop
235 case <-ticker.C:
236 }
237 case opts.io.IsInteractive():
238 var answer string
239 selector := huh.NewSelect[string]().
240 Title("Choose an action:").
241 Options(
242 huh.NewOption("View logs", "View logs"),
243 huh.NewOption("Retry", "Retry"),
244 huh.NewOption("Exit", "Exit"),
245 ).
246 Value(&answer)
247 if err := opts.io.Run(ctx, selector); err != nil {
248 if ctx.Err() != nil {
249 break loop
250 }
251 return err
252 }
253 switch answer {
254 case "View logs":
255 return ciutils.TraceJob(ctx, &ciutils.JobInputs{
256 Branch: branch,
257 }, &ciutils.JobOptions{
258 Repo: repo,
259 Client: client,
260 IO: opts.io,
261 BranchFunc: opts.branch,
262 })
263 case "Retry":
264 _, _, err := client.Pipelines.RetryPipelineBuild(repoName, runningPipeline.ID)
265 if err != nil {
266 if ctx.Err() != nil {
267 break loop
268 }
269 return err
270 }
271 updatedPipeline, err := ciutils.GetPipelineWithFallback(ctx, client, repoName, branch, opts.io)
272 if err != nil {
273 // Fallback: refresh by pipeline ID if MR lookup fails
274 updatedPipeline, _, err = client.Pipelines.GetPipeline(repoName, runningPipeline.ID, gitlab.WithContext(ctx))
275 if err != nil {
276 if ctx.Err() != nil {
277 break loop
278 }
279 return err
280 }
281 }
282 runningPipeline = updatedPipeline
283 default:
284 break loop
285 }
286 default:
287 break loop
288 }
289 }
290 // Only show "Exiting..." message if cancelled via Ctrl+C
291 if ctx.Err() != nil {
292 fmt.Fprintln(writer.Newline(), "Exiting...") //nolint:forbidigo // writer is a uilive live-updating writer, not IOStreams
293 }
294 if runningPipeline.Status == string(gitlab.Failed) {
295 return cmdutils.SilentError
296 }
297 return nil
298 },
299 }
301 pipelineStatusCmd.Flags().BoolP("live", "l", false, "Show status in real time until the pipeline ends.")
302 pipelineStatusCmd.Flags().BoolP("compact", "c", false, "Show status in compact format.")
303 pipelineStatusCmd.Flags().BoolP("wait", "w", false, "Wait to return until the pipeline is finished, and provide output without a prompt.")
304 pipelineStatusCmd.Flags().StringP("branch", "b", "", "Check pipeline status for a branch. Defaults to the current branch.")
305 cmdutils.EnableJSONOutput(pipelineStatusCmd, opts.io, &opts.outputFormat, "Format output as: text, json. Note: JSON output is not compatible with --live, --wait, or --compact flags.")
307 return pipelineStatusCmd
308}
310// isLivePollableStatus reports whether a pipeline status represents an
311// in-progress state that --live should keep polling. Terminal statuses
312// (success, failed, skipped, canceled) and statuses requiring user action
313// (manual) are excluded — they don't progress on their own.
314func isLivePollableStatus(status string) bool {
315 switch status {
316 case string(gitlab.Created), string(gitlab.WaitingForResource), string(gitlab.Preparing),
317 string(gitlab.Pending), string(gitlab.Running), string(gitlab.Scheduled):
318 return true
319 }
320 return false
321}
Diagnostics8 git calls · 249 ms
CallStatusSizeTime0249 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=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=44Open pack map
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:02001.8 KiB · hit2 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=1857 git.response.cache=HIT git.response.duration_ms=2 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:0200635 B · hit3 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=635 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=517b073a0d5c32bc4e93f86de74b31d60ff8cf03 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=635 git.pkt.payload.max=608 git.sideband.band1.bytes=608 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=608 git.pack.trailer=178abb9456d874b7fd38fa21ad5cf9ca3ebcccaaOpen pack map
fetchtree:0200138 B · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=235 git.response.bytes=138 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=150d1d755b9bc2f4f1fdb755cc45f63901b179d5 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=138 git.pkt.payload.max=111 git.sideband.band1.bytes=111 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=111 git.pack.trailer=8ca095a643d59835d6950ca5f31d5b1cd99ecbdeOpen pack map
fetch2003.3 KiB235 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=3334 git.response.cache=MISS git.response.duration_ms=235 git.fetch.wants=e7d3ef9057ae41756ec2ad632f589cf8a2a80db5 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=3334 git.pkt.payload.max=3307 git.sideband.band1.bytes=3307 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
- a5e2e1ba9d124af4
- Request
- 2083d5d4…
- 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