GitLabgitlab-org
cli
main
1package note
3import (
4 "context"
5 "fmt"
6 "strings"
8 "github.com/MakeNowJust/heredoc/v2"
9 "github.com/spf13/cobra"
11 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
13 "gitlab.com/gitlab-org/cli/internal/cmdutils"
14 "gitlab.com/gitlab-org/cli/internal/commands/mr/mrutils"
15 "gitlab.com/gitlab-org/cli/internal/glrepo"
16 "gitlab.com/gitlab-org/cli/internal/iostreams"
17 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
18 "gitlab.com/gitlab-org/cli/internal/text"
19)
21type createOptions struct {
22 io *iostreams.IOStreams
23 factory cmdutils.Factory
24 gitlabClient func() (*gitlab.Client, error)
26 // Flags.
27 message string
28 attach []string
29 unique bool
30 reply string
31 filePath string
32 line mrutils.LineRange
33 oldLine int
34 resolvable bool
35 internal bool
37 // Populated in complete.
38 client *gitlab.Client
39 mr *gitlab.MergeRequest
40 repo glrepo.Interface
41 body string
42 position *gitlab.PositionOptions
43}
45func NewCmdCreate(f cmdutils.Factory) *cobra.Command {
46 opts := &createOptions{
47 io: f.IO(),
48 factory: f,
49 gitlabClient: f.GitLabClient,
50 }
52 cmd := &cobra.Command{
53 Use: "create [<id> | <branch>]",
54 Short: "Create a comment or discussion on a merge request. (EXPERIMENTAL)",
55 Long: heredoc.Docf(`
56 Add a comment to a merge request. By default, the command creates the comment
57 as a new discussion thread.
59 Use %[1]s--resolvable=false%[1]s to create a non-resolvable note instead.
60 Non-resolvable notes do not block merging when the project requires
61 **All threads must be resolved**. Use this option for automation or status
62 updates that do not need a human to resolve them.
64 Use %[1]s--internal%[1]s to create an internal note, which only project members can view. A reply to an internal thread is itself internal. When combined with %[1]s--reply%[1]s, %[1]s--internal%[1]s checks the target thread's visibility and fails if the thread is public. Replying to an internal thread without %[1]s--internal%[1]s still produces an internal reply.
66 Use %[1]s--reply%[1]s to add a note to an existing discussion thread instead of
67 starting a new one. The value can be a full discussion ID or a unique
68 prefix of at least 8 characters. Find discussion IDs with
69 %[1]sglab mr note list%[1]s. Human-readable output uses
70 eight characters before the ellipsis, for example
71 %[1]s[discussion: abc12345…]%[1]s; pass
72 only those characters, for example %[1]s--reply abc12345%[1]s. To get a
73 full ID, use the %[1]sid%[1]s field of each discussion object:
74 %[1]sglab mr note list -F json | jq -r '.[].id'%[1]s.
76 Use %[1]s--file%[1]s to place a diff comment on a specific file in the latest
77 merge request diff version. Combine with %[1]s--line%[1]s (new side) or
78 %[1]s--old-line%[1]s (old/removed side) to target a specific line. Omit
79 both flags for a file-level comment.
81 To add the comment to a pending review instead of publishing it immediately, use %[1]sglab mr note draft create%[1]s.
83 The flag rules are:
85 - %[1]s--line%[1]s and %[1]s--old-line%[1]s require %[1]s--file%[1]s, and
86 cannot be used together.
87 - %[1]s--file%[1]s, %[1]s--reply%[1]s, and %[1]s--unique%[1]s are mutually
88 exclusive.
89 - %[1]s--resolvable=false%[1]s cannot be combined with %[1]s--reply%[1]s
90 or %[1]s--file%[1]s (and by extension %[1]s--line%[1]s or
91 %[1]s--old-line%[1]s).
92 - %[1]s--internal%[1]s cannot be combined with %[1]s--file%[1]s
93 (and by extension %[1]s--line%[1]s or
94 %[1]s--old-line%[1]s), nor with %[1]s--resolvable=true%[1]s unless
95 %[1]s--reply%[1]s is also given.
96 - %[1]s--attach%[1]s and %[1]s--unique%[1]s are mutually exclusive,
97 because every upload gets a fresh URL and so an attached comment can
98 never match an existing one.
100 %[1]s--attach%[1]s uploads a file and references it at the end of the comment. Repeat the flag for more than one file, or pass %[1]s-%[1]s to read the file from standard input. An attachment is content on its own, so a comment with only %[1]s--attach%[1]s does not prompt for a body. When standard input is not a terminal, it is read as the comment body, unless %[1]s--attach -%[1]s reads the file from standard input. The command waits until standard input closes, so to post only the attachment from a script, redirect standard input from %[1]s/dev/null%[1]s.
101 `, "`") + text.ExperimentalString,
102 Example: heredoc.Doc(`
103 # Add a comment to merge request 123
104 glab mr note create 123 -m "Looks good to me!"
106 # Add a comment to the current branch's merge request
107 glab mr note create -m "LGTM"
109 # Open editor to compose the message
110 glab mr note create 123
112 # Pipe from stdin
113 echo "LGTM" | glab mr note create 123
115 # Read the body from a file
116 glab mr note create 123 < plan.md
118 # Skip if already posted
119 glab mr note create 123 -m "LGTM" --unique
121 # Create a non-resolvable note, for example for bot or CI status updates
122 glab mr note create 123 -m "Build status: green" --resolvable=false
124 # Create an internal note, visible only to project members
125 glab mr note create 123 -m "Rotating the leaked token now." --internal
127 # Reply to an internal thread, refusing to post if that thread is public
128 glab mr note create 123 --reply abc12345 --internal -m "Patch is ready."
130 # Reply to an existing discussion thread
131 glab mr note create 123 --reply abc12345 -m "I agree!"
133 # Add a diff comment on line 42 of main.go
134 glab mr note create 123 --file main.go --line 42 -m "Needs refactoring"
136 # Add a diff comment on lines 10-15 (multiline range)
137 glab mr note create 123 --file main.go --line 10:15 -m "Extract this block"
139 # Add a diff comment on a removed line (old side)
140 glab mr note create 123 --file main.go --old-line 7 -m "Why was this removed?"
142 # Add a file-level diff comment (no line specified)
143 glab mr note create 123 --file main.go -m "General comment on this file"
145 # Attach a screenshot alongside the message
146 glab mr note create 123 -m "Renders wrong here." --attach ./screenshot.png
148 # Attach an image piped from the clipboard
149 pngpaste - | glab mr note create 123 --attach -
150 `),
151 Args: cobra.MaximumNArgs(1),
152 Annotations: map[string]string{
153 mcpannotations.Destructive: "true",
154 },
155 RunE: func(cmd *cobra.Command, args []string) error {
156 if err := opts.validateFlags(cmd); err != nil {
157 return err
158 }
159 if err := opts.complete(cmd, args); err != nil {
160 return err
161 }
162 if err := opts.validate(); err != nil {
163 return err
164 }
165 return opts.run(cmd.Context())
166 },
167 }
169 fl := cmd.Flags()
170 fl.StringVarP(&opts.message, "message", "m", "", "Comment or note message.")
171 fl.BoolVar(&opts.unique, "unique", false, "Don't create a note if a note with the same body already exists. Reads all merge request comments first.")
172 fl.StringVar(&opts.reply, "reply", "", "Reply to an existing discussion. Accepts a full discussion ID or a unique prefix of at least 8 characters.")
173 fl.StringVar(&opts.filePath, "file", "", "File path for a diff comment, like <path/to/file>. Targets the latest merge request diff version.")
174 fl.Var(&opts.line, "line", "Line in the new version. A single line number, like 42, or a range, like 10:15.")
175 fl.IntVar(&opts.oldLine, "old-line", 0, "Line in the old version, for commenting on a removed line.")
176 fl.BoolVar(&opts.resolvable, "resolvable", true, "Create the note as a resolvable discussion thread. Set to false to create a non-resolvable note.")
177 fl.BoolVar(&opts.internal, "internal", false, "Create the note as an internal note, visible only to project members.")
178 cmdutils.AddAttachFlag(cmd, &opts.attach, "comment")
180 // Each upload gets a fresh URL, so an attached note never matches an
181 // existing one and --unique could not skip anything.
182 cmd.MarkFlagsMutuallyExclusive("unique", "attach")
183 cmd.MarkFlagsMutuallyExclusive("reply", "unique")
184 cmd.MarkFlagsMutuallyExclusive("reply", "file")
185 cmd.MarkFlagsMutuallyExclusive("unique", "file")
186 cmd.MarkFlagsMutuallyExclusive("line", "old-line")
187 cmd.MarkFlagsMutuallyExclusive("internal", "file")
189 return cmd
190}
192func (o *createOptions) complete(cmd *cobra.Command, args []string) error {
193 client, err := o.gitlabClient()
194 if err != nil {
195 return err
196 }
197 o.client = client
199 mr, repo, err := mrutils.MRFromArgs(cmd.Context(), o.factory, args, "any")
200 if err != nil {
201 return err
202 }
203 o.mr = mr
204 o.repo = repo
206 body := o.message
207 if strings.TrimSpace(body) == "" && !cmdutils.SkipNoteBody(o.io, o.attach) {
208 body, err = mrutils.NoteBodyFromStdinOrEditor(cmd.Context(), o.io, o.factory.Config)
209 if err != nil {
210 return err
211 }
212 }
213 o.body = body
215 if o.filePath != "" {
216 o.position, err = mrutils.DiffPosition(cmd.Context(), o.client, o.repo.FullName(), o.mr.IID, o.filePath, o.line, o.oldLine)
217 if err != nil {
218 return err
219 }
220 }
222 return nil
223}
225func (o *createOptions) validateFlags(cmd *cobra.Command) error {
226 if o.internal {
227 if o.reply == "" {
228 if cmd.Flags().Changed("resolvable") && o.resolvable {
229 return fmt.Errorf("--internal cannot be used with --resolvable=true")
230 }
231 o.resolvable = false
232 }
233 }
235 if !o.resolvable {
236 if o.reply != "" {
237 return fmt.Errorf("--resolvable=false cannot be used with --reply")
238 }
239 if o.filePath != "" {
240 return fmt.Errorf("--resolvable=false cannot be used with --file, --line, or --old-line")
241 }
242 }
243 return nil
244}
246func (o *createOptions) validate() error {
247 if strings.TrimSpace(o.body) == "" && len(o.attach) == 0 {
248 return fmt.Errorf("aborted: note has an empty message")
249 }
250 if o.reply != "" && len(o.reply) < 8 {
251 return fmt.Errorf("discussion ID prefix must be at least 8 characters, got %d", len(o.reply))
252 }
253 if (o.line.Start != 0 || o.oldLine != 0) && o.filePath == "" {
254 return fmt.Errorf("--line and --old-line require --file")
255 }
256 return nil
257}
259func (o *createOptions) run(ctx context.Context) error {
260 body, err := cmdutils.AppendAttachments(ctx, o.io, o.client, o.repo.FullName(), o.body, o.attach)
261 if err != nil {
262 return err
263 }
264 o.body = body
266 switch {
267 case o.reply != "":
268 return o.runReply(ctx)
269 case o.unique:
270 found, err := deduplicateNote(o.io, o.client, o.repo.FullName(), o.mr.IID, o.body, o.mr.WebURL)
271 if err != nil {
272 return err
273 }
274 if found {
275 return nil
276 }
277 }
279 if !o.resolvable {
280 return o.runCreateNote(ctx)
281 }
282 return o.runCreate(ctx)
283}
285func (o *createOptions) runCreate(ctx context.Context) error {
286 createOpts := &gitlab.CreateMergeRequestDiscussionOptions{Body: &o.body}
287 if o.position != nil {
288 createOpts.Position = o.position
289 }
291 disc, _, err := o.client.Discussions.CreateMergeRequestDiscussion(
292 o.repo.FullName(),
293 o.mr.IID,
294 createOpts,
295 gitlab.WithContext(ctx),
296 )
297 if err != nil {
298 return fmt.Errorf("failed to create discussion: %w", err)
299 }
301 if len(disc.Notes) == 0 {
302 return fmt.Errorf("discussion created but returned no notes")
303 }
305 o.io.LogInfof("%s#note_%d\n", o.mr.WebURL, disc.Notes[0].ID)
306 return nil
307}
309func (o *createOptions) runCreateNote(ctx context.Context) error {
310 createOpts := &gitlab.CreateMergeRequestNoteOptions{Body: &o.body}
311 if o.internal {
312 createOpts.Internal = &o.internal
313 }
315 note, _, err := o.client.Notes.CreateMergeRequestNote(
316 o.repo.FullName(),
317 o.mr.IID,
318 createOpts,
319 gitlab.WithContext(ctx),
320 )
321 if err != nil {
322 return fmt.Errorf("failed to create note: %w", err)
323 }
325 o.io.LogInfof("%s#note_%d\n", o.mr.WebURL, note.ID)
326 return nil
327}
329func (o *createOptions) runReply(ctx context.Context) error {
330 discussion, err := mrutils.ResolveDiscussion(ctx, o.client, o.repo.FullName(), o.mr.IID, o.reply)
331 if err != nil {
332 return err
333 }
334 discussionID := discussion.ID
336 if o.internal && !mrutils.IsInternalDiscussion(discussion) {
337 return fmt.Errorf(
338 "--internal was requested but discussion %s is not internal, so the reply would be publicly visible",
339 mrutils.TruncateDiscussionID(discussionID),
340 )
341 }
343 note, _, err := o.client.Discussions.AddMergeRequestDiscussionNote(
344 o.repo.FullName(),
345 o.mr.IID,
346 discussionID,
347 &gitlab.AddMergeRequestDiscussionNoteOptions{Body: &o.body},
348 gitlab.WithContext(ctx),
349 )
350 if err != nil {
351 return fmt.Errorf("failed to add reply: %w", err)
352 }
354 o.io.LogInfof("%s#note_%d\n", o.mr.WebURL, note.ID)
355 return nil
356}
Diagnostics8 git calls · 356 ms
CallStatusSizeTime0356 ms
discover200185 B4 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch 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 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 · 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=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
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=3 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=2 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=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:0200540 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=340 git.response.bytes=540 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=d1be7f980a856805fa31e30e01fff4db335cbe1b 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=540 git.pkt.payload.max=513 git.sideband.band1.bytes=513 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=513 git.pack.trailer=6c82398efd91c9e023d583b948fde889bd4991b2Open pack map
fetch2003.9 KiB340 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=3960 git.response.cache=MISS git.response.duration_ms=340 git.fetch.wants=516fd3577e73b2abd876c0e3e40281532f9ada2a 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=3960 git.pkt.payload.max=3933 git.sideband.band1.bytes=3933 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
- a5e29d322eb2c465
- Request
- c7b80c03…
- 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