GitLabgitlab-org
cli
main
1package mrutils
3import (
4 "context"
5 "errors"
6 "fmt"
7 "strings"
9 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
11 "gitlab.com/gitlab-org/cli/internal/api"
12)
14// ErrNoteNotFound is returned by FindNoteInDiscussionPaginated when no note
15// with the requested ID exists. Callers can distinguish this from a real
16// lookup failure (a network or API error while paginating) with errors.Is,
17// and should not report the latter as "not found".
18var ErrNoteNotFound = errors.New("note not found")
20// ListAllDiscussions fetches all discussions for a merge request, paginating automatically.
21var ListAllDiscussions = func(ctx context.Context, client *gitlab.Client, projectID any, mrIID int64, opts *gitlab.ListMergeRequestDiscussionsOptions) ([]*gitlab.Discussion, error) {
22 if opts == nil {
23 opts = &gitlab.ListMergeRequestDiscussionsOptions{}
24 }
25 if opts.PerPage == 0 {
26 opts.PerPage = api.DefaultListLimit
27 }
29 var allDiscussions []*gitlab.Discussion
30 page := opts.Page
31 if page == 0 {
32 page = 1
33 }
35 for {
36 opts.Page = page
37 discussions, resp, err := client.Discussions.ListMergeRequestDiscussions(projectID, mrIID, opts, gitlab.WithContext(ctx))
38 if err != nil {
39 return nil, err
40 }
42 allDiscussions = append(allDiscussions, discussions...)
44 if resp == nil || resp.NextPage == 0 {
45 break
46 }
47 page = resp.NextPage
48 }
50 return allDiscussions, nil
51}
53// FindNoteInDiscussionPaginated finds the discussion and note object for a specific
54// note ID, scanning discussions page by page and returning as soon as a match is
55// found instead of fetching every page first.
56//
57// Returns ErrNoteNotFound (wrapped, check with errors.Is) if every page is scanned
58// without a match. Any other error indicates a real failure while listing
59// discussions and must not be treated as "not found" by callers.
60func FindNoteInDiscussionPaginated(ctx context.Context, client *gitlab.Client, projectID any, mrIID int64, noteID int64) (string, *gitlab.Note, error) {
61 opts := &gitlab.ListMergeRequestDiscussionsOptions{ListOptions: gitlab.ListOptions{PerPage: api.DefaultListLimit}}
63 for discussion, err := range gitlab.Scan2(func(p gitlab.PaginationOptionFunc) ([]*gitlab.Discussion, *gitlab.Response, error) {
64 return client.Discussions.ListMergeRequestDiscussions(projectID, mrIID, opts, p, gitlab.WithContext(ctx))
65 }) {
66 if err != nil {
67 return "", nil, fmt.Errorf("fetch discussions: %w", err)
68 }
70 for _, n := range discussion.Notes {
71 if n.ID == noteID {
72 return discussion.ID, n, nil
73 }
74 }
75 }
77 return "", nil, fmt.Errorf("%w: %d", ErrNoteNotFound, noteID)
78}
80// FilterOpts specifies how to filter discussions.
81type FilterOpts struct {
82 // State filters by resolution status: "resolved", "unresolved", "resolvable", or "" for all.
83 State string
84 // Type filters by discussion type: "general", "diff", "system", or "" for all.
85 Type string
86 // FilePath filters to discussions on a specific file path.
87 FilePath string
88}
90// FilterDiscussions filters discussions based on the provided options.
91func FilterDiscussions(discussions []*gitlab.Discussion, opts FilterOpts) []*gitlab.Discussion {
92 if opts.State == "" && opts.Type == "" && opts.FilePath == "" {
93 return discussions
94 }
96 filtered := []*gitlab.Discussion{}
98 for _, discussion := range discussions {
99 if len(discussion.Notes) == 0 {
100 continue
101 }
103 if !matchesState(discussion, opts.State) {
104 continue
105 }
107 if !matchesType(discussion, opts.Type) {
108 continue
109 }
111 if !matchesFilePath(discussion, opts.FilePath) {
112 continue
113 }
115 filtered = append(filtered, discussion)
116 }
118 return filtered
119}
121// matchesState checks if a discussion matches the requested resolution state.
122// Supported states: "resolved", "unresolved", "resolvable", or "" for all.
123func matchesState(discussion *gitlab.Discussion, state string) bool {
124 if state == "" {
125 return true
126 }
128 hasResolvableNotes := false
129 allResolved := true
131 for _, note := range discussion.Notes {
132 if note.Resolvable {
133 hasResolvableNotes = true
134 if !note.Resolved {
135 allResolved = false
136 }
137 }
138 }
140 // Non-resolvable discussions don't match any resolution filter
141 if !hasResolvableNotes {
142 return false
143 }
145 switch state {
146 case "resolved":
147 return allResolved
148 case "unresolved":
149 return !allResolved
150 case "resolvable":
151 return true // already confirmed hasResolvableNotes above
152 default:
153 return true
154 }
155}
157// matchesType checks if a discussion matches the requested type.
158func matchesType(discussion *gitlab.Discussion, typ string) bool {
159 if typ == "" {
160 return true
161 }
163 firstNote := discussion.Notes[0]
165 switch typ {
166 case "system":
167 return firstNote.System
168 case "diff":
169 return !firstNote.System && firstNote.Position != nil
170 case "general":
171 return !firstNote.System && firstNote.Position == nil
172 default:
173 return true
174 }
175}
177// ResolveDiscussionID resolves a prefix (8+ chars) to a full discussion ID.
178// Returns an error if the prefix is ambiguous or not found.
179func ResolveDiscussionID(ctx context.Context, client *gitlab.Client, projectID any, mrIID int64, prefix string) (string, error) {
180 discussion, err := ResolveDiscussion(ctx, client, projectID, mrIID, prefix)
181 if err != nil {
182 return "", err
183 }
184 return discussion.ID, nil
185}
187// ResolveDiscussion resolves a prefix (8+ chars) to the discussion it names,
188// for callers that need the thread's notes and not only its ID.
189// Returns an error if the prefix is ambiguous or not found.
190func ResolveDiscussion(ctx context.Context, client *gitlab.Client, projectID any, mrIID int64, prefix string) (*gitlab.Discussion, error) {
191 prefixLen := len(prefix)
192 if prefixLen < 8 {
193 return nil, fmt.Errorf("discussion ID prefix must be at least 8 characters, got %d", len(prefix))
194 }
195 discussions, err := ListAllDiscussions(ctx, client, projectID, mrIID, &gitlab.ListMergeRequestDiscussionsOptions{})
196 if err != nil {
197 return nil, err
198 }
199 var matches []*gitlab.Discussion
200 for _, d := range discussions {
201 if len(d.ID) >= prefixLen && d.ID[:prefixLen] == prefix {
202 matches = append(matches, d)
203 }
204 }
205 switch len(matches) {
206 case 0:
207 return nil, fmt.Errorf("no discussion found matching prefix %q", prefix)
208 case 1:
209 return matches[0], nil
210 default:
211 ids := make([]string, 0, len(matches))
212 for _, d := range matches {
213 ids = append(ids, d.ID)
214 }
215 return nil, fmt.Errorf("prefix %q matches %d discussions: %s", prefix, len(matches), formatMatches(ids))
216 }
217}
219// IsInternalDiscussion reports whether a thread is internal. GitLab tracks
220// internal per thread rather than per note, so the opening note decides it.
221func IsInternalDiscussion(discussion *gitlab.Discussion) bool {
222 if len(discussion.Notes) == 0 {
223 return false
224 }
225 return discussion.Notes[0].Internal
226}
228// formatMatches formats discussion IDs for display, truncating each to 8 chars.
229func formatMatches(matches []string) string {
230 var b strings.Builder
231 for i, m := range matches {
232 if i > 0 {
233 b.WriteString(", ")
234 }
235 b.WriteString(TruncateDiscussionID(m))
236 }
237 return b.String()
238}
240// matchesFilePath checks if a discussion is on the specified file path.
241func matchesFilePath(discussion *gitlab.Discussion, filePath string) bool {
242 if filePath == "" {
243 return true
244 }
246 firstNote := discussion.Notes[0]
247 if firstNote.Position == nil {
248 return false
249 }
251 return firstNote.Position.NewPath == filePath || firstNote.Position.OldPath == filePath
252}
Diagnostics8 git calls · 226 ms
CallStatusSizeTime0226 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 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 · 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=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 · 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=4273 git.response.cache=HIT git.response.duration_ms=3 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=2 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:0200746 B · 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=746 git.response.cache=HIT git.response.duration_ms=2 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:0200469 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=211 git.response.bytes=469 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=6020159a68b7314d330ee4ac0f7529b651d7accc 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=469 git.pkt.payload.max=442 git.sideband.band1.bytes=442 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=442 git.pack.trailer=97b1fd715810f2e169ed93a75830c9ee2eff1fc0Open pack map
fetch2002.3 KiB211 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2328 git.response.cache=MISS git.response.duration_ms=211 git.fetch.wants=b2dbf529d35fe73ef229d73c974a9b022cfa34fa 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=2328 git.pkt.payload.max=2301 git.sideband.band1.bytes=2301 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
- a5e2c1acea1a89da
- Request
- d68e417f…
- 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