Skip to content

Commit

Permalink
add support {{if}} control struct for output templates (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
tibulca authored Nov 16, 2023
1 parent 4fc7578 commit 33b6a70
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 7 deletions.
36 changes: 29 additions & 7 deletions output.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package cobra2snooty
import (
"bytes"
"fmt"
"regexp"
"strings"
"text/tabwriter"

Expand All @@ -26,6 +27,12 @@ import (
const (
outputHeader = `Output
------
`
outputDescription = `
If the command succeeds, the CLI returns output similar to the following sample. Values in brackets represent your values.
.. code-block::
`
)

Expand All @@ -36,14 +43,18 @@ const (
tabwriterPadChar = ' '
)

// regex for one or more characters except right curly bracket '}'.
const charsExceptRightCurlyBracket = "[^}]+"

// This function can return the output for all commands when the output template is added as an annotation in the command file

func printOutputCreate(buf *bytes.Buffer, cmd *cobra.Command) {
if cmd.Annotations["output"] == "" {
return
}

output := strings.ReplaceAll(cmd.Annotations["output"], "{{range .Results}}", "")
output := removeRange(cmd.Annotations["output"])
output = replaceWithValueOrDefault(output)
output = strings.ReplaceAll(output, "{{end}}", "")
output = strings.ReplaceAll(output, "{{.", "<")
output = strings.ReplaceAll(output, "}}", ">")
Expand All @@ -54,13 +65,24 @@ func printOutputCreate(buf *bytes.Buffer, cmd *cobra.Command) {
w.Init(buf, tabwriterMinWidth, tabwriterWidth, tabwriterPadding, tabwriterPadChar, 0)

buf.WriteString(outputHeader)
buf.WriteString(`
If the command succeeds, the CLI returns output similar to the following sample. Values in brackets represent your values.
.. code-block::
`)
buf.WriteString(outputDescription)
fmt.Fprintln(w, " "+output)
w.Flush()
buf.WriteString("\n")
}

func removeRange(text string) string {
// remove {{range}} control structure. Examples: {{range .}}, {{range .Results}}
re := `{{range ` + charsExceptRightCurlyBracket + `}}`
return regexp.MustCompile(re).ReplaceAllString(text, "")
}

func replaceWithValueOrDefault(text string) string {
// replaces {{if .field}}{{.field}}{{else}}defaultValue{{end}} with {{.field}}
re := `{{if` + charsExceptRightCurlyBracket + `}}` +
`({{` + charsExceptRightCurlyBracket + `}})` +
`{{else}}` + charsExceptRightCurlyBracket + `{{end}}`

// $1 is the first group (surrounded by round brackets in the regex expression)
return regexp.MustCompile(re).ReplaceAllString(text, "$1")
}
51 changes: 51 additions & 0 deletions output_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2023 MongoDB Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cobra2snooty

import (
"bytes"
"testing"

"github.com/spf13/cobra"
)

func TestPrintOutputCreate(t *testing.T) {
t.Run("replaceWithValueOrDefault", func(t *testing.T) {
outputTemplate := `ID NAME DATABASE COLLECTION TYPE
{{range .}}{{.IndexID}} %s {{.Database}} {{.CollectionName}} {{if .Type }}{{.Type}}{{else}}defaultValue{{end}}
{{end}}`

expected := outputHeader + outputDescription +
` ID NAME DATABASE COLLECTION TYPE
<IndexID> <Name> <Database> <CollectionName> <Type>
`

cmd := &cobra.Command{
Annotations: map[string]string{
"output": outputTemplate,
},
}

buf := new(bytes.Buffer)
printOutputCreate(buf, cmd)
result := buf.String()

if result != expected {
t.Errorf("expected:\n[%s]\ngot:\n[%s]\n", expected, result)
}
})
}

0 comments on commit 33b6a70

Please sign in to comment.