GitLabgitlab-org
cli
main
1package mrutils
3import (
4 "context"
5 "crypto/sha1"
6 "fmt"
7 "strconv"
8 "strings"
10 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
12 "gitlab.com/gitlab-org/cli/internal/diff"
13)
15// LineRange is the value of a --line flag: a single new-side line like "42"
16// or a range like "10:15". It parses during flag parsing, so a malformed value
17// fails before a command prompts for a comment body. The zero value means no
18// line.
19type LineRange struct {
20 Start, End int
21}
23func (r *LineRange) String() string {
24 switch {
25 case r.Start == 0:
26 return ""
27 case r.Start == r.End:
28 return strconv.Itoa(r.Start)
29 default:
30 return fmt.Sprintf("%d:%d", r.Start, r.End)
31 }
32}
34func (r *LineRange) Set(s string) error {
35 start, end, err := parseLine(s)
36 if err != nil {
37 return err
38 }
39 r.Start, r.End = start, end
40 return nil
41}
43func (r *LineRange) Type() string {
44 return "string"
45}
47// DiffPosition resolves a file path and a --line or --old-line value into a
48// diff position on the latest merge request diff version. Leave lines and
49// oldLine zero for a file-level comment.
50func DiffPosition(ctx context.Context, client *gitlab.Client, project string, mrIID int64, filePath string, lines LineRange, oldLine int) (*gitlab.PositionOptions, error) {
51 version, err := latestDiffVersion(ctx, client, project, mrIID)
52 if err != nil {
53 return nil, err
54 }
56 fileDiff, err := findFileDiff(version, filePath)
57 if err != nil {
58 return nil, err
59 }
61 return buildDiffPosition(version, fileDiff, lines.Start, lines.End, oldLine)
62}
64// latestDiffVersion returns the latest MR diff version with its diffs included.
65func latestDiffVersion(ctx context.Context, client *gitlab.Client, project string, mrIID int64) (*gitlab.MergeRequestDiffVersion, error) {
66 versions, _, err := client.MergeRequests.GetMergeRequestDiffVersions(project, mrIID, nil, gitlab.WithContext(ctx))
67 if err != nil {
68 return nil, fmt.Errorf("failed to list MR diff versions: %w", err)
69 }
70 if len(versions) == 0 {
71 return nil, fmt.Errorf("no diff versions found for MR !%d", mrIID)
72 }
73 // The API lists versions newest first.
74 latest := versions[0]
75 full, _, err := client.MergeRequests.GetSingleMergeRequestDiffVersion(project, mrIID, latest.ID, nil, gitlab.WithContext(ctx))
76 if err != nil {
77 return nil, fmt.Errorf("failed to fetch diff version %d: %w", latest.ID, err)
78 }
79 return full, nil
80}
82// findFileDiff finds a file's diff in the given version by matching NewPath or OldPath.
83func findFileDiff(version *gitlab.MergeRequestDiffVersion, filePath string) (*gitlab.Diff, error) {
84 for _, d := range version.Diffs {
85 if d.NewPath == filePath || d.OldPath == filePath {
86 return d, nil
87 }
88 }
89 return nil, fmt.Errorf("file %q not found in MR diff", filePath)
90}
92// buildDiffPosition builds a PositionOptions for a diff comment.
93// lineStart/lineEnd refer to new-side lines (lineEnd > lineStart for multiline).
94// oldLine refers to an old-side (removed) line.
95// For file-level comments, pass lineStart=0 and oldLine=0.
96//
97// When targeting an "unchanged" (context) line, both OldLine and NewLine must be
98// set in the position — GitLab's API requires both sides for context lines.
99// For added lines only NewLine is set; for removed lines only OldLine.
100// Reference implementation: GitLab VS Code Extension, see
101// https://gitlab.com/gitlab-org/gitlab-vscode-extension/-/blob/main/src/common/services/mr/create_comment.ts
102func buildDiffPosition(version *gitlab.MergeRequestDiffVersion, fileDiff *gitlab.Diff, lineStart, lineEnd, oldLine int) (*gitlab.PositionOptions, error) {
103 pos := &gitlab.PositionOptions{
104 BaseSHA: new(version.BaseCommitSHA),
105 HeadSHA: new(version.HeadCommitSHA),
106 StartSHA: new(version.StartCommitSHA),
107 NewPath: new(fileDiff.NewPath),
108 OldPath: new(fileDiff.OldPath),
109 PositionType: new("text"),
110 }
112 lines := diff.Parse(fileDiff.Diff)
114 switch {
115 case lineStart == 0 && oldLine == 0:
116 // File-level comment: target first available line
117 if len(lines) == 0 {
118 return nil, fmt.Errorf("diff for %s is empty, cannot place a comment", fileDiff.NewPath)
119 }
120 for _, l := range lines {
121 switch l.Type {
122 case diff.Added:
123 pos.NewLine = new(int64(l.NewLine))
124 return pos, nil
125 case diff.Removed:
126 pos.OldLine = new(int64(l.OldLine))
127 return pos, nil
128 case diff.Unchanged:
129 if l.NewLine > 0 {
130 pos.NewLine = new(int64(l.NewLine))
131 pos.OldLine = new(int64(l.OldLine))
132 return pos, nil
133 }
134 }
135 }
136 return nil, fmt.Errorf("no targetable line found in diff for %s", fileDiff.NewPath)
138 case oldLine > 0:
139 // Targeting an old-side (removed) line.
140 correspondingNewLine, lt, err := diff.FindOldLine(lines, oldLine)
141 if err != nil {
142 return nil, fmt.Errorf("old line %d not found in diff for %s", oldLine, fileDiff.OldPath)
143 }
144 pos.OldLine = new(int64(oldLine))
145 if lt == diff.Unchanged {
146 pos.NewLine = new(int64(correspondingNewLine))
147 }
149 case lineEnd > lineStart:
150 // Multiline range on the new side.
151 // GitLab attaches the note at new_line/old_line, so those must
152 // reference the *end* of the range; line_range defines the
153 // highlighted span.
154 startOld, startLT, err := diff.FindNewLine(lines, lineStart)
155 if err != nil {
156 return nil, fmt.Errorf("line %d not found in diff for %s", lineStart, fileDiff.NewPath)
157 }
158 endOld, endLT, err := diff.FindNewLine(lines, lineEnd)
159 if err != nil {
160 return nil, fmt.Errorf("line %d not found in diff for %s", lineEnd, fileDiff.NewPath)
161 }
162 pos.NewLine = new(int64(lineEnd))
163 if endLT == diff.Unchanged {
164 pos.OldLine = new(int64(endOld))
165 }
167 startPos := &gitlab.LinePositionOptions{
168 LineCode: new(lineCode(fileDiff.NewPath, lineStart)),
169 Type: new("new"),
170 NewLine: new(int64(lineStart)),
171 }
172 if startLT == diff.Unchanged {
173 startPos.OldLine = new(int64(startOld))
174 }
176 endPos := &gitlab.LinePositionOptions{
177 LineCode: new(lineCode(fileDiff.NewPath, lineEnd)),
178 Type: new("new"),
179 NewLine: new(int64(lineEnd)),
180 }
181 if endLT == diff.Unchanged {
182 endPos.OldLine = new(int64(endOld))
183 }
185 pos.LineRange = &gitlab.LineRangeOptions{
186 Start: startPos,
187 End: endPos,
188 }
190 default:
191 // Single new-side line.
192 oldLineNum, lt, err := diff.FindNewLine(lines, lineStart)
193 if err != nil {
194 return nil, fmt.Errorf("line %d not found in diff for %s", lineStart, fileDiff.NewPath)
195 }
196 pos.NewLine = new(int64(lineStart))
197 if lt == diff.Unchanged {
198 pos.OldLine = new(int64(oldLineNum))
199 }
200 }
202 return pos, nil
203}
205// parseLine parses a line flag value like "42" or "10:15" into start and end line numbers.
206// For a single line, start == end.
207func parseLine(s string) (int, int, error) {
208 if s == "" {
209 return 0, 0, nil
210 }
211 parts := strings.SplitN(s, ":", 2)
212 start, err := strconv.Atoi(parts[0])
213 if err != nil {
214 return 0, 0, fmt.Errorf("invalid line number %q", s)
215 }
216 if start <= 0 {
217 return 0, 0, fmt.Errorf("line number must be positive, got %d", start)
218 }
219 if len(parts) == 2 {
220 end, err := strconv.Atoi(parts[1])
221 if err != nil {
222 return 0, 0, fmt.Errorf("invalid line range %q", s)
223 }
224 if end < start {
225 return 0, 0, fmt.Errorf("invalid line range %q: end must be >= start", s)
226 }
227 return start, end, nil
228 }
229 return start, start, nil
230}
232// lineCode generates a GitLab line_code for multiline ranges.
233// Format: sha1(file_path)_oldline_newline
234func lineCode(path string, line int) string {
235 h := sha1.Sum([]byte(path))
236 return fmt.Sprintf("%x_%d_%d", h, 0, line)
237}
Diagnostics8 git calls · 214 ms
CallStatusSizeTime0214 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 · 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=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:0 · deepen 1020032 KiB · hit6 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=6 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 · hit1 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=1 git.response.bytes=746 git.response.cache=HIT git.response.duration_ms=1 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=3 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.4 KiB202 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=202 git.response.bytes=2449 git.response.cache=MISS git.response.duration_ms=202 git.fetch.wants=24dae8eb909e2adea075026efe17bc9cdcc192b1 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=2449 git.pkt.payload.max=2422 git.sideband.band1.bytes=2422 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
- a5e2bb150ffacfc3
- Request
- 4a2885d0…
- 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