GitLabgitlab-org
cli
main
1package list
3import (
4 "time"
6 "github.com/MakeNowJust/heredoc/v2"
7 "github.com/spf13/cobra"
9 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
11 "gitlab.com/gitlab-org/cli/internal/api"
12 "gitlab.com/gitlab-org/cli/internal/cmdutils"
13 "gitlab.com/gitlab-org/cli/internal/commands/mr/mrutils"
14 "gitlab.com/gitlab-org/cli/internal/glrepo"
15 "gitlab.com/gitlab-org/cli/internal/iostreams"
16 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
17 "gitlab.com/gitlab-org/cli/internal/utils"
18)
20// defaultSortByOrder provides sensible default sort directions for each order option.
21// Time-based fields default to desc (newest first), while priority and title default to asc.
22var defaultSortByOrder = map[string]string{
23 "created_at": "desc",
24 "updated_at": "desc",
25 "merged_at": "desc",
26 "title": "asc",
27 "popularity": "desc",
28 "milestone_due": "asc",
29 "priority": "asc",
30 "label_priority": "asc",
31}
33type options struct {
34 // metadata
35 assignee []string
36 author string
37 createdAfter time.Time
38 createdBefore time.Time
39 deployedAfter time.Time
40 deployedBefore time.Time
41 environment string
42 group string
43 labels []string
44 milestone string
45 mine bool
46 notLabels []string
47 reviewer []string
48 search string
49 sourceBranch string
50 targetBranch string
52 // issue states
53 state string
54 closed bool
55 merged bool
56 all bool
57 draft bool
58 notDraft bool
60 // Pagination
61 page int
62 perPage int
63 outputFormat string
65 // display opts
66 listType string
67 titleQualifier string
69 // sort options
70 sort string
71 orderBy string
73 io *iostreams.IOStreams
74 baseRepo func() (glrepo.Interface, error)
75 apiClient func(repoHost string) (*api.Client, error)
76}
78func NewCmdList(f cmdutils.Factory, runE func(opts *options) error) *cobra.Command {
79 opts := &options{
80 io: f.IO(),
81 baseRepo: f.BaseRepo,
82 apiClient: f.ApiClient,
83 }
85 mrListCmd := &cobra.Command{
86 Use: "list [flags]",
87 Short: `List merge requests.`,
88 Long: heredoc.Docf(`
89 Defaults to open merge requests. Use %[1]s--all%[1]s to include closed
90 and merged requests. Use %[1]s--group%[1]s to list for a group instead
91 of the current project.
92 `, "`"),
93 Aliases: []string{"ls"},
94 Annotations: map[string]string{
95 mcpannotations.Safe: "true",
96 },
97 Example: heredoc.Doc(`
98 glab mr list --all
99 glab mr ls -a
100 glab mr list --assignee=@me
101 glab mr list --reviewer=@me
102 glab mr list --source-branch=new-feature
103 glab mr list --target-branch=main
104 glab mr list --search "this adds feature X"
105 glab mr list --label needs-review
106 glab mr list --not-label waiting-maintainer-feedback,subsystem-x
107 glab mr list -M --per-page 10
108 glab mr list --draft
109 glab mr list --not-draft`),
110 Args: cobra.NoArgs,
111 ValidArgsFunction: cobra.NoFileCompletions,
112 RunE: func(cmd *cobra.Command, args []string) error {
113 if err := opts.complete(cmd); err != nil {
114 return err
115 }
117 if runE != nil {
118 return runE(opts)
119 }
121 return opts.run()
122 },
123 }
125 cmdutils.EnableRepoOverride(mrListCmd, f)
126 mrListCmd.Flags().StringSliceVarP(&opts.labels, "label", "l", []string{}, "Filter merge request by label <name>. Multiple labels can be comma-separated or specified by repeating the flag.")
127 mrListCmd.Flags().StringSliceVar(&opts.notLabels, "not-label", []string{}, "Filter merge requests by not having label <name>. Multiple labels can be comma-separated or specified by repeating the flag.")
128 mrListCmd.Flags().StringVar(&opts.author, "author", "", "Filter merge request by author <username>.")
129 mrListCmd.Flags().StringVarP(&opts.milestone, "milestone", "m", "", "Filter merge request by milestone <title>.")
130 mrListCmd.Flags().StringVarP(&opts.sourceBranch, "source-branch", "s", "", "Filter by source branch <name>.")
131 mrListCmd.Flags().StringVarP(&opts.targetBranch, "target-branch", "t", "", "Filter by target branch <name>.")
132 mrListCmd.Flags().StringVar(&opts.search, "search", "", "Filter by <string> in title and description.")
133 mrListCmd.Flags().BoolVarP(&opts.all, "all", "A", false, "Get all merge requests.")
134 mrListCmd.Flags().BoolVarP(&opts.closed, "closed", "c", false, "Get only closed merge requests.")
135 mrListCmd.Flags().BoolVarP(&opts.merged, "merged", "M", false, "Get only merged merge requests.")
136 mrListCmd.Flags().BoolVarP(&opts.draft, "draft", "d", false, "Filter by draft merge requests.")
137 mrListCmd.Flags().BoolVarP(&opts.notDraft, "not-draft", "", false, "Filter by non-draft merge requests.")
138 cmdutils.EnableJSONOutput(mrListCmd, opts.io, &opts.outputFormat)
139 mrListCmd.Flags().IntVarP(&opts.page, "page", "p", 1, "Page number.")
140 mrListCmd.Flags().IntVarP(&opts.perPage, "per-page", "P", 30, "Number of items to list per page.")
141 mrListCmd.Flags().StringSliceVarP(&opts.assignee, "assignee", "a", []string{}, "Get only merge requests assigned to users. Multiple users can be comma-separated or specified by repeating the flag.")
142 mrListCmd.Flags().StringSliceVarP(&opts.reviewer, "reviewer", "r", []string{}, "Get only merge requests with users as reviewer. Multiple users can be comma-separated or specified by repeating the flag.")
143 mrListCmd.Flags().StringVarP(&opts.sort, "sort", "S", "", "Sort direction for --order field: asc or desc.")
144 mrListCmd.Flags().StringVarP(&opts.orderBy, "order", "o", "", "Order merge requests by <field>. Order options: created_at, updated_at, merged_at, title, priority, label_priority, milestone_due, and popularity.")
145 mrListCmd.Flags().TimeVar(&opts.createdBefore, "created-before", time.Time{}, []string{time.RFC3339}, "Filter merge requests created before a certain date (ISO 8601 format).")
146 mrListCmd.Flags().TimeVar(&opts.createdAfter, "created-after", time.Time{}, []string{time.RFC3339}, "Filter merge requests created after a certain date (ISO 8601 format).")
147 mrListCmd.Flags().TimeVar(&opts.deployedBefore, "deployed-before", time.Time{}, []string{time.RFC3339}, "Filter merge requests deployed before a certain date (ISO 8601 format).")
148 mrListCmd.Flags().TimeVar(&opts.deployedAfter, "deployed-after", time.Time{}, []string{time.RFC3339}, "Filter merge requests deployed after a certain date (ISO 8601 format).")
149 mrListCmd.Flags().StringVar(&opts.environment, "environment", "", "Filter merge requests deployed to the given environment <name>.")
151 mrListCmd.Flags().BoolP("opened", "O", false, "Get only open merge requests.")
152 _ = mrListCmd.Flags().MarkHidden("opened")
153 _ = mrListCmd.Flags().MarkDeprecated("opened", "default value if neither --closed, --locked or --merged is used.")
155 mrListCmd.Flags().BoolVarP(&opts.mine, "mine", "", false, "Get only merge requests assigned to me.")
156 _ = mrListCmd.Flags().MarkHidden("mine")
157 _ = mrListCmd.Flags().MarkDeprecated("mine", "use --assignee=@me.")
158 mrListCmd.PersistentFlags().StringP("group", "g", "", "Select a group/subgroup. This option is ignored if a repo argument is set.")
159 mrListCmd.MarkFlagsMutuallyExclusive("draft", "not-draft")
160 mrListCmd.MarkFlagsMutuallyExclusive("label", "not-label")
161 mrListCmd.MarkFlagsMutuallyExclusive("closed", "merged")
163 return mrListCmd
164}
166func (o *options) complete(cmd *cobra.Command) error {
167 switch {
168 case o.all:
169 o.state = "all"
170 case o.closed:
171 o.state = "closed"
172 o.titleQualifier = o.state
173 case o.merged:
174 o.state = "merged"
175 o.titleQualifier = o.state
176 default:
177 o.state = "opened"
178 o.titleQualifier = "open"
179 }
181 group, err := cmdutils.GroupOverride(cmd)
182 if err != nil {
183 return err
184 }
185 o.group = group
187 // Apply sensible default sort direction if user didn't explicitly set --sort
188 sortFlagChanged := cmd.Flags().Changed("sort")
189 if !sortFlagChanged && o.orderBy != "" {
190 if defaultSort, ok := defaultSortByOrder[o.orderBy]; ok {
191 o.sort = defaultSort
192 }
193 }
195 return nil
196}
198func (o *options) run() error {
199 var mergeRequests []*gitlab.BasicMergeRequest
201 // NOTE: this command can not only be used for projects,
202 // so we have to manually check for the base repo, if it doesn't exist,
203 // we bootstrap the client with the default hostname.
204 var repoHost string
205 if baseRepo, err := o.baseRepo(); err == nil {
206 repoHost = baseRepo.RepoHost()
207 }
208 apiClient, err := o.apiClient(repoHost)
209 if err != nil {
210 return err
211 }
212 client := apiClient.Lab()
214 l := &gitlab.ListProjectMergeRequestsOptions{
215 State: new(o.state),
216 ListOptions: gitlab.ListOptions{
217 Page: 1,
218 PerPage: 30,
219 },
220 }
221 jsonOutput := o.outputFormat == "json"
222 if jsonOutput {
223 l.Page = 0
224 l.PerPage = 0
225 }
227 if o.author != "" {
228 u, err := api.UserByName(client, o.author)
229 if err != nil {
230 return err
231 }
232 l.AuthorID = new(u.ID)
233 o.listType = "search"
234 }
235 if o.sourceBranch != "" {
236 l.SourceBranch = new(o.sourceBranch)
237 o.listType = "search"
238 }
239 if o.targetBranch != "" {
240 l.TargetBranch = new(o.targetBranch)
241 o.listType = "search"
242 }
243 if o.search != "" {
244 l.Search = new(o.search)
245 o.listType = "search"
246 }
247 if len(o.labels) > 0 {
248 l.Labels = (*gitlab.LabelOptions)(&o.labels)
249 o.listType = "search"
250 }
251 if len(o.notLabels) > 0 {
252 l.NotLabels = (*gitlab.LabelOptions)(&o.notLabels)
253 o.listType = "search"
254 }
255 if o.milestone != "" {
256 l.Milestone = new(o.milestone)
257 o.listType = "search"
258 }
259 if o.page != 0 {
260 l.Page = int64(o.page)
261 }
262 if o.perPage != 0 {
263 l.PerPage = int64(o.perPage)
264 }
265 if o.draft {
266 l.WIP = new("yes")
267 o.listType = "search"
268 }
269 if o.notDraft {
270 l.WIP = new("no")
271 o.listType = "search"
272 }
274 if o.mine {
275 l.Scope = new("assigned_to_me")
276 o.listType = "search"
277 }
279 if o.orderBy != "" {
280 l.OrderBy = new(o.orderBy)
281 o.listType = "search"
282 }
284 if o.sort != "" {
285 l.Sort = new(o.sort)
286 }
288 assigneeIds := make([]int, 0)
289 if len(o.assignee) > 0 {
290 if o.assignee[0] == "@any" {
291 l.AssigneeID = gitlab.AssigneeID(gitlab.UserIDAny)
292 } else {
293 users, err := api.UsersByNames(client, o.assignee)
294 if err != nil {
295 return err
296 }
297 for _, user := range users {
298 assigneeIds = append(assigneeIds, int(user.ID))
299 }
300 }
301 }
303 reviewerIds := make([]int, 0)
304 if len(o.reviewer) > 0 {
305 if o.reviewer[0] == "@any" {
306 l.ReviewerID = gitlab.ReviewerID(gitlab.UserIDAny)
307 } else {
308 users, err := api.UsersByNames(client, o.reviewer)
309 if err != nil {
310 return err
311 }
312 for _, user := range users {
313 reviewerIds = append(reviewerIds, int(user.ID))
314 }
315 }
316 }
317 title := utils.NewListTitle(o.titleQualifier + " merge request")
319 if !o.createdBefore.IsZero() {
320 l.CreatedBefore = new(o.createdBefore)
321 }
323 if !o.createdAfter.IsZero() {
324 l.CreatedAfter = new(o.createdAfter)
325 }
327 if !o.deployedBefore.IsZero() {
328 l.DeployedBefore = new(o.deployedBefore)
329 }
331 if !o.deployedAfter.IsZero() {
332 l.DeployedAfter = new(o.deployedAfter)
333 }
335 if o.environment != "" {
336 l.Environment = new(o.environment)
337 }
339 if o.group != "" {
340 mergeRequests, err = api.ListGroupMRs(client, o.group, projectListMROptionsToGroup(l), api.WithMRAssignees(assigneeIds), api.WithMRReviewers(reviewerIds))
341 title.RepoName = o.group
342 } else {
343 var repo glrepo.Interface
344 repo, err = o.baseRepo()
345 if err != nil {
346 return err
347 }
349 title.RepoName = repo.FullName()
350 mergeRequests, err = api.ListMRs(client, repo.FullName(), l, api.WithMRAssignees(assigneeIds), api.WithMRReviewers(reviewerIds))
351 }
352 if err != nil {
353 return err
354 }
356 title.Page = int(l.Page)
357 title.ListActionType = o.listType
358 title.CurrentPageTotal = len(mergeRequests)
360 if jsonOutput {
361 return o.io.PrintJSON(mergeRequests)
362 } else {
363 if err := o.io.StartPager(); err != nil {
364 return err
365 }
366 defer o.io.StopPager()
367 o.io.LogInfof("%s\n%s\n", title.Describe(), mrutils.DisplayAllMRs(o.io, mergeRequests))
368 }
369 return nil
370}
372func projectListMROptionsToGroup(l *gitlab.ListProjectMergeRequestsOptions) *gitlab.ListGroupMergeRequestsOptions {
373 return &gitlab.ListGroupMergeRequestsOptions{
374 ListOptions: l.ListOptions,
375 State: l.State,
376 OrderBy: l.OrderBy,
377 Sort: l.Sort,
378 Milestone: l.Milestone,
379 View: l.View,
380 Labels: l.Labels,
381 NotLabels: l.NotLabels,
382 WithLabelsDetails: l.WithLabelsDetails,
383 WithMergeStatusRecheck: l.WithMergeStatusRecheck,
384 CreatedAfter: l.CreatedAfter,
385 CreatedBefore: l.CreatedBefore,
386 UpdatedAfter: l.UpdatedAfter,
387 UpdatedBefore: l.UpdatedBefore,
388 Scope: l.Scope,
389 AuthorID: l.AuthorID,
390 AssigneeID: l.AssigneeID,
391 ReviewerID: l.ReviewerID,
392 ReviewerUsername: l.ReviewerUsername,
393 MyReactionEmoji: l.MyReactionEmoji,
394 SourceBranch: l.SourceBranch,
395 TargetBranch: l.TargetBranch,
396 Search: l.Search,
397 WIP: l.WIP,
398 }
399}
Diagnostics8 git calls · 208 ms
CallStatusSizeTime0208 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 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 · hit3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=HIT git.response.duration_ms=3 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
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=3 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: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=2 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=44Open pack map
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=2 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:0200746 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=746 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=f3d413a22af5a9c2fe9aa49709b1cb36d1351a7f 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=746 git.pkt.payload.max=719 git.sideband.band1.bytes=719 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=719 git.pack.trailer=330baf80c59a4208b55120dff7dd824b7952b790Open pack map
fetchtree:0200171 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=171 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=e5226532b29c6fa7d1a428029e4deb769f21c7a5 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=171 git.pkt.payload.max=144 git.sideband.band1.bytes=144 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=144 git.pack.trailer=4d83d1433e7e30d5b9834bba8f7c596c9a0675ffOpen pack map
fetch2003.7 KiB195 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=195 git.response.bytes=3801 git.response.cache=MISS git.response.duration_ms=195 git.fetch.wants=62824232c28fa87b1cacb3117bacebf68d3546d6 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=3801 git.pkt.payload.max=3774 git.sideband.band1.bytes=3774 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
- a5e2eebc5a5277be
- Request
- 35c8cf69…
- 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