GitLabgitlab-org
cli
main
1package api
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "maps"
11 "net/http"
12 "net/url"
13 "os"
14 "regexp"
15 "slices"
16 "sort"
17 "strconv"
18 "strings"
19 "time"
21 "github.com/MakeNowJust/heredoc/v2"
22 "github.com/spf13/cobra"
23 jsonPretty "github.com/tidwall/pretty"
25 "gitlab.com/gitlab-org/cli/internal/api"
26 "gitlab.com/gitlab-org/cli/internal/cmdutils"
27 "gitlab.com/gitlab-org/cli/internal/glinstance"
28 "gitlab.com/gitlab-org/cli/internal/glrepo"
29 "gitlab.com/gitlab-org/cli/internal/iostreams"
30 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
31)
33type options struct {
34 io *iostreams.IOStreams
36 apiClient func(repoHost string) (*api.Client, error)
37 baseRepo func() (glrepo.Interface, error)
38 branch func() (string, error)
40 hostname string
41 requestMethod string
42 requestMethodPassed bool
43 requestPath string
44 requestInputFile string
45 fields []fieldFlag
46 formFields []string
47 requestHeaders []string
48 showResponseHeaders bool
49 paginate bool
50 silent bool
51 outputFormat string
52 placeholderFlags []string
53 placeholders map[string]string
54 placeholderRE *regexp.Regexp
55}
57type fieldFlag struct {
58 spec string
59 raw bool
60}
62// fieldFlagList is the one ordered list --field and --raw-field collect into.
63// pflag keeps a slice per flag, losing the interleave order, which is part of
64// the request: repeated names ending in [] send every value as typed. changed
65// is pflag's reset bit, shared so neither flag discards the other's values.
66type fieldFlagList struct {
67 fields *[]fieldFlag
68 changed bool
69}
71type fieldFlagValue struct {
72 list *fieldFlagList
73 raw bool
74}
76// Type keeps pflag's string-array name, so --help and the docs read as before.
77func (v *fieldFlagValue) Type() string { return "stringArray" }
79func (v *fieldFlagValue) Set(spec string) error {
80 if !v.list.changed {
81 *v.list.fields = nil
82 v.list.changed = true
83 }
84 *v.list.fields = append(*v.list.fields, fieldFlag{spec: spec, raw: v.raw})
85 return nil
86}
88func (v *fieldFlagValue) String() string {
89 var specs []string
90 for _, f := range *v.list.fields {
91 if f.raw == v.raw {
92 specs = append(specs, f.spec)
93 }
94 }
95 if len(specs) == 0 {
96 return ""
97 }
98 return "[" + strings.Join(specs, ",") + "]"
99}
101func NewCmdApi(f cmdutils.Factory, runF func(*options) error) *cobra.Command {
102 opts := options{
103 io: f.IO(),
104 apiClient: f.ApiClient,
105 baseRepo: f.BaseRepo,
106 branch: f.Branch,
107 }
109 cmd := &cobra.Command{
110 Use: "api <endpoint>",
111 Short: "Make an authenticated request to the GitLab API.",
112 Long: heredoc.Docf(`
113 Makes an authenticated HTTP request to the GitLab API, and prints the response.
114 Specify either a path to a GitLab API v4 endpoint, or %[1]sgraphql%[1]s to access the
115 GitLab GraphQL API.
117 For more information, see:
119 - [GitLab REST API documentation](https://docs.gitlab.com/api/)
120 - [GitLab GraphQL documentation](https://docs.gitlab.com/api/graphql/)
122 If the current directory is a Git directory, this command uses the GitLab
123 authenticated host in the current directory. Otherwise, %[1]sgitlab.com%[1]s is used.
124 To override the GitLab hostname, use %[1]s--hostname%[1]s.
126 When used in the endpoint argument, these placeholder values are replaced
127 with values from the repository of the current directory:
129 - %[1]s:branch%[1]s
130 - %[1]s:fullpath%[1]s
131 - %[1]s:group%[1]s
132 - %[1]s:id%[1]s
133 - %[1]s:namespace%[1]s
134 - %[1]s:repo%[1]s
135 - %[1]s:user%[1]s
136 - %[1]s:username%[1]s
138 To define your own placeholder, pass %[1]s--placeholder <name>=<value>%[1]s and use %[1]s:<name>%[1]s in the endpoint or in %[1]s--field%[1]s values. In the endpoint, the value is encoded as a single path segment. In %[1]s--field%[1]s values, it is sent unchanged. To put a value in a query string, pass it as a field instead: %[1]s-X GET -F <key>=:<name>%[1]s. A custom placeholder cannot reuse the name of a built-in placeholder.
140 The default HTTP request method is %[1]sGET%[1]s when no parameters are added,
141 and %[1]sPOST%[1]s otherwise. To override the method, use %[1]s--method%[1]s.
143 Pass one or more %[1]s--raw-field%[1]s values in %[1]skey=value%[1]s format to add
144 JSON-encoded string parameters to the %[1]sPOST%[1]s body.
146 The %[1]s--field%[1]s flag behaves like %[1]s--raw-field%[1]s but converts values
147 based on their format:
149 - Literal values %[1]strue%[1]s, %[1]sfalse%[1]s, %[1]snull%[1]s, and integer numbers are converted to
150 the matching JSON types.
151 - Values starting with %[1]s[%[1]s or %[1]s{%[1]s are parsed as JSON arrays or objects
152 (e.g. %[1]s-F 'topics=["my-topic","GitLab"]'%[1]s). Invalid JSON returns an error.
153 The value must start with the bracket or brace: a leading space, as in
154 %[1]s-F 'topics= ["a"]'%[1]s, is part of the value, so it is sent as a string.
155 - Placeholder values %[1]s:namespace%[1]s, %[1]s:repo%[1]s, and %[1]s:branch%[1]s are populated with values
156 from the repository of the current directory, including inside JSON
157 arrays and objects (e.g. %[1]s-F 'input={"projectPath":":fullpath"}'%[1]s).
158 - If the value starts with %[1]s@%[1]s, the rest of the value is interpreted as a
159 filename to read the value from. Pass %[1]s-%[1]s to read from standard input.
161 %[1]s--raw-field%[1]s does not parse JSON arrays or objects; those values are
162 sent as strings. To pass a JSON body literally, use %[1]s--input%[1]s.
164 A bracketed %[1]s--raw-field%[1]s value such as %[1]s-f 'scopes=[api,read_api]'%[1]s is sent as
165 the literal string %[1]s"[api,read_api]"%[1]s. Earlier versions converted that shape
166 into an array on request bodies, which %[1]s--raw-field%[1]s never documented. Use
167 %[1]s-F 'scopes=["api","read_api"]'%[1]s for an array.
169 Field names are never parsed. A bracketed name is only meaningful where the
170 fields become URL query parameters. That means %[1]sGET%[1]s and %[1]sDELETE%[1]s requests,
171 and any request where %[1]s--input%[1]s supplies the body. There the name is used
172 literally and percent-encoded, so %[1]s-f 'position[base_sha]=abc'%[1]s arrives as
173 the nested parameter it describes.
175 A name ending in %[1]s[]%[1]s collects values instead of holding one, which is how
176 the API reads an array. Repeating the name sends every value, in the order
177 the flags were given: %[1]s-X GET -f 'ids[]=1' -f 'ids[]=2'%[1]s sends both.
178 Because every value is sent, %[1]s--field%[1]s does not override %[1]s--raw-field%[1]s of
179 the same name, as it does for other names.
181 Any other name holds a single value. Among values from the same flag, the
182 last one wins. When both flags name it, the %[1]s--field%[1]s value wins, whichever
183 order the two were given in.
185 The %[1]s-F 'ids=[1,2]'%[1]s spelling emits %[1]sids[]%[1]s as well. Spelling one query
186 parameter both ways is therefore an error. Passing %[1]s-f 'ids[]=1'%[1]s with
187 %[1]s-F 'ids=[2,3]'%[1]s is rejected, because nothing says which order the three
188 values belong in.
190 In a JSON request body a field name containing a bracket is an error. Such
191 a name would be sent as a single literal key, which the API ignores. The
192 request would succeed without doing what the name asked. Pass the value as
193 JSON instead, as in %[1]s-F 'position={"base_sha":"abc"}'%[1]s or %[1]s-F 'ids=[1,2]'%[1]s.
194 Or use %[1]s--input%[1]s.
196 With no %[1]s--method%[1]s, adding any field makes the request a %[1]sPOST%[1]s. Sending
197 bracketed names as query parameters therefore needs an explicit
198 %[1]s--method GET%[1]s. %[1]s--form%[1]s is unaffected: its part names are always literal.
200 For GraphQL requests, all fields other than %[1]squery%[1]s and %[1]soperationName%[1]s are
201 interpreted as GraphQL variables. The bracket rule applies to them
202 unchanged: where the request sends a JSON body, a bracketed variable name
203 is an error.
205 To send data as %[1]smultipart/form-data%[1]s instead of JSON, use %[1]s--form%[1]s. This is
206 required for API endpoints that accept file uploads, such as wiki attachments.
207 Pass one or more %[1]s--form%[1]s values in %[1]skey=value%[1]s format. To upload a file,
208 prefix the value with %[1]s@%[1]s followed by the file path. Pass %[1]s-%[1]s to read from
209 standard input. Do not combine %[1]s--form%[1]s with %[1]s--field%[1]s, %[1]s--raw-field%[1]s, or %[1]s--input%[1]s.
211 To pass a raw request body, use %[1]s--input%[1]s with a file path. Pass %[1]s-%[1]s to
212 read from standard input. In this mode, parameters specified with %[1]s--field%[1]s
213 flags are serialized into URL query parameters.
215 A %[1]s--input%[1]s body is sent as %[1]sapplication/json%[1]s, which is what most GitLab
216 endpoints require to parse it. To send a body of another type, set the
217 header yourself with %[1]s--header 'Content-Type: ...'%[1]s; an explicit header is
218 never overridden.
220 In %[1]s--paginate%[1]s mode, all pages of results are requested sequentially until
221 no more pages of results remain. For GraphQL requests:
223 - The original query must accept an %[1]s$endCursor: String%[1]s variable.
224 - The query must fetch the %[1]spageInfo{ hasNextPage, endCursor }%[1]s set of fields from a collection.
226 %[1]sglab api%[1]s does not retry a failed request. When GitLab answers with HTTP 429, %[1]sglab api%[1]s exits with an error that says how long to wait before you retry, taken from the %[1]sRetry-After%[1]s or %[1]sRateLimit-Reset%[1]s response header.
228 The %[1]s--output%[1]s flag controls the output format:
230 - %[1]sjson%[1]s (default): Pretty-printed JSON. Arrays are output as a single JSON array.
231 - %[1]sndjson%[1]s: Newline-delimited JSON, also known as JSON Lines. Each array element
232 or object is output on a separate line. This format is more memory-efficient for
233 large datasets and works well with tools like %[1]sjq%[1]s.
235 For ndjson format specifications, see the
236 [ndjson spec](https://github.com/ndjson/ndjson-spec) and [JSON Lines](https://jsonlines.org/).
237 `, "`"),
238 Example: heredoc.Doc(`
239 # List releases for the current project, expanding the :fullpath placeholder
240 glab api projects/:fullpath/releases
242 # List issues for a project by URL-encoded path
243 glab api projects/gitlab-com%2Fwww-gitlab-com/issues
245 # Get a branch whose name contains a slash, using a custom placeholder
246 glab api projects/:fullpath/repository/branches/:target --placeholder target=feature/login
248 # Upload a file to a project wiki
249 glab api --method POST projects/:fullpath/wikis/attachments --form "file=@./image.png" --form "branch=main"
251 # Debug the HTTP request and response, including headers and body.
252 # Use --input to send a complete JSON request body from stdin.
253 echo '{"allowed_to_push":[{"user_id":1}]}' | GLAB_DEBUG_HTTP=1 glab api -X PATCH "projects/:fullpath/protected_branches/main" --input -
255 # Fetch all pages of issues
256 glab api issues --paginate
258 # Fetch all pages of issues as newline-delimited JSON
259 glab api issues --paginate --output ndjson
261 # Pipe paginated output to jq to filter open issues
262 glab api issues --paginate --output ndjson | jq 'select(.state == "opened")'
264 # Run a simple GraphQL query
265 glab api graphql -f query="query { currentUser { username } }"
267 # Run a multi-line GraphQL query for project metadata
268 glab api graphql -f query='
269 query {
270 project(fullPath: "gitlab-org/gitlab-docs") {
271 name
272 forksCount
273 statistics {
274 wikiSize
275 }
276 issuesEnabled
277 boards {
278 nodes {
279 id
280 name
281 }
282 }
283 }
284 }
285 '
287 # Run a paginated GraphQL query using an endCursor variable
288 glab api graphql --paginate -f query='
289 query($endCursor: String) {
290 project(fullPath: "gitlab-org/graphql-sandbox") {
291 name
292 issues(first: 2, after: $endCursor) {
293 edges {
294 node {
295 title
296 }
297 }
298 pageInfo {
299 endCursor
300 hasNextPage
301 }
302 }
303 }
304 }'
305 `),
306 Annotations: map[string]string{
307 mcpannotations.Destructive: "true",
308 "help:environment": heredoc.Doc(`
309 GITLAB_TOKEN, OAUTH_TOKEN (in order of precedence): an authentication token for API requests.
310 GITLAB_HOST, GITLAB_URI, GITLAB_URL: specify a GitLab host to make request to.
311 GLAB_DEBUG_HTTP: print the full HTTP request and response, including headers and body, to stderr.
312 `),
313 },
314 Args: cobra.ExactArgs(1),
315 RunE: func(cmd *cobra.Command, args []string) error {
316 opts.complete(cmd, args)
318 if err := opts.validate(cmd); err != nil {
319 return err
320 }
322 if runF != nil {
323 return runF(&opts)
324 }
325 return opts.run(cmd.Context())
326 },
327 }
329 fl := cmd.Flags()
330 fl.StringVar(&opts.hostname, "hostname", "", "The GitLab hostname for the request. Defaults to gitlab.com, or the authenticated host in the current Git directory.")
331 fl.StringVarP(&opts.requestMethod, "method", "X", "GET", "The HTTP method for the request.")
332 fieldList := &fieldFlagList{fields: &opts.fields}
333 fl.VarP(&fieldFlagValue{list: fieldList}, "field", "F", "Add a parameter of inferred type. Using this flag changes the default HTTP method to POST.")
334 fl.VarP(&fieldFlagValue{list: fieldList, raw: true}, "raw-field", "f", "Add a string parameter.")
335 fl.StringArrayVar(&opts.formFields, "form", nil, "Add a multipart form field. To upload a file, prefix the value with @ followed by the file path. To read from standard input, use @- (at most once). Using this flag changes the default HTTP method to POST.")
336 fl.StringArrayVarP(&opts.requestHeaders, "header", "H", nil, "Add an additional HTTP request header.")
337 fl.BoolVarP(&opts.showResponseHeaders, "include", "i", false, "Include HTTP response headers in the output.")
338 fl.BoolVar(&opts.paginate, "paginate", false, "Make additional HTTP requests to fetch all pages of results.")
339 fl.StringVar(&opts.requestInputFile, "input", "", "The file to use as the body for the HTTP request. Sent as 'application/json' unless you set another 'Content-Type' with --header.")
340 fl.BoolVar(&opts.silent, "silent", false, "Do not print the response body.")
341 fl.Var(cmdutils.NewEnumValue([]string{"json", "ndjson"}, "json", &opts.outputFormat), "output", "Format output as: json, ndjson.")
342 fl.StringArrayVar(&opts.placeholderFlags, "placeholder", nil, "Define a custom placeholder in <name>=<value> format, expanded from :<name>. Repeat the flag to define more than one.")
343 cmd.MarkFlagsMutuallyExclusive("paginate", "input")
344 cmd.MarkFlagsMutuallyExclusive("form", "field")
345 cmd.MarkFlagsMutuallyExclusive("form", "raw-field")
346 cmd.MarkFlagsMutuallyExclusive("form", "input")
347 return cmd
348}
350func (o *options) complete(cmd *cobra.Command, args []string) {
351 o.requestPath = args[0]
352 o.requestMethodPassed = cmd.Flags().Changed("method")
353}
355func (o *options) validate(cmd *cobra.Command) error {
356 if cmd.Flags().Changed("hostname") {
357 if err := glinstance.HostnameValidator(o.hostname); err != nil {
358 return &cmdutils.FlagError{Err: fmt.Errorf("error parsing --hostname: %w", err)}
359 }
360 }
362 if o.paginate && !strings.EqualFold(o.requestMethod, http.MethodGet) && o.requestPath != "graphql" {
363 return &cmdutils.FlagError{Err: errors.New("the '--paginate' option is not supported for non-GET requests")}
364 }
366 if o.outputFormat != "json" && o.outputFormat != "ndjson" {
367 return &cmdutils.FlagError{Err: fmt.Errorf("invalid output format %q: must be 'json' or 'ndjson'", o.outputFormat)}
368 }
370 stdinCount := 0
371 for _, f := range o.formFields {
372 if strings.HasSuffix(f, "=@-") {
373 stdinCount++
374 }
375 }
376 if stdinCount > 1 {
377 return &cmdutils.FlagError{Err: errors.New("'@-' (stdin) can only be used once across all --form fields")}
378 }
380 return o.parsePlaceholders()
381}
383func (o *options) parsePlaceholders() error {
384 if len(o.placeholderFlags) == 0 {
385 return nil
386 }
388 o.placeholders = make(map[string]string, len(o.placeholderFlags))
389 for _, spec := range o.placeholderFlags {
390 name, value, ok := strings.Cut(spec, "=")
391 switch {
392 case !ok:
393 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --placeholder %q: expected <name>=<value>", spec)}
394 case !placeholderNameRE.MatchString(name):
395 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --placeholder name %q: must start with a letter, contain only letters, digits, '_', or '-', and not end with '-'", name)}
396 case slices.Contains(Placeholders, name):
397 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --placeholder name %q: conflicts with a built-in placeholder", name)}
398 }
399 if _, dup := o.placeholders[name]; dup {
400 return &cmdutils.FlagError{Err: fmt.Errorf("invalid --placeholder name %q: defined more than once", name)}
401 }
402 o.placeholders[name] = value
403 }
405 names := slices.Concat(Placeholders, slices.Collect(maps.Keys(o.placeholders)))
406 slices.SortStableFunc(names, func(a, b string) int { return len(b) - len(a) })
407 o.placeholderRE = regexp.MustCompile(`:(` + strings.Join(names, "|") + `)\b`)
408 return nil
409}
411// EffectiveMethod reports the HTTP method an invocation of this command uses.
412func EffectiveMethod(cmd *cobra.Command) string {
413 fl := cmd.Flags()
415 bodyFlags := []string{"field", "raw-field", "form", "input"}
416 method := resolveMethod(
417 fl.Lookup("method").Value.String(),
418 fl.Changed("method"),
419 slices.ContainsFunc(bodyFlags, fl.Changed),
420 )
422 if method == "" {
423 return http.MethodGet
424 }
425 return strings.ToUpper(method)
426}
428// resolveMethod applies the documented default: the request is a GET unless
429// parameters, a form, or an input file are supplied, and an explicit --method
430// always wins. Shared with the telemetry hook so the two cannot drift.
431func resolveMethod(method string, methodPassed, hasBody bool) string {
432 if !methodPassed && hasBody {
433 return http.MethodPost
434 }
435 return method
436}
438func (o *options) run(ctx context.Context) error {
439 // Parsing needs the method: it decides whether a bracketed name is an error.
440 method := o.methodForRequest()
442 params, rawKeys, err := parseFields(o, o.fieldsBecomeJSONBody(method))
443 if err != nil {
444 return err
445 }
446 isGraphQL := o.requestPath == "graphql"
447 requestPath, err := fillPlaceholders(o.requestPath, o, true)
448 if err != nil {
449 return fmt.Errorf("unable to expand placeholder in path: %w", err)
450 }
451 requestHeaders := o.requestHeaders
452 var requestBody any = params
453 var bodyIsJSON bool
455 o.warnOnLegacyRawArrays(method, params, rawKeys)
457 if o.paginate && !isGraphQL {
458 requestPath = addPerPage(requestPath, 100, params)
459 }
461 if o.requestInputFile != "" {
462 file, size, err := openUserFile(o.requestInputFile, o.io.In)
463 if err != nil {
464 return err
465 }
466 defer file.Close()
467 requestPath, err = parseQuery(requestPath, params)
468 if err != nil {
469 return err
470 }
471 requestBody = file
472 // GitLab rejects a body with no Content-Type with HTTP 415.
473 bodyIsJSON = true
474 if size >= 0 {
475 requestHeaders = append([]string{fmt.Sprintf("Content-Length: %d", size)}, requestHeaders...)
476 }
477 } else if len(o.formFields) > 0 {
478 body, contentType := buildMultipartBody(o.formFields, o.io.In)
479 requestBody = body
480 requestHeaders = append([]string{fmt.Sprintf("Content-Type: %s", contentType)}, requestHeaders...)
481 }
483 headersOutputStream := o.io.StdOut
484 if o.silent {
485 o.io.StdOut = io.Discard
486 } else {
487 err := o.io.StartPager()
488 if err != nil {
489 return err
490 }
491 defer o.io.StopPager()
492 }
494 var repoHost string
495 if o.hostname != "" {
496 repoHost = o.hostname
497 } else {
498 // NOTE: check if repository is available
499 br, err := o.baseRepo()
500 if err == nil {
501 repoHost = br.RepoHost()
502 }
503 }
504 client, err := o.apiClient(repoHost)
505 if err != nil {
506 return err
507 }
509 hasNextPage := true
510 for hasNextPage {
511 resp, err := httpRequest(ctx, client, method, requestPath, requestBody, requestHeaders, bodyIsJSON)
512 if err != nil {
513 return err
514 }
516 endCursor, err := processResponse(resp, o, headersOutputStream)
517 _ = resp.Body.Close()
518 if err != nil {
519 return err
520 }
522 if !o.paginate {
523 break
524 }
526 if isGraphQL {
527 hasNextPage = endCursor != ""
528 if hasNextPage {
529 params["endCursor"] = endCursor
530 }
531 } else {
532 requestPath, hasNextPage = findNextPage(resp)
533 // The Link URL already carries the previous request's parameters, so
534 // rebuilding the query duplicates them and can override page. Only a
535 // query method puts fields in the query; any other method carries
536 // them in the body and has to keep sending it.
537 if isQueryMethod(method) {
538 requestBody = nil
539 }
540 }
542 if hasNextPage && o.showResponseHeaders {
543 o.io.LogInfo()
544 }
545 }
547 return nil
548}
550func processResponse(resp *http.Response, opts *options, headersOutputStream io.Writer) (string, error) {
551 if opts.showResponseHeaders {
552 fmt.Fprintln(headersOutputStream, resp.Proto, resp.Status) //nolint:forbidigo // headersOutputStream is a generic io.Writer, passed io.Discard in tests
553 printHeaders(headersOutputStream, resp.Header, opts.io.ColorEnabled())
554 fmt.Fprint(headersOutputStream, "\r\n") //nolint:forbidigo // headersOutputStream is a generic io.Writer, passed io.Discard in tests
555 }
557 if resp.StatusCode == http.StatusNoContent {
558 return "", nil
559 }
560 var responseBody io.Reader = resp.Body
562 isJSON, _ := regexp.MatchString(`[/+]json(;|$)`, resp.Header.Get("Content-Type"))
564 var serverError string
565 if isJSON && (opts.requestPath == "graphql" || resp.StatusCode >= http.StatusBadRequest) {
566 var err error
567 responseBody, serverError, err = parseErrorResponse(responseBody, resp.StatusCode)
568 if err != nil {
569 return "", err
570 }
571 }
573 var bodyCopy *bytes.Buffer
574 isGraphQLPaginate := isJSON && resp.StatusCode == http.StatusOK && opts.paginate && opts.requestPath == "graphql"
575 if isGraphQLPaginate {
576 bodyCopy = &bytes.Buffer{}
577 responseBody = io.TeeReader(responseBody, bodyCopy)
578 }
580 var err error
581 switch {
582 case opts.outputFormat == "ndjson" && isJSON && resp.StatusCode == http.StatusOK:
583 err = streamNDJSON(responseBody, opts.io.StdOut)
584 case isJSON && opts.io.ColorEnabled():
585 out := &bytes.Buffer{}
586 _, err = io.Copy(out, responseBody)
587 if err == nil {
588 result := jsonPretty.Color(jsonPretty.Pretty(out.Bytes()), nil)
589 _, err = fmt.Fprintln(opts.io.StdOut, string(result)) //nolint:forbidigo // write error must propagate to the caller
590 }
591 default:
592 _, err = io.Copy(opts.io.StdOut, responseBody)
593 }
594 if err != nil {
595 return "", err
596 }
598 if serverError != "" || resp.StatusCode > 299 {
599 if serverError != "" {
600 opts.io.LogErrorf("glab: %s\n", serverError)
601 } else {
602 opts.io.LogErrorf("glab: HTTP %d\n", resp.StatusCode)
603 }
604 if hint := api.RateLimitHint(resp, time.Now()); hint != "" {
605 opts.io.LogErrorf("glab: %s\n", hint)
606 }
607 return "", cmdutils.SilentError
608 }
610 if isGraphQLPaginate {
611 return findEndCursor(bodyCopy), nil
612 }
614 return "", nil
615}
617// streamNDJSON streams JSON response as newline-delimited JSON.
618// If the response is a JSON array, each element is written as a separate line.
619// If the response is a single JSON object, it's written as-is with a newline.
620func streamNDJSON(body io.Reader, out io.Writer) error {
621 dec := json.NewDecoder(body)
622 dec.UseNumber()
624 // Peek at the first token to determine if it's an array or object
625 token, err := dec.Token()
626 if err != nil {
627 if errors.Is(err, io.EOF) {
628 return nil
629 }
630 return err
631 }
633 // Check if it's an array
634 if delim, ok := token.(json.Delim); ok && delim == '[' {
635 // Stream each array element as a separate line
636 for dec.More() {
637 var element json.RawMessage
638 if err := dec.Decode(&element); err != nil {
639 return err
640 }
641 if _, err := fmt.Fprintln(out, string(element)); err != nil { //nolint:forbidigo // out is a generic io.Writer parameter for streaming, not IOStreams directly
642 return err
643 }
644 }
645 // Consume the closing bracket
646 if _, err := dec.Token(); err != nil {
647 return err
648 }
649 return nil
650 }
652 // For non-array JSON, simply copy the entire body and add newline
653 // Reset the body reader since we consumed the first token
654 var tokenStr string
655 switch v := token.(type) {
656 case json.Delim:
657 tokenStr = string(rune(v))
658 default:
659 // For primitive values (string, number, bool, null), marshal back to JSON
660 b, _ := json.Marshal(v) //nolint:forbidigo // re-encoding a parsed JSON token value into a string, not writing to stdout
661 tokenStr = string(b)
662 }
664 fullBody := io.MultiReader(strings.NewReader(tokenStr), dec.Buffered(), body)
666 // Copy directly to output with newline
667 if _, err := io.Copy(out, fullBody); err != nil {
668 return err
669 }
670 _, err = out.Write([]byte("\n"))
671 return err
672}
674// Placeholders are the tokens `glab api` expands in a request path or field
675// value, without their leading colon. Exported so documentation and the bundled
676// skills can be checked against the real set rather than a copy of it: a token
677// that is neither here nor defined with --placeholder is sent to the API verbatim.
678//
679// Order matters. The regexp alternation below tries these in sequence, so a
680// longer token must precede any token that prefixes it.
681var Placeholders = []string{
682 "group/:namespace/:repo",
683 "namespace/:repo",
684 "fullpath",
685 "id",
686 "user",
687 "username",
688 "group",
689 "namespace",
690 "repo",
691 "branch",
692}
694var placeholderRE = regexp.MustCompile(`:(` + strings.Join(Placeholders, "|") + `)\b`)
696var placeholderNameRE = regexp.MustCompile(`^[A-Za-z](?:[A-Za-z0-9_-]*[A-Za-z0-9_])?$`)
698// jsonFieldHint is shared by both --field JSON failures so the guidance cannot
699// drift between them.
700const jsonFieldHint = `Use proper JSON syntax (e.g. -F 'key=["value1","value2"]') or -f to pass a literal string.`
702// legacyRawArrayRE matches the bracketed shorthand that --raw-field values were
703// once converted into arrays by, before array handling moved to --field only.
704// It exists to warn, not to parse: the value itself is sent literally.
705var legacyRawArrayRE = regexp.MustCompile(`^\[\s*([[:lower:]_]+(\s*,\s*[[:lower:]_]+)*)?\s*\]$`)
707// fillPlaceholders populates `:namespace` and `:repo` placeholders with values from the current repository.
708// When escapePath is true, substituted values are URL-encoded so they're safe as a single path segment;
709// callers expanding placeholders into request bodies or query values should pass false to preserve raw values.
710func fillPlaceholders(value string, opts *options, escapePath bool) (string, error) {
711 re := placeholderRE
712 if opts.placeholderRE != nil {
713 re = opts.placeholderRE
714 }
715 if !re.MatchString(value) {
716 return value, nil
717 }
719 maybeEscape := func(s string) string {
720 if escapePath {
721 return url.PathEscape(s)
722 }
723 return s
724 }
726 var err error
727 filled := re.ReplaceAllStringFunc(value, func(m string) string {
728 if custom, ok := opts.placeholders[m[1:]]; ok {
729 return maybeEscape(custom)
730 }
731 switch m {
732 case ":id":
733 baseRepo, baseRepoErr := opts.baseRepo()
734 if baseRepoErr != nil {
735 err = baseRepoErr
736 return ""
737 }
739 h, apiClientErr := opts.apiClient(baseRepo.RepoHost())
740 if apiClientErr != nil {
741 err = apiClientErr
742 return ""
743 }
744 project, e := baseRepo.Project(h.Lab())
745 if e == nil && project != nil {
746 return strconv.FormatInt(project.ID, 10)
747 }
748 err = e
749 return ""
750 case ":group/:namespace/:repo", ":fullpath":
751 baseRepo, baseRepoErr := opts.baseRepo()
752 if baseRepoErr != nil {
753 err = baseRepoErr
754 return ""
755 }
756 return maybeEscape(baseRepo.FullName())
757 case ":namespace/:repo":
758 baseRepo, baseRepoErr := opts.baseRepo()
759 if baseRepoErr != nil {
760 err = baseRepoErr
761 return ""
762 }
764 return maybeEscape(baseRepo.RepoNamespace() + "/" + baseRepo.RepoName())
765 case ":group":
766 baseRepo, baseRepoErr := opts.baseRepo()
767 if baseRepoErr != nil {
768 err = baseRepoErr
769 return ""
770 }
772 return maybeEscape(baseRepo.RepoGroup())
773 case ":user", ":username":
774 h, apiClientErr := opts.apiClient("")
775 if apiClientErr != nil {
776 err = apiClientErr
777 return m
778 }
779 u, _, e := h.Lab().Users.CurrentUser()
780 if e == nil && u != nil {
781 return maybeEscape(u.Username)
782 }
783 err = e
784 return m
785 case ":namespace":
786 baseRepo, baseRepoErr := opts.baseRepo()
787 if baseRepoErr != nil {
788 err = baseRepoErr
789 return ""
790 }
792 return maybeEscape(baseRepo.RepoNamespace())
793 case ":repo":
794 baseRepo, baseRepoErr := opts.baseRepo()
795 if baseRepoErr != nil {
796 err = baseRepoErr
797 return ""
798 }
800 return maybeEscape(baseRepo.RepoName())
801 case ":branch":
802 branch, e := opts.branch()
803 if e != nil {
804 err = e
805 }
806 return maybeEscape(branch)
807 default:
808 err = fmt.Errorf("invalid placeholder: %q", m)
809 return ""
810 }
811 })
813 if err != nil {
814 return value, err
815 }
817 return filled, nil
818}
820func printHeaders(w io.Writer, headers http.Header, colorize bool) {
821 var names []string
822 for name := range headers {
823 if name == "Status" {
824 continue
825 }
826 names = append(names, name)
827 }
828 sort.Strings(names)
830 var headerColor, headerColorReset string
831 if colorize {
832 headerColor = "\x1b[1;34m" // bright blue
833 headerColorReset = "\x1b[m"
834 }
835 for _, name := range names {
836 fmt.Fprintf(w, "%s%s%s: %s\r\n", headerColor, name, headerColorReset, strings.Join(headers[name], ", ")) //nolint:forbidigo // w is a generic io.Writer, passed io.Discard in tests
837 }
838}
840// methodForRequest is the method the request is sent with: absent --method, a
841// field, a form field, or --input makes it a POST rather than the flag's GET
842// default. resolveMethod is shared with the telemetry hook, so the two cannot
843// disagree about the rule; each site computes hasBody for itself.
844func (o *options) methodForRequest() string {
845 return resolveMethod(o.requestMethod, o.requestMethodPassed,
846 len(o.fields) > 0 || o.requestInputFile != "" || len(o.formFields) > 0)
847}
849// fieldsBecomeJSONBody reports whether the fields become a body, not a query.
850func (o *options) fieldsBecomeJSONBody(method string) bool {
851 if o.requestInputFile != "" {
852 // --input supplies the body, so the fields are query parameters.
853 return false
854 }
855 return !isQueryMethod(method)
856}
858// parseFields returns the request parameters, plus the keys that came from
859// --raw-field in the order they were given. The caller needs that provenance to
860// warn about legacy bracketed values without parsing the flags a second time,
861// and a map alone cannot supply it: --field overwrites a --raw-field of the same
862// name, and map iteration has no order. With jsonBody, a bracketed name errors.
863func parseFields(opts *options, jsonBody bool) (map[string]any, []string, error) {
864 params := make(map[string]any)
865 rawKeys := make([]string, 0, len(opts.fields))
866 // A --raw-field never overrides a --field; the old two-pass read implied that.
867 magicOwned := make(map[string]struct{}, len(opts.fields))
868 for _, f := range opts.fields {
869 key, strValue, err := parseField(f.spec)
870 if err != nil {
871 return params, rawKeys, err
872 }
873 if jsonBody && strings.ContainsAny(key, "[]") {
874 return params, rawKeys, bracketedFieldNameError(key)
875 }
876 value := any(strValue)
877 if !f.raw {
878 if value, err = magicFieldValue(strValue, opts); err != nil {
879 return params, rawKeys, fmt.Errorf("error parsing %q value: %w", key, err)
880 }
881 }
882 // A name ending in "[]" collects rather than holds one value, so there is
883 // no override to apply: every value is sent.
884 accumulates := strings.HasSuffix(key, "[]")
885 if f.raw {
886 rawKeys = append(rawKeys, key)
887 if _, owned := magicOwned[key]; owned {
888 continue
889 }
890 } else if !accumulates {
891 magicOwned[key] = struct{}{}
892 }
893 addFieldParam(params, key, value)
894 }
895 if !jsonBody {
896 if err := checkQueryKeyCollision(params); err != nil {
897 return params, rawKeys, err
898 }
899 }
900 return params, rawKeys, nil
901}
903// bracketedNameRE splits a name into its root and its bracketed segments. Root
904// and segments are both bracket-free, so a name the bracket syntax cannot
905// describe, such as "a[b", "a]" or "a[b]c", does not match. The guard in
906// parseFields is wider than this: it rejects any name holding a bracket at all.
907var bracketedNameRE = regexp.MustCompile(`^([^\[\]]+)((?:\[[^\[\]]*\])+)$`)
909// bracketedNameProblem is the clause every such error shares, whatever advice
910// follows it. Tests derive their expectations from it rather than respelling it.
911const bracketedNameProblem = "a field name containing a bracket is not supported in a JSON request body; pass the value as JSON"
913// bracketedFieldNameError reports a name a JSON body cannot carry. Where the
914// name has the shape its brackets describe, the advice is built from the user's
915// own segments, so it spells the request they were asking for rather than an
916// example they have to translate. A name that has no such shape gets the forms
917// that work and no invented key.
918func bracketedFieldNameError(key string) error {
919 m := bracketedNameRE.FindStringSubmatch(key)
920 if m == nil {
921 return fmt.Errorf("field name %q: %s with -F, or use --input", key, bracketedNameProblem)
922 }
923 segments := strings.Split(strings.TrimSuffix(strings.TrimPrefix(m[2], "["), "]"), "][")
924 return fmt.Errorf("field name %q: %s, for example -F '%s=%s', or use --input", key, bracketedNameProblem, m[1], jsonShapeOf(segments))
925}
927// jsonShapeOf renders the value a name's bracketed segments describe, outermost
928// first: an empty segment is an array, a named one an object key. The innermost
929// value is a placeholder, since the name says nothing about the value's type.
930func jsonShapeOf(segments []string) string {
931 if len(segments) == 0 {
932 return `"..."`
933 }
934 head, rest := segments[0], segments[1:]
935 if head == "" {
936 if len(rest) == 0 {
937 // An array of unknown element type, so no element is invented either.
938 return "[...]"
939 }
940 return "[" + jsonShapeOf(rest) + "]"
941 }
942 // strconv.Quote, not the bare name: a segment may hold a quote of its own.
943 return "{" + strconv.Quote(head) + ":" + jsonShapeOf(rest) + "}"
944}
946// addFieldParam stores one field's value. A name ending in "[]" accumulates in
947// flag order; any other, position[base_sha] included, stays last-wins.
948func addFieldParam(params map[string]any, key string, value any) {
949 existing, seen := params[key]
950 if !seen || !strings.HasSuffix(key, "[]") {
951 params[key] = value
952 return
953 }
954 if list, isList := existing.(queryList); isList {
955 params[key] = append(list, value)
956 return
957 }
958 params[key] = queryList{existing, value}
959}
961// queryWireKey is the query parameter a name addresses: a JSON array emits key[]=,
962// except where the name already carries those brackets, as parseQuery also reads
963// it. Computing "ids[][]" here would hide the clash between -F 'ids[]=[1,2]' and
964// -F 'ids=[3]', which both address ids[].
965func queryWireKey(name string, value any) string {
966 if _, isArray := value.([]any); isArray && !strings.HasSuffix(name, "[]") {
967 return name + "[]"
968 }
969 return name
970}
972// checkQueryKeyCollision rejects two field names that emit one query parameter,
973// as -f 'ids[]=1' -F 'ids=[2,3]' does: map order would shuffle their values.
974func checkQueryKeyCollision(params map[string]any) error {
975 owner := make(map[string]string, len(params))
976 for name, value := range params {
977 wire := queryWireKey(name, value)
978 prior, clash := owner[wire]
979 if !clash {
980 owner[wire] = name
981 continue
982 }
983 // Order the two names so the message does not depend on map order.
984 first, second := prior, name
985 if second < first {
986 first, second = second, first
987 }
988 return fmt.Errorf("field names %q and %q both address query parameter %q; spell the array one way, or use --input", first, second, wire)
989 }
990 return nil
991}
993// warnOnLegacyRawArrays prints a one-time hint per matching field when a
994// --raw-field value has the shape that used to be converted into a JSON array
995// on request bodies. The value is sent literally now, which the API usually
996// rejects outright, but an endpoint that accepts either a string or an array
997// would accept it silently as a single element. The hint makes that
998// discoverable. It goes to stderr, so scripted stdout consumers are unaffected.
999//
1000// It reads the values parseFields already produced, walking rawKeys so the
1001// warnings come out in flag order. Reading the parsed value is what makes this
1002// honest: when a --field of the same name overrides a --raw-field, the literal
1003// string is not what gets sent, so there is nothing to warn about.
1004func (o *options) warnOnLegacyRawArrays(method string, params map[string]any, rawKeys []string) {
1005 if isQueryMethod(method) {
1006 // Query parameters were never array-converted, so nothing changed here.
1007 return
1008 }
1009 warned := make(map[string]bool, len(rawKeys))
1010 for _, key := range rawKeys {
1011 if warned[key] {
1012 continue
1013 }
1014 value, isString := params[key].(string)
1015 if !isString || !legacyRawArrayRE.MatchString(value) {
1016 continue
1017 }
1018 warned[key] = true
1019 o.io.LogErrorf(
1020 "Warning: --raw-field %q is sent as the literal string %s. Use -F (--field) with JSON for an array, e.g. -F '%s=[\"value1\",\"value2\"]'.\n",
1021 key, value, key,
1022 )
1023 }
1024}
1026func parseField(f string) (string, string, error) {
1027 idx := strings.IndexRune(f, '=')
1028 if idx == -1 {
1029 return f, "", fmt.Errorf("field %q requires a value separated by an '=' sign", f)
1030 }
1031 return f[0:idx], f[idx+1:], nil
1032}
1034func magicFieldValue(v string, opts *options) (any, error) {
1035 if strings.HasPrefix(v, "@") {
1036 return readUserFile(v[1:], opts.io.In)
1037 }
1039 if n, err := strconv.Atoi(v); err == nil {
1040 return n, nil
1041 }
1043 if strings.HasPrefix(v, "[") || strings.HasPrefix(v, "{") {
1044 // Decode with UseNumber so large integers keep full precision rather
1045 // than degrading through float64.
1046 dec := json.NewDecoder(strings.NewReader(v))
1047 dec.UseNumber()
1048 var parsed any
1049 if err := dec.Decode(&parsed); err != nil {
1050 // The decoder's own message names the offending character, and the
1051 // caller already prefixes the field name, so an "invalid JSON" of
1052 // our own would be the third restatement of the same fact.
1053 return nil, fmt.Errorf("%w. %s", err, jsonFieldHint)
1054 }
1055 // Reject trailing data so a value like `[1,2]oops` still errors rather
1056 // than silently parsing only the leading JSON value. The decoder error
1057 // locates the offending character, so keep it rather than flattening
1058 // this to a bare "trailing data".
1059 if _, err := dec.Token(); !errors.Is(err, io.EOF) {
1060 if err == nil {
1061 err = errors.New("more than one JSON value")
1062 }
1063 return nil, fmt.Errorf("unexpected trailing data: %w. %s", err, jsonFieldHint)
1064 }
1065 return expandPlaceholdersIn(parsed, opts)
1066 }
1068 switch v {
1069 case "true":
1070 return true, nil
1071 case "false":
1072 return false, nil
1073 case "null":
1074 return nil, nil
1075 default:
1076 return fillPlaceholders(v, opts, false)
1077 }
1078}
1080// expandPlaceholdersIn expands placeholders in every string leaf and object key
1081// of a JSON-decoded value, so `-F 'input={"projectPath":":fullpath"}'` behaves
1082// the way the flag's documentation promises.
1083//
1084// Expansion runs after decoding, never before. Splicing an expanded value into
1085// the raw JSON text would let a branch name containing a double quote, which
1086// git accepts as a legal refname, inject JSON structure into an authenticated
1087// request. Decoding first means the expanded text is an ordinary Go string that
1088// json.Marshal re-escapes on the way out, and url.Values.Encode percent-encodes
1089// on the query path.
1090func expandPlaceholdersIn(v any, opts *options) (any, error) {
1091 switch t := v.(type) {
1092 case string:
1093 return fillPlaceholders(t, opts, false)
1094 case []any:
1095 for i, item := range t {
1096 expanded, err := expandPlaceholdersIn(item, opts)
1097 if err != nil {
1098 return nil, err
1099 }
1100 t[i] = expanded
1101 }
1102 return t, nil
1103 case map[string]any:
1104 // Build a new map rather than mutating during iteration: an expanded key
1105 // may collide with or replace an existing one. Such a collision is
1106 // rejected rather than resolved, because Go randomizes map iteration
1107 // order, so silently keeping one of the two would drop a field from the
1108 // request body non-deterministically between runs of the same command.
1109 out := make(map[string]any, len(t))
1110 // Records which source key produced each expanded key, so the error can
1111 // name both culprits. Reporting only the key we happened to reach second
1112 // would make the message itself depend on iteration order, and for a
1113 // literal key colliding with a placeholder it would read "test expands to
1114 // test" whenever the literal came second.
1115 source := make(map[string]string, len(t))
1116 for key, item := range t {
1117 expandedKey, err := fillPlaceholders(key, opts, false)
1118 if err != nil {
1119 return nil, err
1120 }
1121 if prior, taken := source[expandedKey]; taken {
1122 first, second := prior, key
1123 if first > second {
1124 first, second = second, first
1125 }
1126 return nil, fmt.Errorf(
1127 "keys %q and %q both expand to %q. Rename one of them so the request body is unambiguous",
1128 first, second, expandedKey,
1129 )
1130 }
1131 source[expandedKey] = key
1132 expanded, err := expandPlaceholdersIn(item, opts)
1133 if err != nil {
1134 return nil, err
1135 }
1136 out[expandedKey] = expanded
1137 }
1138 return out, nil
1139 default:
1140 // Numbers, booleans and null carry no placeholders.
1141 return v, nil
1142 }
1143}
1145func readUserFile(fn string, stdin io.ReadCloser) ([]byte, error) {
1146 var r io.ReadCloser
1147 if fn == "-" {
1148 r = stdin
1149 } else {
1150 var err error
1151 r, err = os.Open(fn)
1152 if err != nil {
1153 return nil, err
1154 }
1155 }
1156 defer r.Close()
1157 return io.ReadAll(r)
1158}
1160func openUserFile(fn string, stdin io.ReadCloser) (io.ReadCloser, int64, error) {
1161 if fn == "-" {
1162 return stdin, -1, nil
1163 }
1165 r, err := os.Open(fn)
1166 if err != nil {
1167 return r, -1, err
1168 }
1170 s, err := os.Stat(fn)
1171 if err != nil {
1172 r.Close()
1173 return r, -1, err
1174 }
1176 return r, s.Size(), nil
1177}
1179func parseErrorResponse(r io.Reader, statusCode int) (io.Reader, string, error) {
1180 bodyCopy := &bytes.Buffer{}
1181 b, err := io.ReadAll(io.TeeReader(r, bodyCopy))
1182 if err != nil {
1183 return r, "", err
1184 }
1186 var parsedBody struct {
1187 Message string
1188 Errors []json.RawMessage
1189 }
1190 err = json.Unmarshal(b, &parsedBody)
1191 if err != nil {
1192 // in cases where it's an object within an object we can try to parse it as is
1193 var t any
1194 err = json.Unmarshal(b, &t)
1195 if err != nil {
1196 return r, "", err
1197 }
1198 return bodyCopy, fmt.Sprintf("%+v", t), nil
1199 }
1200 if parsedBody.Message != "" {
1201 return bodyCopy, fmt.Sprintf("%s (HTTP %d)", parsedBody.Message, statusCode), nil
1202 }
1204 type errorMessage struct {
1205 Message string
1206 }
1207 var respErrors []string
1208 for _, rawErr := range parsedBody.Errors {
1209 if len(rawErr) == 0 {
1210 continue
1211 }
1212 if rawErr[0] == '{' {
1213 var objectError errorMessage
1214 err := json.Unmarshal(rawErr, &objectError)
1215 if err != nil {
1216 return r, "", err
1217 }
1218 respErrors = append(respErrors, objectError.Message)
1219 } else if rawErr[0] == '"' {
1220 var stringError string
1221 err := json.Unmarshal(rawErr, &stringError)
1222 if err != nil {
1223 return r, "", err
1224 }
1225 respErrors = append(respErrors, stringError)
1226 }
1227 }
1229 if len(respErrors) > 0 {
1230 return bodyCopy, strings.Join(respErrors, "\n"), nil
1231 }
1233 return bodyCopy, "", nil
1234}
Diagnostics7 git calls · 279 ms
CallStatusSizeTime0279 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=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 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=1 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 · 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=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 · hit4 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=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 · 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:0200285 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=267 git.response.bytes=285 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=48bbcb7832066dead74ecdecb6257183f3d03bf0 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=285 git.pkt.payload.max=258 git.sideband.band1.bytes=258 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=258 git.pack.trailer=2570819fa1caef7b0fd3f7ba2d1b1a658b78702eOpen pack map
fetch20014 KiB267 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=14232 git.response.cache=MISS git.response.duration_ms=267 git.fetch.wants=5b5da0d6d158fe262cfd2a7494968ff9839f1482 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=14232 git.pkt.payload.max=14205 git.sideband.band1.bytes=14205 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
- a5e1b2b20f8df54b
- Request
- 0611f1a5…
- 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