-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
216 lines (188 loc) · 5.58 KB
/
Copy pathmain.go
File metadata and controls
216 lines (188 loc) · 5.58 KB
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package main
import (
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"text/template"
// "sort"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
// "github.com/IBM-Cloud/ibm-cloud-cli-sdk/plugin"
sl_plugin "github.ibm.com/SoftLayer/softlayer-cli/plugin"
)
var fileName string
var outputPath string
var debug bool
var rootCmd = &cobra.Command{
Use: "doc-gen",
Short: "Generate the documentation for the sl plugin",
RunE: func(Cmd *cobra.Command, args []string) error {
CliDocs()
return nil
},
}
func main() {
rootCmd.Flags().StringVarP(&outputPath, "output", "o", "./docs", "Output path, default to ./docs .")
rootCmd.Flags().BoolVarP(&debug, "verbose", "v", false, "Enable Debug logging.")
err := rootCmd.Execute()
checkError(err)
return
}
func checkError(err error) {
if err != nil {
panic(err)
}
}
// For top level commands, like `sl account` or `sl hardware`
type SlCmdGroup struct {
Name string
CommandShortLink string
Commands []SlCmdDoc
Help string
}
// For specific commands
type SlCmdDoc struct {
Name string
CommandShortLink string
Use string
Flags []SlCmdFlag
Help string
LongHelp string
Backtick string
CommandPath string
}
// For a commands flags
type SlCmdFlag struct {
Name string
Help string
Default string
}
// This function builds the documentation for IBMCLOUD docs
func CliDocs() {
// fmt.Printf("IBMCLOUD SL Command Directory\n")
SlCommands := sl_plugin.GetTopCobraCommand(nil, nil)
CmdGroups := []SlCmdGroup{}
for _, iCmd := range SlCommands.Commands() {
shortName := strings.ReplaceAll(iCmd.Name(), " ", "_")
shortName = strings.ReplaceAll(iCmd.Name(), "-", "_")
thisCmdGroup := SlCmdGroup{
Name: iCmd.Name(),
CommandShortLink: fmt.Sprintf("sl_%v", shortName),
Commands: nil,
Help: iCmd.Short,
}
if len(iCmd.Commands()) > 0 {
thisCmdGroup.Commands = buildSlCmdDoc(iCmd)
} else {
// This is a single command, like 'call-api' and doesn't have sub-commands
thisCmdGroup.Commands = []SlCmdDoc{cobraToSl(iCmd, "")}
}
printDebug(fmt.Sprintf("Working on command group %s\n", shortName))
PrintMakrdown(thisCmdGroup)
CmdGroups = append(CmdGroups, thisCmdGroup)
}
jOut, err := json.MarshalIndent(CmdGroups, "", " ")
checkError(err)
err = os.WriteFile("sl.json", jOut, 0755) //#nosec G306 -- This is a false positive
checkError(err)
// fmt.Println(string(jOut))
}
// Generates the Markdown
func PrintMakrdown(cmd SlCmdGroup) {
var cmdTemplate = `<!-- THIS FILE IS AUTOMATICALLY GENERATED, DO NOT EDIT -->
<!-- markdownlint-disable first-heading-h1 lastupdated-misformat-or-missing frontmatter-yaml -->
{{range .Commands}}
## ibmcloud {{.CommandPath}}
{: #{{.CommandShortLink}}}
{{.Help}}
{{.LongHelp}}
{{.Backtick}}bash
ibmcloud {{.Use}}
{{.Backtick}}
{: codeblock}
{{if .Flags}}
**Command options**:
{{range .Flags}}
--{{.Name}}
: {{.Help}}
{{end}}{{end}}{{end}}`
mdTemplate, err := template.New("cmd template").Parse(cmdTemplate)
checkError(err)
filename := fmt.Sprintf("%s/%v.md", outputPath, cmd.CommandShortLink)
printDebug(fmt.Sprintf("\tCreating file %s\n", filename))
outfile, err := os.Create(filename) //#nosec G304 -- This is a false positive
defer outfile.Close()
err = mdTemplate.Execute(outfile, cmd)
checkError(err)
}
func getLongHelp(helpString string) string {
// Removes some ugly empty lines sometimes.
empty_line := regexp.MustCompile(`(?m)^(\t)+$`)
helpString = empty_line.ReplaceAllString(helpString, "")
helpString = strings.ReplaceAll(helpString, "${COMMAND_NAME}", "ibmcloud")
example_regex := regexp.MustCompile(`(?i)Example:+`)
helpString = example_regex.ReplaceAllString(helpString, "**Examples**:\n")
// for 'indented-by-two'
indent_regex := regexp.MustCompile(`(?m)^ {2}(\S)`)
helpString = indent_regex.ReplaceAllString(helpString, " $1")
return getFlagHelp(helpString)
}
func getFlagHelp(helpString string) string {
// for 'no-inline-html' errors
fake_html_regex := regexp.MustCompile(`<([0-9A-Za-z_\-\.\s]+)>`)
helpString = fake_html_regex.ReplaceAllString(helpString, "$1")
// for 'no-reversed-links'
fake_link_regex := regexp.MustCompile(`\)\[`)
helpString = fake_link_regex.ReplaceAllString(helpString, ") [")
return helpString
}
func buildSlCmdDoc(topCommand *cobra.Command) []SlCmdDoc {
docs := []SlCmdDoc{}
for _, iCmd := range topCommand.Commands() {
thisDoc := cobraToSl(iCmd, topCommand.Name())
docs = append(docs, thisDoc)
}
return docs
}
func cobraToSl(iCmd *cobra.Command, tlcmd string) SlCmdDoc {
shortName := fmt.Sprintf("sl_%s_%s", tlcmd, iCmd.Name())
shortName = strings.ReplaceAll(shortName, " ", "_")
shortName = strings.ReplaceAll(shortName, "-", "_")
longHelp := getLongHelp(iCmd.Long)
thisDoc := SlCmdDoc{
Name: iCmd.Name(),
CommandShortLink: shortName,
CommandPath: iCmd.CommandPath(),
Use: iCmd.UseLine(),
Flags: nil,
Help: iCmd.Short,
LongHelp: longHelp,
Backtick: "```",
}
thisDoc.Flags = buildSlCmdFlag(iCmd)
return thisDoc
}
func buildSlCmdFlag(topCommand *cobra.Command) []SlCmdFlag {
flags := []SlCmdFlag{}
flagSet := topCommand.Flags()
flagSet.VisitAll(func(pflag *pflag.Flag) {
flagName := pflag.Name
if pflag.Shorthand != "" {
flagName = fmt.Sprintf("%s, %s", pflag.Shorthand, flagName)
}
thisFlag := SlCmdFlag{
Name: flagName,
Help: getFlagHelp(pflag.Usage),
Default: pflag.DefValue,
}
flags = append(flags, thisFlag)
})
return flags
}
func printDebug(output string) {
if debug {
fmt.Printf("%s", output)
}
}