...
1
16
17 package templates
18
19 import (
20 "strings"
21
22 "github.com/MakeNowJust/heredoc"
23 "github.com/russross/blackfriday/v2"
24 "github.com/spf13/cobra"
25 )
26
27 const Indentation = ` `
28
29
30 func LongDesc(s string) string {
31 if len(s) == 0 {
32 return s
33 }
34 return normalizer{s}.heredoc().markdown().trim().string
35 }
36
37
38 func Examples(s string) string {
39 if len(s) == 0 {
40 return s
41 }
42 return normalizer{s}.trim().indent().string
43 }
44
45
46 func Normalize(cmd *cobra.Command) *cobra.Command {
47 if len(cmd.Long) > 0 {
48 cmd.Long = LongDesc(cmd.Long)
49 }
50 if len(cmd.Example) > 0 {
51 cmd.Example = Examples(cmd.Example)
52 }
53 return cmd
54 }
55
56
57 func NormalizeAll(cmd *cobra.Command) *cobra.Command {
58 if cmd.HasSubCommands() {
59 for _, subCmd := range cmd.Commands() {
60 NormalizeAll(subCmd)
61 }
62 }
63 Normalize(cmd)
64 return cmd
65 }
66
67 type normalizer struct {
68 string
69 }
70
71 func (s normalizer) markdown() normalizer {
72 bytes := []byte(s.string)
73 formatted := blackfriday.Run(bytes, blackfriday.WithExtensions(blackfriday.NoIntraEmphasis), blackfriday.WithRenderer(&ASCIIRenderer{Indentation: Indentation}))
74 s.string = string(formatted)
75 return s
76 }
77
78 func (s normalizer) heredoc() normalizer {
79 s.string = heredoc.Doc(s.string)
80 return s
81 }
82
83 func (s normalizer) trim() normalizer {
84 s.string = strings.TrimSpace(s.string)
85 return s
86 }
87
88 func (s normalizer) indent() normalizer {
89 indentedLines := []string{}
90 for _, line := range strings.Split(s.string, "\n") {
91 trimmed := strings.TrimSpace(line)
92 indented := Indentation + trimmed
93 indentedLines = append(indentedLines, indented)
94 }
95 s.string = strings.Join(indentedLines, "\n")
96 return s
97 }
98
View as plain text