-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathdocs.go
More file actions
317 lines (276 loc) · 10.1 KB
/
Copy pathdocs.go
File metadata and controls
317 lines (276 loc) · 10.1 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package commandsgen
import (
"bytes"
"fmt"
"regexp"
"sort"
"strings"
)
func GenerateDocsFiles(commands Commands) (map[string][]byte, error) {
optionSetMap := make(map[string]OptionSets)
for i, optionSet := range commands.OptionSets {
optionSetMap[optionSet.Name] = commands.OptionSets[i]
}
w := &docWriter{
fileMap: make(map[string]*bytes.Buffer),
optionSetMap: optionSetMap,
allCommands: commands.CommandList,
globalFlagsMap: make(map[string]map[string]Option),
}
// sorted ascending by full name of command (activity complete, batch list, etc)
for _, cmd := range commands.CommandList {
if err := cmd.writeDoc(w); err != nil {
return nil, fmt.Errorf("failed writing docs for command %s: %w", cmd.FullName, err)
}
}
// Write global flags section once at the end of each file
w.writeGlobalFlagsSections()
// Format and return
var finalMap = make(map[string][]byte)
for key, buf := range w.fileMap {
finalMap[key] = buf.Bytes()
}
return finalMap, nil
}
type docWriter struct {
allCommands []Command
fileMap map[string]*bytes.Buffer
optionSetMap map[string]OptionSets
optionsStack [][]Option
globalFlagsMap map[string]map[string]Option // fileName -> optionName -> Option
}
func (c *Command) writeDoc(w *docWriter) error {
w.processOptions(c)
// If this is a root command, write a new file
depth := c.depth()
if depth == 1 {
w.writeCommand(c)
} else if depth > 1 {
w.writeSubcommand(c)
}
return nil
}
func (w *docWriter) writeCommand(c *Command) {
fileName := c.fileName()
w.fileMap[fileName] = &bytes.Buffer{}
w.fileMap[fileName].WriteString("---\n")
w.fileMap[fileName].WriteString("id: " + fileName + "\n")
w.fileMap[fileName].WriteString("title: Temporal CLI " + fileName + " command reference\n")
w.fileMap[fileName].WriteString("sidebar_label: " + fileName + "\n")
w.fileMap[fileName].WriteString("description: " + c.Docs.DescriptionHeader + "\n")
w.fileMap[fileName].WriteString("toc_max_heading_level: 4\n")
w.fileMap[fileName].WriteString("keywords:\n")
for _, keyword := range c.Docs.Keywords {
w.fileMap[fileName].WriteString(" - " + keyword + "\n")
}
w.fileMap[fileName].WriteString("tags:\n")
for _, tag := range c.Docs.Tags {
w.fileMap[fileName].WriteString(" - " + tag + "\n")
}
w.fileMap[fileName].WriteString("---")
w.fileMap[fileName].WriteString("\n\n")
w.fileMap[fileName].WriteString("{/* NOTE: This is an auto-generated file. Any edit to this file will be overwritten.\n")
w.fileMap[fileName].WriteString("This file is generated from https://github.com/temporalio/cli/blob/main/internal/commandsgen/commands.yml via internal/cmd/gen-docs */}\n\n")
// Add introductory paragraph
w.fileMap[fileName].WriteString(fmt.Sprintf("This page provides a reference for the `temporal` CLI `%s` command. ", fileName))
w.fileMap[fileName].WriteString("The flags applicable to each subcommand are presented in a table within the heading for the subcommand. ")
w.fileMap[fileName].WriteString("Refer to [Global Flags](#global-flags) for flags that you can use with every subcommand.\n\n")
}
func (w *docWriter) writeSubcommand(c *Command) {
fileName := c.fileName()
prefix := strings.Repeat("#", c.depth())
w.fileMap[fileName].WriteString(prefix + " " + c.leafName() + "\n\n")
w.fileMap[fileName].WriteString(escapeMDXDescription(c.Description) + "\n\n")
if w.isLeafCommand(c) {
// gather options from command and all options available from parent commands
var options = make([]Option, 0)
var globalOptions = make([]Option, 0)
for i, o := range w.optionsStack {
if i == len(w.optionsStack)-1 {
options = append(options, o...)
} else {
globalOptions = append(globalOptions, o...)
}
}
// alphabetize options
sort.Slice(options, func(i, j int) bool {
return options[i].Name < options[j].Name
})
// Write command-specific flags or global flags message
if len(options) > 0 {
w.fileMap[fileName].WriteString("Use the following options to change the behavior of this command. ")
w.fileMap[fileName].WriteString("You can also use any of the [global flags](#global-flags) that apply to all subcommands.\n\n")
w.writeOptionsTable(options, c)
} else {
w.fileMap[fileName].WriteString("Use [global flags](#global-flags) to customize the connection to the Temporal Service for this command.\n\n")
}
// Collect global flags for later (deduplicated)
w.collectGlobalFlags(fileName, globalOptions)
}
}
func (w *docWriter) writeOptionsTable(options []Option, c *Command) {
if len(options) == 0 {
return
}
fileName := c.fileName()
buf := w.fileMap[fileName]
// Command-specific flags: 3 columns (no Default)
buf.WriteString("| Flag | Required | Description |\n")
buf.WriteString("|------|----------|-------------|\n")
for _, o := range options {
w.writeOptionRow(buf, o, false)
}
buf.WriteString("\n")
}
func (w *docWriter) writeOptionRow(buf *bytes.Buffer, o Option, includeDefault bool) {
// Flag name column
flagName := fmt.Sprintf("`--%s`", o.Name)
if len(o.Short) > 0 {
flagName += fmt.Sprintf(", `-%s`", o.Short)
}
// Required column
required := "No"
if o.Required {
required = "Yes"
}
// Description column - starts with data type
optionType := o.Type
if o.DisplayType != "" {
optionType = o.DisplayType
}
description := fmt.Sprintf("**%s** %s", optionType, encodeJSONExample(o.Description))
if len(o.EnumValues) > 0 {
description += fmt.Sprintf(" Accepted values: %s.", strings.Join(o.EnumValues, ", "))
}
if o.Experimental {
description += " _(Experimental)_"
}
// Escape pipes in description for table compatibility
description = strings.ReplaceAll(description, "|", "\\|")
if includeDefault {
// Default column
defaultVal := ""
if len(o.Default) > 0 {
defaultVal = fmt.Sprintf("`%s`", o.Default)
}
buf.WriteString(fmt.Sprintf("| %s | %s | %s | %s |\n", flagName, required, description, defaultVal))
} else {
buf.WriteString(fmt.Sprintf("| %s | %s | %s |\n", flagName, required, description))
}
}
func (w *docWriter) collectGlobalFlags(fileName string, options []Option) {
if w.globalFlagsMap[fileName] == nil {
w.globalFlagsMap[fileName] = make(map[string]Option)
}
for _, o := range options {
// Only add if not already present (deduplication)
if _, exists := w.globalFlagsMap[fileName][o.Name]; !exists {
w.globalFlagsMap[fileName][o.Name] = o
}
}
}
func (w *docWriter) writeGlobalFlagsSections() {
for fileName, optionsMap := range w.globalFlagsMap {
if len(optionsMap) == 0 {
continue
}
// Convert map to slice and sort
options := make([]Option, 0, len(optionsMap))
for _, o := range optionsMap {
options = append(options, o)
}
sort.Slice(options, func(i, j int) bool {
return options[i].Name < options[j].Name
})
buf := w.fileMap[fileName]
buf.WriteString("## Global Flags\n\n")
buf.WriteString("The following options can be used with any command.\n\n")
// Global flags: 4 columns (with Default)
buf.WriteString("| Flag | Required | Description | Default |\n")
buf.WriteString("|------|----------|-------------|--------|\n")
for _, o := range options {
w.writeOptionRow(buf, o, true)
}
buf.WriteString("\n")
}
}
func (w *docWriter) processOptions(c *Command) {
// Pop options from stack if we are moving up a level
if len(w.optionsStack) >= len(strings.Split(c.FullName, " ")) {
w.optionsStack = w.optionsStack[:len(w.optionsStack)-1]
}
var options []Option
options = append(options, c.Options...)
// Maintain stack of options available from parent commands
for _, set := range c.OptionSets {
optionSet, ok := w.optionSetMap[set]
if !ok {
panic(fmt.Sprintf("invalid option set %v used", set))
}
optionSetOptions := optionSet.Options
options = append(options, optionSetOptions...)
}
w.optionsStack = append(w.optionsStack, options)
}
func (w *docWriter) isLeafCommand(c *Command) bool {
for _, maybeSubCmd := range w.allCommands {
if maybeSubCmd.isSubCommand(c) {
return false
}
}
return true
}
// encodeJSONExample wraps single-quoted JSON examples in backticks so MDX
// does not parse curly braces as JSX expressions. This handles option
// description table cells. See also escapeMDXDescription which handles
// the same class of issues for command description body text.
func encodeJSONExample(v string) string {
re := regexp.MustCompile(`('[^']*\{[^']*\}[^']*')`)
v = re.ReplaceAllString(v, "`$1`")
return v
}
var (
reAngleBracketPlaceholder = regexp.MustCompile(`<([a-z][a-z0-9_:-]+)>`)
reHeadingID = regexp.MustCompile(`^(#{1,6}\s+.+?)\s+\{#([\w-]+)\}\s*$`)
reJSONInSingleQuotes = regexp.MustCompile(`'([^']*\{[^']*\}[^']*)'`)
)
// escapeMDXDescription escapes patterns in command descriptions that are
// valid Markdown but break MDX compilation: heading IDs ({#id}), bare
// angle-bracket placeholders (<name>), and curly braces in JSON examples.
// Code fences are left untouched. Inline backtick spans are also preserved,
// assuming balanced backticks. See also encodeJSONExample which handles
// the same class of issues for option description table cells.
func escapeMDXDescription(desc string) string {
lines := strings.Split(desc, "\n")
var result []string
inCodeBlock := false
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "```") {
inCodeBlock = !inCodeBlock
result = append(result, line)
continue
}
if inCodeBlock {
result = append(result, line)
continue
}
// Convert {#custom-id} to MDX-compatible {/* #custom-id */} comment syntax.
line = reHeadingID.ReplaceAllString(line, "$1 {/* #$2 */}")
// Escape <placeholder> patterns that MDX would parse as HTML tags.
// Split on backtick spans to avoid modifying inline code.
parts := strings.Split(line, "`")
for i := range parts {
if i%2 == 0 { // outside backticks
parts[i] = reAngleBracketPlaceholder.ReplaceAllString(parts[i], `\<$1\>`)
}
}
line = strings.Join(parts, "`")
// Escape curly braces inside single-quoted JSON examples.
line = reJSONInSingleQuotes.ReplaceAllStringFunc(line, func(match string) string {
return strings.NewReplacer("{", `\{`, "}", `\}`).Replace(match)
})
result = append(result, line)
}
return strings.Join(result, "\n")
}