at v0.4.1
1 | // See LICENSE file for copyright and license details |
2 | |
3 | // Package help implements the "shrt help" command |
4 | package help |
5 | |
6 | import ( |
7 | "context" |
8 | "fmt" |
9 | "io" |
10 | "log" |
11 | "strings" |
12 | "text/template" |
13 | |
14 | "djmo.ch/go-shrt/cmd/shrt/internal/base" |
15 | ) |
16 | |
17 | var usageTmpl = `{{ if .Usage }}usage: {{ .Usage }} |
18 | |
19 | {{ end }}{{ .LongHelp | trim }}{{ if .Subcommands }} |
20 | |
21 | The commands are: |
22 | {{ range .Subcommands -}}{{ if .Runnable }} |
23 | {{ .Name | printf "%-8s"}}{{ .ShortHelp }}{{ end }}{{ end }} |
24 | |
25 | Use "shrt help <command>" for more information about a command. |
26 | |
27 | Additional topics are: |
28 | {{ range .Subcommands -}}{{ if (not .Runnable) }} |
29 | {{ .Name | printf "%-12s"}}{{ .ShortHelp }}{{ end }}{{ end }} |
30 | |
31 | Use "shrt help <topic>" for more information about that topic.{{ end }} |
32 | ` |
33 | |
34 | func Help(ctx context.Context) { |
35 | var ( |
36 | args = ctx.Value("args").([]string) |
37 | w = ctx.Value("w").(io.Writer) |
38 | ) |
39 | if args == nil { |
40 | args = []string{} |
41 | } |
42 | switch len(args) { |
43 | case 0: |
44 | printUsage(w, base.Shrt) |
45 | case 1: |
46 | if args[0] == "documentation" { |
47 | printDocumentation(w) |
48 | return |
49 | } |
50 | cmd := base.FindCommand(args[0]) |
51 | if cmd == nil { |
52 | log.Fatal("unknown subcommand ", args[0]) |
53 | } |
54 | printUsage(w, cmd) |
55 | default: |
56 | log.Fatal("help expects at most one argument") |
57 | } |
58 | } |
59 | |
60 | func printDocumentation(w io.Writer) { |
61 | fmt.Fprintln(w, "// See LICENSE file for copyright and license details") |
62 | fmt.Fprintln(w, "// Code generated by 'go test ./cmd/shrt -v -run=TestDocsUpToDate -fixdocs'; DO NOT EDIT") |
63 | fmt.Fprintln(w, "// Edit the code in other files and then execute 'go generate ./cmd/shrt' to generate this one.") |
64 | fmt.Fprintln(w) |
65 | fmt.Fprintln(w, "/*") |
66 | printUsage(w, base.Shrt) |
67 | for _, cmd := range base.Shrt.Subcommands { |
68 | if cmd.LongHelp != "" { |
69 | fmt.Fprintln(w) |
70 | fmt.Fprintf(w, "# %s%s\n", strings.ToTitle(string(cmd.ShortHelp[0])), |
71 | cmd.ShortHelp[1:]) |
72 | fmt.Fprintln(w) |
73 | printUsage(w, cmd) |
74 | } |
75 | } |
76 | fmt.Fprintln(w, "*/") |
77 | fmt.Fprintln(w, "package main") |
78 | } |
79 | |
80 | func printUsage(w io.Writer, cmd *base.Command) { |
81 | tmpl := template.New(cmd.Name) |
82 | tmpl.Funcs(template.FuncMap{"trim": strings.TrimSpace}) |
83 | template.Must(tmpl.Parse(usageTmpl)) |
84 | tmpl.Execute(w, cmd) |
85 | } |