Skip to content

Commit

Permalink
Merge pull request #62 from cerberauth/add-yaml-output-support
Browse files Browse the repository at this point in the history
feat: add support for yaml output
  • Loading branch information
emmanuelgautier authored Nov 5, 2023
2 parents c23de22 + 706e1c6 commit 6398d78
Showing 1 changed file with 42 additions and 8 deletions.
50 changes: 42 additions & 8 deletions cmd/generate/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/getkin/kin-openapi/openapi3"
"github.com/ory/oathkeeper/rule"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)

var (
Expand All @@ -24,8 +25,35 @@ var (
outputpath string
upstreamUrl string
serverUrls []string

jsonOutput bool
yamlOutput bool
)

func encodeJSON(rules []rule.Rule) (*bytes.Buffer, error) {
outputBuf := new(bytes.Buffer)
enc := json.NewEncoder(outputBuf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")

if encodeErr := enc.Encode(rules); encodeErr != nil {
return nil, encodeErr
}

return outputBuf, nil
}

func encodeYAML(rules []rule.Rule) (*bytes.Buffer, error) {
outputBuf := new(bytes.Buffer)
enc := yaml.NewEncoder(outputBuf)

if encodeErr := enc.Encode(rules); encodeErr != nil {
return nil, encodeErr
}

return outputBuf, nil
}

func NewGenerateCmd() (generateCmd *cobra.Command) {
generateCmd = &cobra.Command{
Use: "generate",
Expand Down Expand Up @@ -83,24 +111,30 @@ func NewGenerateCmd() (generateCmd *cobra.Command) {
log.Fatal(err)
}

jsonBuf := new(bytes.Buffer)
enc := json.NewEncoder(jsonBuf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
var outputBuf *bytes.Buffer
var encodeErr error
if yamlOutput && !jsonOutput {
outputBuf, encodeErr = encodeYAML(rules)
} else {
outputBuf, encodeErr = encodeJSON(rules)
}

if encodeErr := enc.Encode(rules); encodeErr != nil {
log.Fatal(encodeErr)
if encodeErr != nil {
log.Fatal(err)
}

if outputpath != "" {
os.WriteFile(outputpath, jsonBuf.Bytes(), 0644)
os.WriteFile(outputpath, outputBuf.Bytes(), 0644)
return
}

os.Stdout.Write(jsonBuf.Bytes())
os.Stdout.Write(outputBuf.Bytes())
},
}

generateCmd.PersistentFlags().BoolVarP(&jsonOutput, "json", "", false, "Use JSON as output format")
generateCmd.PersistentFlags().BoolVarP(&yamlOutput, "yaml", "", false, "Use YAML as output format")

generateCmd.PersistentFlags().StringVarP(&configFilePath, "config", "c", "", "Path to one .yaml, .yml, config file.")
generateCmd.PersistentFlags().StringVarP(&fileurl, "url", "u", "", "OpenAPI URL")
generateCmd.PersistentFlags().StringVarP(&filepath, "file", "f", "", "OpenAPI File Path")
Expand Down

0 comments on commit 6398d78

Please sign in to comment.