GitLabgitlab-org

cli

main
ply8 git calls316 ms101 KiB6 cachedprotocol v2
340 lines11 KiBRaw
1package list
3import (
4 "context"
5 "fmt"
6 "slices"
7 "strings"
9 "github.com/MakeNowJust/heredoc/v2"
10 "github.com/spf13/cobra"
12 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
14 "gitlab.com/gitlab-org/cli/internal/cmdutils"
15 workitemsapi "gitlab.com/gitlab-org/cli/internal/commands/workitems/api"
16 "gitlab.com/gitlab-org/cli/internal/commands/workitems/utils"
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/text"
23type options struct {
24 // Dependencies (for testability)
25 io *iostreams.IOStreams
26 baseRepo func() (glrepo.Interface, error)
27 gitlabClient func() (*gitlab.Client, error)
29 // Flags
30 group string
31 types []string
32 outputFormat string
33 state string
34 after string
35 perPage int64
36 dates map[workitemsapi.DateField]*dateFilterValue
39var dateFlags = []struct {
40 name string
41 field workitemsapi.DateField
42 usage string
43}{
44 {"created-after", workitemsapi.CreatedAfter, "Show work items created on or after <date>."},
45 {"created-before", workitemsapi.CreatedBefore, "Show work items created before <date>."},
46 {"updated-after", workitemsapi.UpdatedAfter, "Show work items updated on or after <date>."},
47 {"updated-before", workitemsapi.UpdatedBefore, "Show work items updated before <date>."},
48 {"closed-after", workitemsapi.ClosedAfter, "Show work items closed on or after <date>. Implies --state closed unless --state is set."},
49 {"closed-before", workitemsapi.ClosedBefore, "Show work items closed before <date>. Implies --state closed unless --state is set."},
50 {"due-after", workitemsapi.DueAfter, "Show work items due on or after <date>."},
51 {"due-before", workitemsapi.DueBefore, "Show work items due before <date>."},
54// dateFilterValue keeps the raw input so the next page command repeats a
55// relative date as given, instead of the date it resolved to.
56type dateFilterValue struct {
57 raw string
58 filter workitemsapi.DateFilter
61func (d *dateFilterValue) Type() string { return "date" }
62func (d *dateFilterValue) String() string { return d.raw }
64func (d *dateFilterValue) Set(s string) error {
65 filter, err := workitemsapi.ParseDateFilter(s)
66 if err != nil {
67 return err
68 }
69 d.raw, d.filter = s, filter
70 return nil
73// jsonPaginationInfo contains pagination metrics for JSON responses
74type jsonPaginationInfo struct {
75 HasNext bool `json:"has_next"`
76 NextCursor string `json:"next_cursor,omitempty"`
77 PerPage int64 `json:"per_page"`
80// jsonListResponse wraps work items with pagination metadata
81type jsonListResponse struct {
82 Data []workitemsapi.WorkItem `json:"data"`
83 Pagination jsonPaginationInfo `json:"pagination"`
86func NewCmd(f cmdutils.Factory) *cobra.Command {
87 opts := &options{
88 io: f.IO(),
89 baseRepo: f.BaseRepo,
90 gitlabClient: f.GitLabClient,
91 dates: make(map[workitemsapi.DateField]*dateFilterValue, len(dateFlags)),
92 }
94 cmd := &cobra.Command{
95 Use: "list [flags]",
96 Short: "List work items in a project or group. (EXPERIMENTAL)",
97 Long: heredoc.Doc(`List work items in a project or group.
99Automatically detects scope from repository context. Use --group flag
100for group-level work items or -R to specify a different project.
102Date filters accept:
104- An absolute date (YYYY-MM-DD). A date without a time is read in the system time zone of the GitLab server.
105- An RFC 3339 timestamp. Use one with an offset, such as 2026-01-01T00:00:00+02:00, for an exact point in time.
106- A relative date: a number followed by d (days), w (weeks), m (months), or y (years). Negative numbers are in the past, positive numbers are in the future, and 0d is today. Relative dates resolve to the start of the day in the time zone of the GitLab instance. They stay relative, so the same command keeps returning the last 7 days, for example.
108Date filters require GitLab 19.4 or later. Relative dates require GitLab 19.6 or later.
109`) + text.ExperimentalString,
110 Aliases: []string{"ls"},
111 Example: heredoc.Doc(`
112 # List first 20 open work items in current project
113 glab work-items list
115 # List open epics in a group (default: 20 items)
116 glab work-items list --type epic -g gitlab-org
118 # List first 50 open work items
119 glab work-items list --per-page 50 -g gitlab-org
121 # Get next page using cursor from previous output
122 glab work-items list --after "eyJpZCI6OTk5OX0" -g gitlab-org
124 # List closed work items
125 glab work-items list --state closed -g gitlab-org
127 # List all work items regardless of state
128 glab work-items list --state all -g gitlab-org
130 # JSON output with pagination metadata
131 glab work-items list --output json -g gitlab-org
133 # List issues in a specific project
134 glab work-items list --type issue -R gitlab-org/cli
136 # List work items created in the last 7 days
137 glab work-items list --created-after -7d -g gitlab-org
139 # List open work items due in the next 2 weeks
140 glab work-items list --due-after 0d --due-before 2w -g gitlab-org
142 # List work items closed in a fixed date range
143 glab work-items list --state closed --closed-after 2026-01-01 --closed-before 2026-04-01 -g gitlab-org`),
144 Args: cobra.NoArgs,
145 ValidArgsFunction: cobra.NoFileCompletions,
146 Annotations: map[string]string{
147 mcpannotations.Safe: "true",
148 },
149 RunE: func(cmd *cobra.Command, args []string) error {
150 if err := opts.complete(cmd); err != nil {
151 return err
152 }
153 if err := opts.validate(); err != nil {
154 return err
155 }
156 return opts.run(cmd.Context())
157 },
158 }
160 // Enable -R flag for repo override
161 cmdutils.EnableRepoOverride(cmd, f)
162 cmdutils.EnableJSONOutput(cmd, opts.io, &opts.outputFormat)
164 // Flags
165 fl := cmd.Flags()
166 fl.StringP("group", "g", "", "List work items for a group or subgroup.")
167 fl.StringSliceVarP(&opts.types, "type", "t", []string{}, "Filter by work item type (epic, issue, task, etc.) Multiple types can be comma-separated or specified by repeating the flag.")
169 fl.StringVar(&opts.state, "state", "opened", "Filter by state: opened, closed, all.")
170 fl.StringVar(&opts.after, "after", "", "Fetch items after this cursor (for pagination)")
171 fl.Int64VarP(&opts.perPage, "per-page", "P", 20, "Number of items to list per page (max 100)")
173 for _, df := range dateFlags {
174 v := &dateFilterValue{}
175 opts.dates[df.field] = v
176 fl.Var(v, df.name, df.usage+" Use YYYY-MM-DD, an RFC 3339 timestamp, or a relative date such as -7d, 2w, -1m, or 1y.")
177 }
179 return cmd
182func (opts *options) complete(cmd *cobra.Command) error {
183 group, err := cmdutils.GroupOverride(cmd)
184 if err != nil {
185 return err
186 }
187 opts.group = group
189 // Reopening a work item clears its closed date, so open items never match.
190 if opts.hasClosedFilter() && !cmd.Flags().Changed("state") {
191 opts.state = "closed"
192 }
193 return nil
196func (opts *options) validate() error {
197 if err := utils.ValidateTypes(opts.types); err != nil {
198 return cmdutils.FlagError{Err: err}
199 }
201 if opts.perPage < 1 || opts.perPage > 100 {
202 return cmdutils.FlagError{
203 Err: fmt.Errorf("--per-page must be between 1 and 100"),
204 }
205 }
207 validStates := []string{"opened", "closed", "all"}
208 if !slices.Contains(validStates, opts.state) {
209 return cmdutils.FlagError{
210 Err: fmt.Errorf("--state must be one of: opened, closed, all"),
211 }
212 }
214 if opts.hasClosedFilter() && opts.state == "opened" {
215 return cmdutils.FlagError{
216 Err: fmt.Errorf("--closed-after and --closed-before need --state closed or all"),
217 }
218 }
220 return nil
223func (opts *options) hasClosedFilter() bool {
224 return opts.dates[workitemsapi.ClosedAfter].raw != "" || opts.dates[workitemsapi.ClosedBefore].raw != ""
227func (opts *options) run(ctx context.Context) error {
228 scope, err := utils.DetectScope(opts.group, opts.baseRepo)
229 if err != nil {
230 return err
231 }
233 client, err := opts.gitlabClient()
234 if err != nil {
235 return fmt.Errorf("failed to get GitLab client: %w", err)
236 }
238 // fetch work items with state filtering and pagination
239 workItems, pageInfo, err := workitemsapi.FetchWorkItems(ctx, client, scope, workitemsapi.ListOptions{
240 Types: opts.types,
241 State: opts.state,
242 After: opts.after,
243 PerPage: opts.perPage,
244 Dates: opts.dateFilters(),
245 })
246 if err != nil {
247 return err
248 }
250 switch opts.outputFormat {
251 case "json":
252 return outputJSON(opts.io, workItems, pageInfo, opts.perPage)
253 case "text":
254 // display a table
255 if len(workItems) == 0 {
256 opts.io.LogInfof("No work items found in %s\n", scope.Path)
257 return nil
258 }
260 table := utils.DisplayWorkItemList(opts.io, workItems)
261 opts.io.LogInfof("%s", table)
263 if pageInfo != nil && pageInfo.HasNextPage {
264 opts.io.LogInfof("\nNext page: %s\n", buildNextPageCommand(opts, pageInfo.EndCursor))
265 }
266 return nil
267 default:
268 return fmt.Errorf("unsupported output format: %s", opts.outputFormat)
269 }
272func (opts *options) dateFilters() map[workitemsapi.DateField]workitemsapi.DateFilter {
273 filters := make(map[workitemsapi.DateField]workitemsapi.DateFilter)
274 for field, v := range opts.dates {
275 if v.raw != "" {
276 filters[field] = v.filter
277 }
278 }
279 return filters
282// buildNextPageCommand constructs the next page command string with preserved flags.
283func buildNextPageCommand(opts *options, cursor string) string {
284 var b strings.Builder
286 b.WriteString("glab work-items list")
288 // preserve group flag
289 if opts.group != "" {
290 fmt.Fprintf(&b, " -g %s", opts.group) //nolint:forbidigo // writing to strings.Builder, not stdout/stderr
291 }
293 // preserve type filters
294 if len(opts.types) > 0 {
295 fmt.Fprintf(&b, " --type %s", strings.Join(opts.types, ",")) //nolint:forbidigo // writing to strings.Builder, not stdout/stderr
296 }
298 // preserve state filter (only if non-default)
299 if opts.state != "opened" {
300 fmt.Fprintf(&b, " --state %s", opts.state) //nolint:forbidigo // writing to strings.Builder, not stdout/stderr
301 }
303 for _, df := range dateFlags {
304 if v := opts.dates[df.field]; v.raw != "" {
305 fmt.Fprintf(&b, " --%s %s", df.name, v.raw) //nolint:forbidigo // writing to strings.Builder, not stdout/stderr
306 }
307 }
309 // preserve per-page (only if non-default)
310 if opts.perPage != 20 {
311 fmt.Fprintf(&b, " --per-page %d", opts.perPage) //nolint:forbidigo // writing to strings.Builder, not stdout/stderr
312 }
314 // preserve output format (only if non-default)
315 if opts.outputFormat != "text" {
316 fmt.Fprintf(&b, " --output %s", opts.outputFormat) //nolint:forbidigo // writing to strings.Builder, not stdout/stderr
317 }
319 // add the cursor
320 fmt.Fprintf(&b, " --after %q", cursor) //nolint:forbidigo // writing to strings.Builder, not stdout/stderr
322 return b.String()
325func outputJSON(io *iostreams.IOStreams, workItems []workitemsapi.WorkItem, pageInfo *workitemsapi.PageInfo, perPage int64) error {
326 response := jsonListResponse{
327 Data: workItems,
328 Pagination: jsonPaginationInfo{
329 HasNext: false,
330 PerPage: perPage,
331 },
332 }
334 if pageInfo != nil && pageInfo.HasNextPage {
335 response.Pagination.HasNext = true
336 response.Pagination.NextCursor = pageInfo.EndCursor
337 }
339 return io.PrintJSON(response)
Diagnostics8 git calls · 316 ms
CallStatusSizeTime0316 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 · hit6 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=6
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=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:02001.8 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=1857
git.response.cache=HIT
git.response.duration_ms=3
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=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200317 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=317
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=33cd62a3f1bc55e6bd56a9b96f181ff12c30955a
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=317
git.pkt.payload.max=290
git.sideband.band1.bytes=290
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=290
git.pack.trailer=5711d3cc007ef3bd902f87854e977c46d0913d04
Open pack map
fetchtree:0200134 B · 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=134
git.response.cache=HIT
git.response.duration_ms=4
git.fetch.filter=tree:0
git.fetch.wants=a26639bcb3dad59f922343bfee14e5625ce7950a
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=134
git.pkt.payload.max=107
git.sideband.band1.bytes=107
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=107
git.pack.trailer=692a20cead216b96f20a284440e1aa9f3e1aa9ae
Open pack map
fetch2003.6 KiB296 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=296
git.response.bytes=3686
git.response.cache=MISS
git.response.duration_ms=296
git.fetch.wants=8dd91396fe4eb44e282e550ecf5c94cc7b40a353
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=3686
git.pkt.payload.max=3659
git.sideband.band1.bytes=3659
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
a5e256f0cf9f1ae0
Request
6923508d…
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