-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
format.go
103 lines (87 loc) · 1.71 KB
/
format.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
package cobradoc
import (
_ "embed"
"errors"
"io"
"regexp"
"strings"
"text/template"
)
type formatInfo struct {
Options
GlobalFlags []flagInfo
GlobalFlagsBlock string
Groups []groupInfo
}
type groupInfo struct {
Title string
Commands []commandInfo
}
type commandInfo struct {
Path string
Usage string
Description string
Flags []flagInfo
FlagsBlock string
}
type flagInfo struct {
Short string
Long string
DefaultValue string
ValueIsOptional bool
IsBool bool
Type string
Description string
}
var (
//go:embed format_troff.tmpl
formatTroff string
//go:embed format_markdown.tmpl
formatMarkdown string
)
var formatTemplates = map[Format]string{
Troff: formatTroff,
Markdown: formatMarkdown,
}
var formatFuncs = map[Format]template.FuncMap{
Troff: {
"upper": func(s string) string {
return strings.ToUpper(s)
},
"escape": func(s string) string {
s = regexp.MustCompile(`\n+\n`).ReplaceAllString(s, "\n.PP\n")
s = strings.NewReplacer(
"-", "\\-", //
"_", "\\_", //
"&", "\\&", //
"\\", "\\\\", //
"~", "\\~", //
).Replace(s)
return s
},
},
Markdown: {
"anchor": func(s string) string {
return "#" + strings.ReplaceAll(s, " ", "-")
},
},
}
func format(fmt Format, fmtInfo formatInfo, w io.Writer) error {
templateText, ok := formatTemplates[fmt]
if !ok {
return errors.New("invalid format")
}
templateFuncs, ok := formatFuncs[fmt]
if !ok {
return errors.New("invalid format")
}
t, err := template.New("cobradoc").Funcs(templateFuncs).Parse(templateText)
if err != nil {
return err
}
err = t.Execute(w, fmtInfo)
if err != nil {
return err
}
return nil
}