@@ -17,6 +17,7 @@ package cobra2snooty
17
17
import (
18
18
"bytes"
19
19
"fmt"
20
+ "regexp"
20
21
"strings"
21
22
"text/tabwriter"
22
23
@@ -26,6 +27,12 @@ import (
26
27
const (
27
28
outputHeader = `Output
28
29
------
30
+ `
31
+ outputDescription = `
32
+ If the command succeeds, the CLI returns output similar to the following sample. Values in brackets represent your values.
33
+
34
+ .. code-block::
35
+
29
36
`
30
37
)
31
38
@@ -36,14 +43,18 @@ const (
36
43
tabwriterPadChar = ' '
37
44
)
38
45
46
+ // regex for one or more characters except right curly bracket '}'.
47
+ const charsExceptRightCurlyBracket = "[^}]+"
48
+
39
49
// This function can return the output for all commands when the output template is added as an annotation in the command file
40
50
41
51
func printOutputCreate (buf * bytes.Buffer , cmd * cobra.Command ) {
42
52
if cmd .Annotations ["output" ] == "" {
43
53
return
44
54
}
45
55
46
- output := strings .ReplaceAll (cmd .Annotations ["output" ], "{{range .Results}}" , "" )
56
+ output := removeRange (cmd .Annotations ["output" ])
57
+ output = replaceWithValueOrDefault (output )
47
58
output = strings .ReplaceAll (output , "{{end}}" , "" )
48
59
output = strings .ReplaceAll (output , "{{." , "<" )
49
60
output = strings .ReplaceAll (output , "}}" , ">" )
@@ -54,13 +65,24 @@ func printOutputCreate(buf *bytes.Buffer, cmd *cobra.Command) {
54
65
w .Init (buf , tabwriterMinWidth , tabwriterWidth , tabwriterPadding , tabwriterPadChar , 0 )
55
66
56
67
buf .WriteString (outputHeader )
57
- buf .WriteString (`
58
- If the command succeeds, the CLI returns output similar to the following sample. Values in brackets represent your values.
59
-
60
- .. code-block::
61
-
62
- ` )
68
+ buf .WriteString (outputDescription )
63
69
fmt .Fprintln (w , " " + output )
64
70
w .Flush ()
65
71
buf .WriteString ("\n " )
66
72
}
73
+
74
+ func removeRange (text string ) string {
75
+ // remove {{range}} control structure. Examples: {{range .}}, {{range .Results}}
76
+ re := `{{range ` + charsExceptRightCurlyBracket + `}}`
77
+ return regexp .MustCompile (re ).ReplaceAllString (text , "" )
78
+ }
79
+
80
+ func replaceWithValueOrDefault (text string ) string {
81
+ // replaces {{if .field}}{{.field}}{{else}}defaultValue{{end}} with {{.field}}
82
+ re := `{{if` + charsExceptRightCurlyBracket + `}}` +
83
+ `({{` + charsExceptRightCurlyBracket + `}})` +
84
+ `{{else}}` + charsExceptRightCurlyBracket + `{{end}}`
85
+
86
+ // $1 is the first group (surrounded by round brackets in the regex expression)
87
+ return regexp .MustCompile (re ).ReplaceAllString (text , "$1" )
88
+ }
0 commit comments