GitLabgitlab-org

cli

main
ply8 git calls424 ms100 KiB5 cachedprotocol v2
230 lines5.7 KiBRaw
1// adapted from https://github.com/cli/cli/blob/trunk/pkg/cmd/pr/diff/diff.go
2package diff
4import (
5 "bufio"
6 "bytes"
7 "context"
8 "errors"
9 "fmt"
10 "io"
11 "strings"
12 "syscall"
14 "github.com/MakeNowJust/heredoc/v2"
15 "github.com/spf13/cobra"
17 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
19 "gitlab.com/gitlab-org/cli/internal/cmdutils"
20 "gitlab.com/gitlab-org/cli/internal/commands/mr/mrutils"
21 "gitlab.com/gitlab-org/cli/internal/iostreams"
22 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
25type options struct {
26 factory cmdutils.Factory
27 io *iostreams.IOStreams
29 args []string
30 useColor string
31 rawDiff bool
34func NewCmdDiff(f cmdutils.Factory, runF func(*options) error) *cobra.Command {
35 opts := &options{
36 factory: f,
37 io: f.IO(),
38 }
40 cmd := &cobra.Command{
41 Use: "diff [<id> | <branch>]",
42 Short: "View changes in a merge request.",
43 Long: heredoc.Docf(`
44 Defaults to the currently checked-out branch. Use %[1]s--color=never%[1]s
45 to disable color output.
47 For automated scripts or patch tools, use %[1]s--raw%[1]s for an unmodified Git patch.
48 `, "`"),
49 Example: heredoc.Doc(`
50 glab mr diff 123
51 glab mr diff branch
53 # Get merge request from current branch
54 glab mr diff
56 glab mr diff 123 --color=never`),
57 Args: cobra.MaximumNArgs(1),
58 Annotations: map[string]string{
59 mcpannotations.Safe: "true",
60 },
61 RunE: func(cmd *cobra.Command, args []string) error {
62 opts.complete(args)
64 if err := opts.validate(cmd); err != nil {
65 return err
66 }
68 if runF != nil {
69 return runF(opts)
70 }
71 return opts.run(cmd.Context())
72 },
73 }
75 cmd.Flags().StringVar(&opts.useColor, "color", "auto", "Use color in diff output: always, never, auto.")
76 cmd.Flags().BoolVar(&opts.rawDiff, "raw", false, "Use raw diff format that can be piped to commands.")
78 return cmd
81func (o *options) complete(args []string) {
82 if len(args) > 0 {
83 o.args = args
84 }
86 if o.useColor == "auto" && !o.io.IsaTTY {
87 o.useColor = "never"
88 }
91func (o *options) validate(cmd *cobra.Command) error {
92 if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(o.args) == 0 {
93 return &cmdutils.FlagError{Err: errors.New("argument required when using the --repo flag")}
94 }
96 if !validColorFlag(o.useColor) {
97 return &cmdutils.FlagError{Err: fmt.Errorf("did not understand color %q: expected one of 'always', 'never', or 'auto'", o.useColor)}
98 }
100 return nil
103func (o *options) run(ctx context.Context) error {
104 client, err := o.factory.GitLabClient()
105 if err != nil {
106 return err
107 }
108 mr, baseRepo, err := mrutils.MRFromArgs(ctx, o.factory, o.args, "any")
109 if err != nil {
110 return err
111 }
113 diffOut := &bytes.Buffer{}
115 if o.rawDiff {
116 rawDiff, _, err := client.MergeRequests.ShowMergeRequestRawDiffs(baseRepo.FullName(), mr.IID, nil)
117 if err != nil {
118 return fmt.Errorf("could not obtain raw diff: %w", err)
119 }
121 diffOut.Write(rawDiff)
122 } else {
123 diffs, _, err := client.MergeRequests.GetMergeRequestDiffVersions(baseRepo.FullName(), mr.IID, &gitlab.GetMergeRequestDiffVersionsOptions{})
124 if err != nil {
125 return fmt.Errorf("could not find merge request diffs: %w", err)
126 }
127 if len(diffs) == 0 {
128 return fmt.Errorf("no merge request diffs found")
129 }
131 // diff versions are returned by the API in order of most recent first
132 diff := diffs[0]
134 // the diffs are not included in the GetMergeRequestDiffVersions so we query for the diff version
135 diffVersion, _, err := client.MergeRequests.GetSingleMergeRequestDiffVersion(baseRepo.FullName(), mr.IID, diff.ID, &gitlab.GetSingleMergeRequestDiffVersionOptions{})
136 if err != nil {
137 return fmt.Errorf("could not find merge request diff: %w", err)
138 }
139 for _, diffLine := range diffVersion.Diffs {
140 oldPath := "a/" + diffLine.OldPath
141 newPath := "b/" + diffLine.NewPath
143 if diffLine.NewFile {
144 oldPath = "/dev/null"
145 }
146 if diffLine.DeletedFile {
147 newPath = "/dev/null"
148 }
150 // output standard unified diff headers
151 diffOut.WriteString("diff --git a/" + diffLine.OldPath + " b/" + diffLine.NewPath + "\n")
153 switch {
154 case diffLine.NewFile:
155 diffOut.WriteString("new file mode " + diffLine.BMode + "\n")
156 case diffLine.DeletedFile:
157 diffOut.WriteString("deleted file mode " + diffLine.AMode + "\n")
158 case diffLine.RenamedFile:
159 diffOut.WriteString("rename from " + diffLine.OldPath + "\n")
160 diffOut.WriteString("rename to " + diffLine.NewPath + "\n")
161 }
163 diffOut.WriteString("--- " + oldPath + "\n")
164 diffOut.WriteString("+++ " + newPath + "\n")
166 diffOut.WriteString(diffLine.Diff)
167 }
169 defer diffOut.Reset()
170 }
172 err = o.io.StartPager()
173 if err != nil {
174 return err
175 }
176 defer o.io.StopPager()
178 if o.useColor == "never" {
179 _, err = io.Copy(o.io.StdOut, diffOut)
180 if errors.Is(err, syscall.EPIPE) {
181 return nil
182 }
183 return err
184 }
186 diffLines := bufio.NewScanner(diffOut)
187 diffLines.Buffer(nil, max(bufio.MaxScanTokenSize, diffOut.Len()+1))
188 for diffLines.Scan() {
189 diffLine := diffLines.Text()
190 switch {
191 case isHeaderLine(diffLine):
192 o.io.LogInfof("\x1b[1;38m%s\x1b[m\n", diffLine)
193 case isAdditionLine(diffLine):
194 o.io.LogInfof("\x1b[32m%s\x1b[m\n", diffLine)
195 case isRemovalLine(diffLine):
196 o.io.LogInfof("\x1b[31m%s\x1b[m\n", diffLine)
197 default:
198 o.io.LogInfo(diffLine)
199 }
200 }
202 if err := diffLines.Err(); err != nil {
203 return fmt.Errorf("error reading merge request diff: %w", err)
204 }
206 return nil
209var diffHeaderPrefixes = []string{"+++", "---", "diff", "index"}
211func isHeaderLine(dl string) bool {
212 for _, p := range diffHeaderPrefixes {
213 if strings.HasPrefix(dl, p) {
214 return true
215 }
216 }
217 return false
220func isAdditionLine(dl string) bool {
221 return strings.HasPrefix(dl, "+")
224func isRemovalLine(dl string) bool {
225 return strings.HasPrefix(dl, "-")
228func validColorFlag(c string) bool {
229 return c == "auto" || c == "always" || c == "never"
Diagnostics8 git calls · 424 ms
CallStatusSizeTime0424 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 KiB188 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=173
git.response.bytes=59849
git.response.cache=EXPIRED
git.response.duration_ms=188
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 · 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
fetchtree:02001.8 KiB · 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=1857
git.response.cache=HIT
git.response.duration_ms=1
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: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=330baf80c59a4208b55120dff7dd824b7952b790
Open pack map
fetchtree:0200136 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=136
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=8d144ed38cf935c4def8f07fe1832acf89ea7583
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=136
git.pkt.payload.max=109
git.sideband.band1.bytes=109
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=109
git.pack.trailer=6bea258413f6de0b4ea7e49b6d6c1baeaa503210
Open pack map
fetch2002.2 KiB226 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=226
git.response.bytes=2221
git.response.cache=MISS
git.response.duration_ms=226
git.fetch.wants=b659b173ce3256cd57470753a6bbe5785a4fd56f
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=2221
git.pkt.payload.max=2194
git.sideband.band1.bytes=2194
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
a5e250d1ec8eb071
Request
de2f716b…
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