GitLabgitlab-org
cli
main
1package help
3import (
4 "bytes"
5 "fmt"
6 "io"
7 "os"
8 "strings"
10 "charm.land/glamour/v2"
11 "charm.land/glamour/v2/styles"
12 "github.com/muesli/termenv"
13 "github.com/spf13/cobra"
14 "golang.org/x/term"
16 "gitlab.com/gitlab-org/cli/internal/iostreams"
17 "gitlab.com/gitlab-org/cli/internal/utils"
18)
20// getGlamourStyle returns the glamour style to use, replicating glamour v1's
21// auto-detection logic that was removed in v2. It checks the GLAMOUR_STYLE
22// environment variable first, then falls back to notty for non-TTY output
23// or dark/light based on terminal background color.
24func getGlamourStyle() string {
25 if s := os.Getenv("GLAMOUR_STYLE"); s != "" {
26 return s
27 }
28 if !term.IsTerminal(int(os.Stdout.Fd())) {
29 return styles.NoTTYStyle
30 }
31 if termenv.HasDarkBackground() {
32 return styles.DarkStyle
33 }
34 return styles.LightStyle
35}
37// renderWithGlamour renders markdown text using Glamour
38func renderWithGlamour(text string) string {
39 if text == "" {
40 return ""
41 }
43 renderer, err := glamour.NewTermRenderer(
44 glamour.WithStandardStyle(getGlamourStyle()),
45 glamour.WithWordWrap(120),
46 glamour.WithPreservedNewLines(),
47 )
48 if err != nil {
49 return text
50 }
52 renderedText, err := renderer.Render(text)
53 if err != nil {
54 return text
55 }
57 return strings.TrimSpace(renderedText)
58}
60// This code forked from the GitHub CLI at http://github.com/cli - cli/internal/text/indent.go
61// https://github.com/cli/cli/blob/929e082c13909044e2585af292ae952c9ca6f25c/pkg/text/indent.go
63// MIT License
64//
65// Copyright (c) 2019 GitHub Inc.
66//
67// Permission is hereby granted, free of charge, to any person obtaining a copy
68// of this software and associated documentation files (the "Software"), to deal
69// in the Software without restriction, including without limitation the rights
70// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
71// copies of the Software, and to permit persons to whom the Software is
72// furnished to do so, subject to the following conditions:
73//
74// The above copyright notice and this permission notice shall be included in all
75// copies or substantial portions of the Software.
76//
77// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
78// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
79// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
80// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
81// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
82// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
83// SOFTWARE.
85// RootUsageFunc renders a command's usage to out. Callers route diagnostic
86// usage messages to stderr; see NewCmdRoot for the wiring and
87// gitlab-org/cli#8371 for why we no longer rely on cobra's c.Print/SetOut.
88func RootUsageFunc(out io.Writer, command *cobra.Command) error {
89 fmt.Fprintf(out, "Usage: %s", command.UseLine()) //nolint:forbidigo // out is a generic io.Writer shared with test buffers
91 subcommands := command.Commands()
92 if len(subcommands) > 0 {
93 fmt.Fprint(out, "\n\nAvailable commands:\n") //nolint:forbidigo // out is a generic io.Writer shared with test buffers
94 for _, c := range subcommands {
95 if !c.IsAvailableCommand() {
96 continue
97 }
98 fmt.Fprintf(out, " %s\n", c.Name()) //nolint:forbidigo // out is a generic io.Writer shared with test buffers
99 }
100 return nil
101 }
103 flagUsages := command.LocalFlags().FlagUsages()
104 if flagUsages != "" {
105 fmt.Fprintln(out, "\n\nFlags:") //nolint:forbidigo // out is a generic io.Writer shared with test buffers
106 fmt.Fprint(out, utils.Indent(dedent(flagUsages), " ")) //nolint:forbidigo // out is a generic io.Writer shared with test buffers
107 }
108 return nil
109}
111var hasFailed bool
113// HasFailed signals that the main process should exit with non-zero status
114func HasFailed() bool {
115 return hasFailed
116}
118// Display helpful error message in case subcommand name was mistyped.
119// This matches Cobra's behavior for root command, which Cobra
120// confusingly doesn't apply to nested commands.
121func nestedSuggestFunc(out io.Writer, command *cobra.Command, arg string) {
122 fmt.Fprintf(out, "unknown command %q for %q\n", arg, command.CommandPath()) //nolint:forbidigo // out is a generic io.Writer shared with test buffers
124 var candidates []string
125 if arg == "help" {
126 candidates = []string{"--help"}
127 } else {
128 if command.SuggestionsMinimumDistance <= 0 {
129 command.SuggestionsMinimumDistance = 2
130 }
131 candidates = command.SuggestionsFor(arg)
132 }
134 if len(candidates) > 0 {
135 fmt.Fprint(out, "\nDid you mean this?\n") //nolint:forbidigo // out is a generic io.Writer shared with test buffers
136 for _, c := range candidates {
137 fmt.Fprintf(out, "\t%s\n", c) //nolint:forbidigo // out is a generic io.Writer shared with test buffers
138 }
139 }
141 fmt.Fprint(out, "\n") //nolint:forbidigo // out is a generic io.Writer shared with test buffers
142 _ = RootUsageFunc(out, command)
143}
145func isRootCmd(command *cobra.Command) bool {
146 return command != nil && !command.HasParent()
147}
149// RootHelpFunc renders help text for the given command. Help is a
150// successful-output channel, so it is written to streams.StdOut. The "unknown
151// command" suggestion path is diagnostic and is routed to streams.StdErr. See
152// NewCmdRoot for the wiring and gitlab-org/cli#8371 for the motivation.
153func RootHelpFunc(streams *iostreams.IOStreams, command *cobra.Command, args []string) {
154 c := streams.Color()
155 originalLong := command.Long
156 originalExample := command.Example
158 if command.Long != "" {
159 command.Long = renderWithGlamour(command.Long)
160 }
161 if command.Example != "" {
162 command.Example = renderWithGlamour(command.Example)
163 }
165 if isRootCmd(command.Parent()) && len(args) >= 2 && args[1] != "--help" && args[1] != "-h" {
166 nestedSuggestFunc(streams.StdErr, command, args[1])
167 hasFailed = true
169 command.Long = originalLong
170 command.Example = originalExample
171 return
172 }
174 var coreCommands []string
175 var additionalCommands []string
176 for _, c := range command.Commands() {
177 if c.Short == "" {
178 continue
179 }
180 if !c.IsAvailableCommand() {
181 continue
182 }
184 s := rpad(c.Name()+":", c.NamePadding()) + c.Short
185 if _, ok := c.Annotations["IsCore"]; ok {
186 coreCommands = append(coreCommands, s)
187 } else {
188 additionalCommands = append(additionalCommands, s)
189 }
190 }
192 // If there are no core commands, assume everything is a core command
193 if len(coreCommands) == 0 {
194 coreCommands = additionalCommands
195 additionalCommands = []string{}
196 }
198 type helpEntry struct {
199 Title string
200 Body string
201 }
203 var helpEntries []helpEntry
204 if command.Long != "" {
205 helpEntries = append(helpEntries, helpEntry{"", command.Long})
206 } else if command.Short != "" {
207 helpEntries = append(helpEntries, helpEntry{"", command.Short})
208 }
209 helpEntries = append(helpEntries, helpEntry{"USAGE", command.UseLine()})
210 if len(command.Aliases) > 0 {
211 helpEntries = append(helpEntries, helpEntry{"ALIASES", dedent(strings.Join(command.Aliases, ", "))})
212 }
213 if len(coreCommands) > 0 {
214 helpEntries = append(helpEntries, helpEntry{"CORE COMMANDS", strings.Join(coreCommands, "\n")})
215 }
216 if len(additionalCommands) > 0 {
217 helpEntries = append(helpEntries, helpEntry{"ADDITIONAL COMMANDS", strings.Join(additionalCommands, "\n")})
218 }
220 flagUsages := command.LocalFlags().FlagUsages()
221 if flagUsages != "" {
222 helpEntries = append(helpEntries, helpEntry{"FLAGS", dedent(flagUsages)})
223 }
224 inheritedFlagUsages := command.InheritedFlags().FlagUsages()
225 if inheritedFlagUsages != "" {
226 helpEntries = append(helpEntries, helpEntry{"INHERITED FLAGS", dedent(inheritedFlagUsages)})
227 }
228 if command.Example != "" {
229 helpEntries = append(helpEntries, helpEntry{"EXAMPLES", command.Example})
230 }
231 for _, s := range AnnotationSections(command) {
232 helpEntries = append(helpEntries, helpEntry{strings.ToUpper(s.Title), s.Body})
233 }
234 helpEntries = append(helpEntries, helpEntry{"LEARN MORE", `
235Use 'glab <command> <subcommand> --help' for more information about a command.`})
236 if _, ok := command.Annotations["help:feedback"]; ok {
237 helpEntries = append(helpEntries, helpEntry{"FEEDBACK", command.Annotations["help:feedback"]})
238 }
240 for _, e := range helpEntries {
241 if e.Title != "" {
242 // If there is a title, add indentation to each line in the body
243 streams.LogInfo(c.Bold(e.Title))
244 streams.LogInfo(utils.Indent(strings.Trim(e.Body, "\r\n"), " "))
245 } else {
246 // If there is no title print the body as is
247 streams.LogInfo(e.Body)
248 }
249 streams.LogInfo()
250 }
252 command.Long = originalLong
253 command.Example = originalExample
254}
256// rpad adds padding to the right of a string.
257func rpad(s string, padding int) string {
258 template := fmt.Sprintf("%%-%ds ", padding)
259 return fmt.Sprintf(template, s)
260}
262func dedent(s string) string {
263 lines := strings.Split(s, "\n")
264 minIndent := -1
266 for _, l := range lines {
267 if l == "" {
268 continue
269 }
271 indent := len(l) - len(strings.TrimLeft(l, " "))
272 if minIndent == -1 || indent < minIndent {
273 minIndent = indent
274 }
275 }
277 if minIndent <= 0 {
278 return s
279 }
281 var buf bytes.Buffer
282 for _, l := range lines {
283 fmt.Fprintln(&buf, strings.TrimPrefix(l, strings.Repeat(" ", minIndent))) //nolint:forbidigo // writing to a bytes.Buffer, not stdout/stderr
284 }
285 return strings.TrimSuffix(buf.String(), "\n")
286}
Diagnostics7 git calls · 36 ms
CallStatusSizeTime036 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 KiB3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
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=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=4 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:0200172 B · 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=172 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=9cf14981aa55bb2b8bcfc2f2549219dc92956502 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=172 git.pkt.payload.max=145 git.sideband.band1.bytes=145 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=145 git.pack.trailer=aa21db2332923792c8da6536bfb011ad61d33c6cOpen pack map
fetch2003.4 KiB · hit21 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=21 git.response.bytes=3438 git.response.cache=HIT git.response.duration_ms=21 git.fetch.wants=060bc1fe2c8724884ebdf79d2b35eb3700e51893 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=3438 git.pkt.payload.max=3411 git.sideband.band1.bytes=3411 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
- a5e1eb86482b452a
- Request
- 9d57ee47…
- 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