GitLabgitlab-org

cli

main
ply8 git calls212 ms100 KiB5 cachedprotocol v2
338 lines10.0 KiBRaw
1package view
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/api"
14 "gitlab.com/gitlab-org/cli/internal/cmdutils"
15 "gitlab.com/gitlab-org/cli/internal/commands/issuable"
16 "gitlab.com/gitlab-org/cli/internal/commands/issue/issueutils"
17 "gitlab.com/gitlab-org/cli/internal/config"
18 "gitlab.com/gitlab-org/cli/internal/glrepo"
19 "gitlab.com/gitlab-org/cli/internal/iostreams"
20 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
21 "gitlab.com/gitlab-org/cli/internal/utils"
24var listIssueNotes = func(ctx context.Context, client *gitlab.Client, projectID any, issueID int64, opts *gitlab.ListIssueNotesOptions) ([]*gitlab.Note, error) {
25 if opts.PerPage == 0 {
26 opts.PerPage = api.DefaultListLimit
27 }
28 return gitlab.ScanAndCollect(func(p gitlab.PaginationOptionFunc) ([]*gitlab.Note, *gitlab.Response, error) {
29 return client.Notes.ListIssueNotes(projectID, issueID, opts, p, gitlab.WithContext(ctx))
30 })
33type IssueWithNotes struct {
34 *gitlab.Issue
35 Notes []*gitlab.Note
38type options struct {
39 showComments bool
40 showSystemLogs bool
41 web bool
42 outputFormat string
44 commentPageNumber int
45 commentLimit int
47 notes []*gitlab.Note
48 issue *gitlab.Issue
50 io *iostreams.IOStreams
51 apiClient func(repoHost string) (*api.Client, error)
52 gitlabClient func() (*gitlab.Client, error)
53 config func() config.Config
54 baseRepo func() (glrepo.Interface, error)
55 defaultHostname string
58func NewCmdView(f cmdutils.Factory, issueType issuable.IssueType) *cobra.Command {
59 examplePath := "issues/123"
61 if issueType == issuable.TypeIncident {
62 examplePath = "issues/incident/123"
63 }
65 opts := &options{
66 io: f.IO(),
67 apiClient: f.ApiClient,
68 gitlabClient: f.GitLabClient,
69 config: f.Config,
70 baseRepo: f.BaseRepo,
71 defaultHostname: f.DefaultHostname(),
72 }
73 issueViewCmd := &cobra.Command{
74 Use: "view <id>",
75 Short: fmt.Sprintf(`Display the title, body, and other information about an %s.`, issueType),
76 Long: heredoc.Docf(`
77 You can use a full GitLab URL instead of an ID. Use %[1]s--web%[1]s
78 to open in a browser.
79 `, "`"),
80 Aliases: []string{"show"},
81 Example: heredoc.Doc(fmt.Sprintf(`
82 glab %[1]s view 123
83 glab %[1]s show 123
84 glab %[1]s view --web 123
85 glab %[1]s view --comments 123
86 glab %[1]s view https://gitlab.com/NAMESPACE/REPO/-/%s`, issueType, examplePath)),
87 Args: cobra.ExactArgs(1),
88 Annotations: map[string]string{
89 mcpannotations.Safe: "true",
90 },
91 RunE: func(cmd *cobra.Command, args []string) error {
92 return opts.run(cmd.Context(), issueType, args)
93 },
94 }
96 issueViewCmd.Flags().BoolVarP(&opts.showComments, "comments", "c", false, fmt.Sprintf("Show %s comments and activities.", issueType))
97 issueViewCmd.Flags().BoolVarP(&opts.showSystemLogs, "system-logs", "s", false, "Show system activities and logs.")
98 issueViewCmd.Flags().BoolVarP(&opts.web, "web", "w", false, fmt.Sprintf("Open %s in a browser. Uses the default browser, or the browser specified in the $BROWSER variable.", issueType))
99 issueViewCmd.Flags().IntVarP(&opts.commentPageNumber, "page", "p", 1, "Page number.")
100 issueViewCmd.Flags().IntVarP(&opts.commentLimit, "per-page", "P", 20, "Number of items to list per page.")
101 cmdutils.EnableJSONOutput(issueViewCmd, opts.io, &opts.outputFormat)
103 return issueViewCmd
106func (o *options) run(ctx context.Context, issueType issuable.IssueType, args []string) error {
107 client, err := o.gitlabClient()
108 if err != nil {
109 return err
110 }
111 cfg := o.config()
113 issue, baseRepo, err := issueutils.IssueFromArg(o.apiClient, client, o.baseRepo, o.defaultHostname, cfg, args[0])
114 if err != nil {
115 return err
116 }
118 o.issue = issue
120 valid, msg := issuable.ValidateIncidentCmd(issueType, "view", o.issue)
121 if !valid {
122 o.io.LogError(msg)
123 return nil
124 }
126 // open in browser if --web flag is specified
127 if o.web {
128 if o.io.IsaTTY && o.io.IsErrTTY {
129 o.io.LogErrorf("Opening %s in your browser.\n", utils.DisplayURL(o.issue.WebURL))
130 }
132 browser, _ := cfg.Get(baseRepo.RepoHost(), "browser")
133 return utils.OpenInBrowser(o.issue.WebURL, browser)
134 }
136 if o.showComments {
137 l := &gitlab.ListIssueNotesOptions{
138 Sort: new("asc"),
139 }
140 if o.commentPageNumber != 0 {
141 l.Page = int64(o.commentPageNumber)
142 }
143 if o.commentLimit != 0 {
144 l.PerPage = int64(o.commentLimit)
145 }
146 o.notes, err = listIssueNotes(ctx, client, baseRepo.FullName(), o.issue.IID, l)
147 if err != nil {
148 return err
149 }
150 }
152 glamourStyle, _ := cfg.Get(baseRepo.RepoHost(), "glamour_style")
153 o.io.ResolveBackgroundColor(glamourStyle)
154 err = o.io.StartPager()
155 if err != nil {
156 return err
157 }
158 defer o.io.StopPager()
160 switch {
161 case o.outputFormat == "json":
162 return printJSONIssue(o)
163 case o.io.IsErrTTY && o.io.IsaTTY:
164 printTTYIssuePreview(o)
165 default:
166 printRawIssuePreview(o)
167 }
168 return nil
171func labelsList(opts *options) string {
172 return strings.Join(opts.issue.Labels, ", ")
175func assigneesList(opts *options) string {
176 assignees := utils.Map(opts.issue.Assignees, func(a *gitlab.IssueAssignee) string {
177 return a.Username
178 })
180 return strings.Join(assignees, ", ")
183func issueState(opts *options, c *iostreams.ColorPalette) string {
184 switch opts.issue.State {
185 case "opened":
186 return c.Green("open")
187 case "locked":
188 return c.Blue(opts.issue.State)
189 default:
190 return c.Red(opts.issue.State)
191 }
194func printTTYIssuePreview(opts *options) {
195 c := opts.io.Color()
196 issueTimeAgo := utils.TimeToPrettyTimeAgo(*opts.issue.CreatedAt)
197 // Header
198 opts.io.LogInfof("%s", issueState(opts, c))
199 opts.io.LogInfof(c.Gray(" • opened by %s %s\n"), opts.issue.Author.Username, issueTimeAgo)
200 opts.io.LogInfof("%s", c.Bold(opts.issue.Title))
201 opts.io.LogInfof(c.Gray(" #%d"), opts.issue.IID)
202 opts.io.LogInfo()
204 // Description
205 if opts.issue.Description != "" {
206 opts.issue.Description, _ = utils.RenderMarkdown(opts.issue.Description, opts.io.BackgroundColor())
207 opts.io.LogInfo(opts.issue.Description)
208 }
210 opts.io.LogInfof(c.Gray("\n%d upvotes • %d downvotes • %d comments\n"), opts.issue.Upvotes, opts.issue.Downvotes, opts.issue.UserNotesCount)
212 // Meta information
213 if labels := labelsList(opts); labels != "" {
214 opts.io.LogInfof("%s", c.Bold("Labels: "))
215 opts.io.LogInfo(labels)
216 }
217 if assignees := assigneesList(opts); assignees != "" {
218 opts.io.LogInfof("%s", c.Bold("Assignees: "))
219 opts.io.LogInfo(assignees)
220 }
221 if opts.issue.Milestone != nil {
222 opts.io.LogInfof("%s", c.Bold("Milestone: "))
223 opts.io.LogInfo(opts.issue.Milestone.Title)
224 }
225 if timeStats := utils.FormatTimeStats(opts.issue.TimeStats); timeStats != "" {
226 opts.io.LogInfof("%s", c.Bold("Time tracking: "))
227 opts.io.LogInfo(timeStats)
228 }
229 if opts.issue.State == "closed" && opts.issue.ClosedBy != nil {
230 if opts.issue.ClosedAt != nil {
231 opts.io.LogInfof("Closed by: %s %s\n", opts.issue.ClosedBy.Username, utils.TimeToPrettyTimeAgo(*opts.issue.ClosedAt))
232 } else {
233 opts.io.LogInfof("Closed by: %s\n", opts.issue.ClosedBy.Username)
234 }
235 }
237 // Comments
238 if opts.showComments {
239 opts.io.LogInfo(heredoc.Doc(`
240 --------------------------------------------
241 Comments / Notes
242 --------------------------------------------
243 `))
244 if len(opts.notes) > 0 {
245 for _, note := range opts.notes {
246 if note.System && !opts.showSystemLogs {
247 continue
248 }
249 createdAt := utils.TimeToPrettyTimeAgo(*note.CreatedAt)
250 opts.io.LogInfof("%s", note.Author.Username)
251 if note.System {
252 opts.io.LogInfof(" %s ", note.Body)
253 opts.io.LogInfo(c.Gray(createdAt))
254 } else {
255 body, _ := utils.RenderMarkdown(note.Body, opts.io.BackgroundColor())
256 opts.io.LogInfof("%s", " commented ")
257 opts.io.LogInfof(c.Gray("%s\n"), createdAt)
258 opts.io.LogInfo(utils.Indent(body, " "))
259 }
260 opts.io.LogInfo()
261 }
262 } else {
263 opts.io.LogInfof("There are no comments on this %s.\n", *opts.issue.IssueType)
264 }
265 }
267 opts.io.LogInfof(c.Gray("\nView this %s on GitLab: %s\n"), *opts.issue.IssueType, opts.issue.WebURL)
270func printRawIssuePreview(opts *options) {
271 opts.io.LogInfof("%s", rawIssuePreview(opts))
274func rawIssuePreview(opts *options) string {
275 var out string
277 assignees := assigneesList(opts)
278 labels := labelsList(opts)
280 out += fmt.Sprintf("title:\t%s\n", opts.issue.Title)
281 out += fmt.Sprintf("state:\t%s\n", issueState(opts, opts.io.Color()))
282 out += fmt.Sprintf("author:\t%s\n", opts.issue.Author.Username)
283 out += fmt.Sprintf("labels:\t%s\n", labels)
284 out += fmt.Sprintf("comments:\t%d\n", opts.issue.UserNotesCount)
285 out += fmt.Sprintf("assignees:\t%s\n", assignees)
286 if opts.issue.Milestone != nil {
287 out += fmt.Sprintf("milestone:\t%s\n", opts.issue.Milestone.Title)
288 }
289 if ts := opts.issue.TimeStats; ts != nil {
290 if ts.HumanTimeEstimate != "" {
291 out += fmt.Sprintf("time_estimate:\t%s\n", ts.HumanTimeEstimate)
292 }
293 if ts.HumanTotalTimeSpent != "" {
294 out += fmt.Sprintf("time_spent:\t%s\n", ts.HumanTotalTimeSpent)
295 }
296 }
298 out += "--\n"
299 out += fmt.Sprintf("%s\n", opts.issue.Description)
301 out += RawIssuableNotes(opts.notes, opts.showComments, opts.showSystemLogs, *opts.issue.IssueType)
303 return out
306// RawIssuableNotes returns a list of comments/notes in a raw format
307func RawIssuableNotes(notes []*gitlab.Note, showComments bool, showSystemLogs bool, issuableName string) string {
308 var out strings.Builder
310 if showComments {
311 out.WriteString("\n--\ncomments/notes:\n\n")
313 if len(notes) > 0 {
314 for _, note := range notes {
315 if note.System && !showSystemLogs {
316 continue
317 }
319 if note.System {
320 out.WriteString(fmt.Sprintf("%s %s %s\n\n", note.Author.Username, note.Body, note.CreatedAt.String()))
321 } else {
322 out.WriteString(fmt.Sprintf("%s commented %s\n%s\n\n", note.Author.Username, note.CreatedAt.String(), note.Body))
323 }
324 }
325 } else {
326 out.WriteString(fmt.Sprintf("There are no comments on this %s.\n", issuableName))
327 }
328 }
330 return out.String()
333func printJSONIssue(opts *options) error {
334 if opts.showComments {
335 return opts.io.PrintJSON(IssueWithNotes{opts.issue, opts.notes})
336 }
337 return opts.io.PrintJSON(opts.issue)
Diagnostics8 git calls · 212 ms
CallStatusSizeTime0212 ms
discover200185 B2 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
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=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=44
Open 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=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200347 B · hit2 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=347
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=73f6a798386c4a4df64da0b5349881ded38885ca
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=347
git.pkt.payload.max=320
git.sideband.band1.bytes=320
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=320
git.pack.trailer=93ed36ed1884d41429801c50b3bb5d32ef1307a5
Open pack map
fetchtree:0200146 B · hit4 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=198
git.response.bytes=146
git.response.cache=HIT
git.response.duration_ms=4
git.fetch.filter=tree:0
git.fetch.wants=76f74c7ffb6e1a64159176b8d07902c6f1372aa4
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=146
git.pkt.payload.max=119
git.sideband.band1.bytes=119
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=119
git.pack.trailer=a5b18fdffd274e7e74004f293f0ecce889495839
Open pack map
fetch2003.1 KiB199 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=3225
git.response.cache=MISS
git.response.duration_ms=199
git.fetch.wants=07f46af84dd69ac4b14dc1d76acfb07671fb8755
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=3225
git.pkt.payload.max=3198
git.sideband.band1.bytes=3198
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
a5e2e84a1f6cecfa
Request
828f83b0…
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