internal/control/help.go
386 lines · 13224 bytes
1package control
2
3import (
4 "fmt"
5 "io"
6 "slices"
7 "strings"
8
9 "gitbay.org/gitbay/internal/protocol"
10 "gitbay.org/gitbay/internal/termtext"
11)
12
13func init() {
14 register(Command{
15 Path: []string{"help"},
16 Summary: "list available commands",
17 Usage: "help [<prefix>...]",
18 Examples: []string{"help", "help repo"},
19 ReadOnly: true,
20 Run: runHelp,
21 })
22}
23
24// nounSummaries is one line per distinct first path element in the
25// registry, reusing the CLI's group short texts (cmd/gitbay/main.go)
26// where the noun matches, so the two agree.
27var nounSummaries = map[string]string{
28 "account": "export or import your account, for instance migration",
29 "admin": "instance administration (admins)",
30 "audit": "instance audit log (admins)",
31 "auth": "whoami, SSH and PGP keys, email, API tokens",
32 "build": "CI builds",
33 "dashboard": "pinned repos, open MRs, assigned issues, recent builds",
34 "email": "manage email addresses",
35 "explore": "public repositories on this instance",
36 "feed": "activity on repositories you can reach",
37 "help": "list available commands",
38 "issue": "issues",
39 "keys": "manage SSH keys",
40 "label": "issue labels",
41 "milestone": "group issues and MRs toward a release",
42 "mr": "merge requests",
43 "notifications": "your notification inbox",
44 "org": "organizations",
45 "pgp": "manage OpenPGP keys",
46 "profile": "user and org profiles",
47 "register": "create an account on this instance",
48 "release": "tag-anchored releases with notes and assets",
49 "repo": "create and manage repositories",
50 "runner": "the claim/report loop CI runners use",
51 "search": "find repositories, issues and merge requests",
52 "query": "saved issue and merge request queries across repositories",
53 "snippet": "shared text files, outside any repository",
54 "status": "commit statuses (CI)",
55 "token": "API tokens (minted over SSH, used with the JSON API)",
56 "web": "browser session",
57 "webhook": "outbound event delivery",
58 "whoami": "show the authenticated account",
59 "wiki": "a repository's wiki pages",
60}
61
62// NounSummaries returns nounSummaries, for the CLI group-text agreement
63// test (task 4.5).
64func NounSummaries() map[string]string { return nounSummaries }
65
66// nounAlias is one bucket of registered commands, reachable under a
67// CLI-only noun that is not itself a registry path (auth, gathering
68// several unrelated registry prefixes): Registered is what runHelp
69// matches against the registry, CLI is the path a gitbay caller
70// actually types to reach it — not always Registered with the alias's
71// own name stitched on (account export -> auth export drops a word),
72// so the two are paired explicitly rather than derived.
73type nounAlias struct {
74 Registered string
75 CLI string
76}
77
78// nounAliases groups a CLI-only noun into the real prefixes it gathers,
79// so `help auth` renders with the same layout a real noun gets instead
80// of falling back to whatever a caller does when help fails. A stock
81// ssh caller — the only one who could ever ask for a bare "auth" and
82// get nothing back from the registry — sees the Registered forms
83// unchanged; the CLI, having sent its own path, sees CLI.
84var nounAliases = map[string][]nounAlias{
85 "auth": {
86 {"account export", "auth export"},
87 {"whoami", "auth whoami"},
88 {"keys", "auth keys"},
89 {"email", "auth email"},
90 {"pgp", "auth pgp"},
91 {"token", "auth token"},
92 },
93}
94
95// NounAliasNames returns the keys of nounAliases, for the CLI's own
96// aliasGroupNames agreement test.
97func NounAliasNames() []string {
98 names := make([]string, 0, len(nounAliases))
99 for name := range nounAliases {
100 names = append(names, name)
101 }
102 return names
103}
104
105// helpEntry is one row of the registry as help reports it.
106type helpEntry struct {
107 Path string `json:"path"`
108 Summary string `json:"summary"`
109 Usage string `json:"usage"`
110 Flags []Flag `json:"flags,omitempty"`
111 Examples []string `json:"examples,omitempty"`
112}
113
114// aliasPaths maps each registered command path under an aliased noun to
115// the path the CLI shows for it.
116func aliasPaths(aliased []nounAlias) map[string]string {
117 paths := map[string]string{}
118 for _, cmd := range registry {
119 p := joinPath(cmd.Path)
120 for _, a := range aliased {
121 if p == a.Registered || strings.HasPrefix(p, a.Registered+" ") {
122 paths[p] = a.CLI + strings.TrimPrefix(p, a.Registered)
123 break
124 }
125 }
126 }
127 return paths
128}
129
130// runHelp lists the registry, sorted, so a noun's commands sit together.
131// Bare `help` stays one line per command. A prefix that names one command
132// exactly renders its full USAGE/FLAGS/EXAMPLES; a prefix that names a
133// noun with several commands under it renders a READ/WRITE summary.
134func runHelp(c *Ctx, args []string) int {
135 prefix := joinPath(args)
136 prefixes := []string{prefix}
137 override := map[string]string{}
138 if aliased, ok := nounAliases[prefix]; ok {
139 prefixes = nil
140 for _, a := range aliased {
141 prefixes = append(prefixes, a.Registered)
142 }
143 if c.CLIPath != "" {
144 override = aliasPaths(aliased)
145 }
146 }
147 var matched []Command
148 for _, cmd := range registry {
149 p := joinPath(cmd.Path)
150 for _, pfx := range prefixes {
151 if pfx == "" || p == pfx || strings.HasPrefix(p, pfx+" ") {
152 matched = append(matched, cmd)
153 break
154 }
155 }
156 }
157 if len(matched) == 0 {
158 return c.fail(protocol.ExitNotFound, "no command matches %q; try: help", prefix)
159 }
160 slices.SortFunc(matched, func(a, b Command) int { return strings.Compare(joinPath(a.Path), joinPath(b.Path)) })
161 entries := make([]helpEntry, len(matched))
162 for i, cmd := range matched {
163 entries[i] = helpEntry{Path: joinPath(cmd.Path), Summary: cmd.Summary, Usage: cmd.Usage, Flags: cmd.Flags, Examples: cmd.Examples}
164 }
165 return c.emit(entries, func(w io.Writer) {
166 switch {
167 case prefix == "":
168 for _, e := range entries {
169 summary := e.Summary
170 if c.Term.Cols > 0 {
171 if avail := c.Term.Cols - max(cells(e.Path), 24) - 1; avail > 0 {
172 summary = clip(summary, avail)
173 }
174 }
175 fmt.Fprintf(w, "%-24s %s\n", e.Path, summary)
176 }
177 case joinPath(matched[0].Path) == prefix:
178 c.helpVerb(w, matched[0], matched[1:])
179 default:
180 c.helpNoun(w, prefix, matched, override)
181 }
182 })
183}
184
185// viaCLI reports whether the caller is the gitbay CLI, as far as the
186// session says: a terminal (only the CLI or a caller passing --term sets
187// one), or a CLI path, which only the CLI sends.
188func (c *Ctx) viaCLI() bool {
189 return c.Term.Cols > 0 || c.CLIPath != ""
190}
191
192// program is how help spells the command it documents: gitbay for the
193// CLI, ssh otherwise.
194func (c *Ctx) program() string {
195 if c.viaCLI() {
196 return "gitbay"
197 }
198 return "ssh git@" + hostOf(c.Cfg.Server.SiteURL)
199}
200
201// cliUsage marks a leading <owner/name> optional in a usage line for the
202// CLI, which infers it inside a clone (cmd/gitbay/ssh.go's withRepo).
203// Stock ssh never does.
204func cliUsage(usage string) string {
205 return strings.Replace(usage, "<owner/name>", "[<owner/name>]", 1)
206}
207
208// shownAs rewrites full, which starts with the registered path, to start
209// with the CLI's path instead when the CLI sent one that differs (#267).
210// The CLI path must name this command: either it regroups it (the same
211// last word, auth keys remove for keys remove) or extends it (repo
212// topics list for repo topics). Arguments after a CLI command can
213// dispatch to a longer registered path (gitbay repo topics list add
214// reaches repo topics add), and that command keeps its own name.
215func (c *Ctx) shownAs(registered, full string) string {
216 rest, ok := strings.CutPrefix(full, registered)
217 if !ok || c.CLIPath == "" || c.CLIPath == registered {
218 return full
219 }
220 reg, cli := strings.Fields(registered), strings.Fields(c.CLIPath)
221 if len(reg) == 0 || len(cli) == 0 || (cli[len(cli)-1] != reg[len(reg)-1] && !strings.HasPrefix(c.CLIPath, registered+" ")) {
222 return full
223 }
224 return c.CLIPath + rest
225}
226
227// shownBelow is how another command listed beside registered prints to
228// this caller. When the CLI only regrouped the command (auth keys remove
229// for keys remove, the same last word) the other command takes the CLI's
230// parent in place of the registered one. When the CLI renamed the last
231// word (repo topics list for repo topics) nothing follows about the
232// other command's name, so it keeps its registered path.
233func (c *Ctx) shownBelow(registered, other string) string {
234 reg, cli, o := strings.Fields(registered), strings.Fields(c.CLIPath), strings.Fields(other)
235 if len(cli) == 0 || len(reg) == 0 || len(o) < len(reg) {
236 return other
237 }
238 if cli[len(cli)-1] != reg[len(reg)-1] || !slices.Equal(o[:len(reg)-1], reg[:len(reg)-1]) {
239 return other
240 }
241 return joinPath(append(slices.Clip(cli[:len(cli)-1]), o[len(reg)-1:]...))
242}
243
244// usageShape is a usage line for the command registered at path as this
245// caller should see it: the CLI's path in place of the registered one
246// where they differ, and a leading <owner/name> optional for the CLI.
247func (c *Ctx) usageShape(path []string, usage string) string {
248 shape := c.shownAs(joinPath(path), usage)
249 if c.viaCLI() {
250 shape = cliUsage(shape)
251 }
252 return shape
253}
254
255// cmdUsage is the running command's usage with the program in front, as
256// a usage refusal prints it.
257func (c *Ctx) cmdUsage() string {
258 return c.program() + " " + c.usageShape(c.Cmd.Path, c.Cmd.Usage)
259}
260
261func (c *Ctx) heading(w io.Writer, s string) {
262 fmt.Fprintln(w, c.Term.paint(sgrBold, s))
263}
264
265// wrapLine prints prefix+text, wrapping text at Term.Cols with a hanging
266// indent under prefix when it would overflow. Plain output never wraps.
267func (c *Ctx) wrapLine(w io.Writer, prefix, text string) {
268 if c.Term.Cols <= 0 || cells(prefix+text) <= c.Term.Cols {
269 fmt.Fprintln(w, prefix+text)
270 return
271 }
272 indent := cells(prefix)
273 width := c.Term.Cols - indent
274 for i, line := range termtext.Wrap(text, width) {
275 if i == 0 {
276 fmt.Fprintln(w, prefix+line)
277 } else {
278 fmt.Fprintln(w, strings.Repeat(" ", indent)+line)
279 }
280 }
281}
282
283func (c *Ctx) helpVerb(w io.Writer, cmd Command, below []Command) {
284 fmt.Fprintln(w, cmd.Summary)
285 fmt.Fprintln(w)
286 c.heading(w, "USAGE")
287 // Cutting at the first optional flag drops the rest of the usage
288 // syntax behind "[flags]" — safe only for what is actually optional.
289 // A required flag (repo delete --yes) or an alternative
290 // (notifications read <id>... | --all) has no " [--" to cut at, so
291 // the usage prints whole.
292 registered := joinPath(cmd.Path)
293 shape := c.usageShape(cmd.Path, cmd.Usage)
294 if i := strings.Index(shape, " [--"); i >= 0 {
295 shape = shape[:i] + " [flags]"
296 }
297 fmt.Fprintf(w, " %s %s\n", c.program(), shape)
298 fmt.Fprintln(w)
299 c.heading(w, "FLAGS")
300 rows := make([][2]string, 0, len(cmd.Flags)+1)
301 for _, f := range cmd.Flags {
302 name := f.Name
303 if f.Arg != "" {
304 name += " " + f.Arg
305 }
306 desc := f.Desc
307 if f.Default != "" {
308 desc += " (default " + f.Default + ")"
309 }
310 rows = append(rows, [2]string{name, desc})
311 }
312 rows = append(rows, [2]string{"--json", "machine-readable output"})
313 wide := 0
314 for _, r := range rows {
315 wide = max(wide, cells(r[0]))
316 }
317 for _, r := range rows {
318 c.wrapLine(w, " "+pad(r[0], wide)+" ", r[1])
319 }
320 if len(cmd.Examples) > 0 {
321 fmt.Fprintln(w)
322 c.heading(w, "EXAMPLES")
323 for _, ex := range cmd.Examples {
324 c.wrapLine(w, " "+c.program()+" ", c.shownAs(registered, ex))
325 }
326 }
327 if len(below) > 0 {
328 fmt.Fprintln(w)
329 c.heading(w, "SEE ALSO")
330 for _, b := range below {
331 fmt.Fprintf(w, " %s %s\n", c.program(), c.shownBelow(registered, joinPath(b.Path)))
332 }
333 }
334}
335
336// helpNoun renders a noun with several commands under it. override, from
337// an aliased noun (auth), gives the full CLI path for a row that is not
338// itself under prefix (keys list, gathered under auth, becomes "auth
339// keys list"); it is empty for an ordinary noun, so every row there
340// still trims to just its own verb.
341func (c *Ctx) helpNoun(w io.Writer, prefix string, cmds []Command, override map[string]string) {
342 head := nounSummaries[strings.Fields(prefix)[0]]
343 fmt.Fprintln(w, head)
344 // An aliased noun is a CLI grouping: over stock ssh there is no
345 // "auth <verb>" to type, and each row already names its full command.
346 _, aliased := nounAliases[prefix]
347 bare := aliased && c.CLIPath == ""
348 display := c.shownAs(prefix, prefix)
349 if !bare {
350 fmt.Fprintln(w)
351 c.heading(w, "USAGE")
352 fmt.Fprintf(w, " %s %s <verb> ...\n", c.program(), display)
353 }
354 rowText := func(cmd Command) string {
355 full := joinPath(cmd.Path)
356 if ov, ok := override[full]; ok {
357 return ov
358 }
359 return strings.TrimPrefix(full, prefix+" ")
360 }
361 wide := 0
362 for _, cmd := range cmds {
363 wide = max(wide, cells(rowText(cmd)))
364 }
365 for _, section := range []struct {
366 title string
367 read bool
368 }{{"READ", true}, {"WRITE", false}} {
369 first := true
370 for _, cmd := range cmds {
371 if cmd.ReadOnly != section.read {
372 continue
373 }
374 if first {
375 fmt.Fprintln(w)
376 c.heading(w, section.title)
377 first = false
378 }
379 fmt.Fprintf(w, " %s %s\n", pad(rowText(cmd), wide), cmd.Summary)
380 }
381 }
382 if !bare {
383 fmt.Fprintln(w)
384 fmt.Fprintf(w, "%s %s <verb> --help for flags.\n", c.program(), display)
385 }
386}