Debian Codegraph @

usage/printer.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 package usage
2
3 import (
4 "bytes"
5 "fmt"
6 "io"
7 "regexp"
8 "strings"
9 "text/template"
10 "unicode"
11
•12 md "github.com/russross/blackfriday/v2"
13 "github.com/urfave/cli"
14 )
15
16 var sectionRe = regexp.MustCompile(`(?m:^##)`)
17 var sectionNameRe = regexp.MustCompile(`(?m:^## [^\n]+)`)
18 var indentRe = regexp.MustCompile(`(?m:^:[^\n]+)`)
19 var definitionListRe = regexp.MustCompile(`(?m:^[\t ]+\*\*[^\*]+\*\*[^\n]*\s+:[^\n]+)`)
20
21 //var sectionRe = regexp.MustCompile(`^## [^\n]*$`)
22
23 type frontmatterData struct {
24 Data interface{}
25 Parent string
26 Children []string
27 }
28
29 // HelpPrinter overwrites cli.HelpPrinter and prints the formatted help to the terminal.
30 func HelpPrinter(w io.Writer, templ string, data interface{}) {
31 b := helpPreprocessor(w, templ, data, false)
32 w.Write(Render(b))
33 }
34
35 func htmlHelpPrinter(w io.Writer, templ string, data interface{}) []byte {
36 b := helpPreprocessor(w, templ, data, true)
37 w.Write([]byte(`<html><head><title>step command line documentation</title>`))
38 w.Write([]byte(`<link href="/style.css" rel="stylesheet" type="text/css">`))
39 w.Write([]byte(`</head><body><div class="wrapper markdown-body command">`))
40 html := md.Run(b)
41 w.Write(html)
42 w.Write([]byte(`</div></body></html>`))
43
44 return html
45 }
46
47 func markdownHelpPrinter(w io.Writer, templ string, parent string, data interface{}) {
48 b := helpPreprocessor(w, templ, data, true)
49
50 frontmatter := frontmatterData{
51 Data: data,
52 Parent: parent,
53 }
54
55 if app, ok := data.(*cli.App); ok {
56 for _, cmd := range app.Commands {
57 frontmatter.Children = append(frontmatter.Children, cmd.Name)
58 }
59 }
60
61 var frontMatterTemplate = `---
62 layout: auto-doc
63 title: {{.Data.HelpName}}
64 menu:
65 docs:
66 {{- if .Parent}}
67 parent: {{.Parent}}
68 {{- end }}
69 {{- if .Children }}
70 children:
71 {{- range .Children }}
72 - {{.}}
73 {{- end }}
74 {{- end }}
75 ---
76
77 `
78 t, err := template.New("frontmatter").Parse(frontMatterTemplate)
79 if err != nil {
80 panic(err)
81 }
82 err = t.Execute(w, frontmatter)
83 if err != nil {
84 panic(err)
85 }
86 w.Write(b)
87 }
88
89 func helpPreprocessor(w io.Writer, templ string, data interface{}, applyRx bool) []byte {
90 buf := new(bytes.Buffer)
91 cli.HelpPrinterCustom(buf, templ, data, nil)
92 //w.Write(buf.Bytes())
93 // s := string(markdownify(buf.Bytes()))
94 s := markdownify(buf)
95 // Move the OPTIONS section to the right place. urfave puts them at the end
96 // of the file, we want them to be after POSITIONAL ARGUMENTS, DESCRIPTION,
97 // USAGE, or NAME (in that order, depending on which sections exist).
98 optLoc := strings.Index(s, "## OPTIONS")
99 if optLoc != -1 {
100 optEnd := findSectionEnd("OPTIONS", s)
101 if optEnd != -1 {
102 options := s[optLoc:optEnd]
103 s = s[:optLoc] + s[optEnd:]
104 if newLoc := findSectionEnd("POSITIONAL ARGUMENTS", s); newLoc != -1 {
105 s = s[:newLoc] + options + s[newLoc:]
106 } else if newLoc := findSectionEnd("DESCRIPTION", s); newLoc != -1 {
107 s = s[:newLoc] + options + s[newLoc:]
108 } else if newLoc := findSectionEnd("USAGE", s); newLoc != -1 {
109 s = s[:newLoc] + options + s[newLoc:]
110 } else if newLoc := findSectionEnd("NAME", s); newLoc != -1 {
111 s = s[:newLoc] + options + s[newLoc:]
112 } else {
113 // Keep it at the end I guess :/.
114 s = s + options
115 }
116 }
117 }
118
119 if applyRx {
120 // Keep capitalized only the first letter in arguments names.
121 s = sectionNameRe.ReplaceAllStringFunc(s, func(s string) string {
122 return s[0:4] + strings.ToLower(s[4:])
123 })
124 // Remove `:` at the start of a line.
125 s = indentRe.ReplaceAllStringFunc(s, func(s string) string {
126 return strings.TrimSpace(s[1:])
127 })
128 // Convert lines like:
129 // **Foo**
130 // : Bar zar ...
131 // To:
132 // - **Foo**: Bar zar ...
133 s = definitionListRe.ReplaceAllStringFunc(s, func(s string) string {
134 i := strings.Index(s, "\n")
135 j := strings.Index(s, ":")
136 return "- " + strings.TrimSpace(s[:i]) + ": " + strings.TrimSpace(s[j+1:])
137 })
138 }
139
140 return []byte(s)
141 }
142
143 func findSectionEnd(h, s string) int {
144 start := strings.Index(s, fmt.Sprintf("## %s", h))
145 if start == -1 {
146 return start
147 }
148 nextSection := sectionRe.FindStringIndex(s[start+2:])
149 if nextSection == nil {
150 return len(s)
151 }
152 return start + 2 + nextSection[0]
153 }
154
155 // Convert some stuff that we can't easily write in help files because
156 // backticks and raw strings don't mix:
157 // - "<foo>" to "`foo`"
158 // - "'''" to "```"
159 func markdownify(r *bytes.Buffer) string {
160 const escapeByte = byte('\\')
161 var last byte
162 var inCode bool
163
164 w := new(bytes.Buffer)
165 for {
166 b, err := r.ReadByte()
167 if err != nil {
168 return w.String()
169 }
170 loop:
171 switch b {
172 case '<':
173 if last != escapeByte && !inCode {
174 w.WriteByte('`')
175 } else {
176 w.WriteByte(b)
177 }
178 case '>':
179 if last != escapeByte && !inCode {
180 w.WriteByte('`')
181 } else {
182 w.WriteByte(b)
183 }
184 case '\'':
185 b1, _ := r.ReadByte()
186 b2, _ := r.ReadByte()
187 if b1 == b && b2 == b {
188 w.WriteString("```")
189 if !inCode {
190 if n, _, err := r.ReadRune(); err == nil {
191 if unicode.IsSpace(n) {
192 w.WriteString("shell")
193 }
194 r.UnreadRune()
195 }
196 }
197 inCode = !inCode
198 } else {
199 // We can only unread the last one (b2)
200 w.WriteByte(b)
201 r.UnreadByte()
202 b = b1
203 last = b
204 goto loop
205 }
206 case '*':
207 if inCode {
208 if b1, _ := r.ReadByte(); b1 != '*' {
209 w.WriteByte(b)
210 w.UnreadByte()
211 }
212 } else {
213 w.WriteByte(b)
214 }
215 case escapeByte:
216 if last == escapeByte {
217 w.WriteByte(escapeByte)
218 b = 0
219 } else {
220 if n, _, err := r.ReadRune(); err == nil {
221 if unicode.IsSpace(n) {
222 w.WriteByte(escapeByte)
223 }
224 r.UnreadRune()
225 }
226 }
227 case 0: // probably because io.EOF
228 default:
229 w.WriteByte(b)
230 }
231 last = b
232 }
233 }