-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtmpl.go
126 lines (104 loc) · 2.41 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package clic
import (
"bytes"
"fmt"
"strings"
"text/template"
)
// TmplData is the structure used for usage output templating. Custom template
// string values should be based on this type.
type TmplData struct {
ResolvedCmd *Clic
ResolvedCmdSet []*Clic
}
// TmplConfig tracks the template string and function map used for usage output
// templating.
type TmplConfig struct {
Text string
FMap template.FuncMap
}
// NewDefaultTmplConfig returns the default TmplConfig value. This can be used
// as an example of how to setup custom usage output templating.
func NewDefaultTmplConfig() *TmplConfig {
resolvedCmdSetHintFn := func(cmds []*Clic) string {
var out, sep string
for _, cmd := range cmds {
out += sep + cmd.FlagSet.Name()
sep = " "
if len(cmd.FlagSet.Flags()) > 0 {
out += sep + "[FLAGS]"
}
}
return out
}
subsAndOperandsHintFn := func(cmd *Clic) string {
var out, sep string
var anySubShowing bool
for _, sub := range cmd.subs {
if sub.HideUsage {
continue
}
anySubShowing = true
out += sep + sub.FlagSet.Name()
sep = "|"
}
if anySubShowing {
pre, suf := "[", "]"
if cmd.SubRequired {
pre, suf = "{", "}"
}
out = pre + out + suf
if len(cmd.OperandSet.Operands()) == 0 {
return " " + out
}
out += " | "
sep = ""
}
for _, op := range cmd.OperandSet.Operands() {
pre, suf := "[", "]"
if op.IsRequired() {
pre, suf = "<", ">"
}
out += sep + pre + op.Name() + suf
sep = " "
}
pre, suf := "{", "}"
if !anySubShowing {
pre, suf = "", ""
}
return " " + pre + out + suf
}
tmplFMap := template.FuncMap{
"ResolvedCmdSetHint": resolvedCmdSetHintFn,
"SubsAndOperandsHint": subsAndOperandsHintFn,
}
tmplText := strings.TrimSpace(`
{{- $cmd := .ResolvedCmd -}}
Usage:
{{if .}} {{end}}{{ResolvedCmdSetHint .ResolvedCmdSet}}
{{- SubsAndOperandsHint $cmd}}
{{- if $cmd.Description}}
{{$cmd.Description}}
{{- end}}
{{if $cmd.FlagSet.Flags}}
{{$cmd.FlagSet.Usage}}{{- end}}
`)
return &TmplConfig{
Text: tmplText,
FMap: tmplFMap,
}
}
func executeTmpl(tc *TmplConfig, data any) string {
tmpl := template.New("clic").Funcs(tc.FMap)
buf := &bytes.Buffer{}
tmpl, err := tmpl.Parse(tc.Text)
if err != nil {
fmt.Fprintf(buf, "%v\n", err)
return buf.String()
}
if err := tmpl.Execute(buf, data); err != nil {
fmt.Fprintf(buf, "%v\n", err)
return buf.String()
}
return buf.String()
}