-
Notifications
You must be signed in to change notification settings - Fork 0
/
tmpl.go
88 lines (70 loc) · 1.79 KB
/
tmpl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package clic
import (
"bytes"
"fmt"
"slices"
"strings"
"text/template"
)
type tmplData struct {
Root *Clic
Current *Clic
Called []*Clic
}
var tmplText = strings.TrimSpace(`
{{- $cur := .Current -}}{{- $subsStarted := false -}}
{{- $leftBrack := "[" -}}{{- $rightBrack := "]" -}}
Usage:
{{if .}} {{end}}{{range $clic := .Called}}
{{- $clic.Handler.FlagSet.Name}} {{if $clic.Handler.FlagSet.Opts}}[FLAGS] {{end -}}
{{- if eq $cur.Handler.FlagSet.Name $clic.Handler.FlagSet.Name }}
{{- if $cur.Meta.SubRequired}}{{$leftBrack = "{"}}{{$rightBrack = "}"}}{{end -}}
{{- if $cur.Subs}}{{$leftBrack}}{{end}}{{range $i, $sub := $cur.Subs}}
{{- if $sub.Meta.SkipUsage}}{{continue}}{{end}}
{{- if and $i $subsStarted}}|{{end}}{{$sub.Handler.FlagSet.Name}}{{$subsStarted = true}}
{{- end}}{{if $cur.Subs}}{{$rightBrack}}{{end}}
{{- if $clic.Meta.ArgsHint}}{{$clic.Meta.ArgsHint}}{{end}}
{{- if $clic.Meta.CmdDesc}}
{{$clic.Meta.CmdDesc}}
{{- end}}
{{- end}}
{{- end}}
{{.Current.Handler.FlagSet.Usage}}
`)
func (c *Clic) Usage() string {
data := &tmplData{
Root: root(c),
Current: c,
Called: allCalled(c),
}
tmpl := template.New("clic")
buf := &bytes.Buffer{}
tmpl, err := tmpl.Parse(tmplText)
if err != nil {
fmt.Fprintf(buf, "cli command: template error: %v\n", err)
return buf.String()
}
if err := tmpl.Execute(buf, data); err != nil {
fmt.Fprintf(buf, "cli command: template error: %v\n", err)
return buf.String()
}
return buf.String()
}
func root(c *Clic) *Clic {
root := c
for root.Parent != nil {
root = root.Parent
}
return root
}
func allCalled(c *Clic) []*Clic {
var all []*Clic
cur := c
for cur.Parent != nil {
all = append(all, cur)
cur = cur.Parent
}
all = append(all, cur)
slices.Reverse(all)
return all
}