Skip to content

Commit

Permalink
feat: add format and lint for JSONNet files
Browse files Browse the repository at this point in the history
This patch adds two commands `kratos jsonnet format` and `kratos jsonnet lint` that help with formatting and linting JSONNet code.
  • Loading branch information
aeneasr committed May 5, 2020
1 parent 2b45e79 commit 0a1b244
Show file tree
Hide file tree
Showing 4 changed files with 156 additions and 1 deletion.
40 changes: 40 additions & 0 deletions cmd/jsonnet.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package cmd

import (
"github.com/spf13/cobra"
)

const globHelp = `Glob Syntax:
pattern:
{ term }
term:
'*' matches any sequence of non-separator characters
'**' matches any sequence of characters
'?' matches any single non-separator character
'[' [ '!' ] { character-range } ']'
character class (must be non-empty)
'{' pattern-list '}'
pattern alternatives
c matches character c (c != '*', '**', '?', '\', '[', '{', '}')
'\' c matches character c
character-range:
c matches character c (c != '\\', '-', ']')
'\' c matches character c
lo '-' hi matches character c for lo <= c <= hi
pattern-list:
pattern { ',' pattern }
comma-separated (without spaces) patterns`

// jsonnetCmd represents the jsonnet command
var jsonnetCmd = &cobra.Command{
Use: "jsonnet",
Short: "Helpers for linting and formatting JSONNet code",
}

func init() {
rootCmd.AddCommand(jsonnetCmd)
}
66 changes: 66 additions & 0 deletions cmd/jsonnet_format.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
Copyright © 2020 NAME HERE <EMAIL ADDRESS>
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 cmd

import (
"fmt"
"io/ioutil"
"path/filepath"

"github.com/google/go-jsonnet/formatter"
"github.com/spf13/cobra"

"github.com/ory/x/cmdx"
"github.com/ory/x/flagx"
)

// jsonnetFormatCmd represents the format command
var jsonnetFormatCmd = &cobra.Command{
Use: "format path/to/files/*.jsonnet [more/files.jsonnet, [supports/**/{foo,bar}.jsonnet]]",
Long: `Formats JSONNet files using the official JSONNet formatter.
Use -w or --write to write output back to files instead of stdout.
` + globHelp,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
for _, pattern := range args {
files, err := filepath.Glob(pattern)
cmdx.Must(err, `Glob path "%s" is not valid: %s`, pattern, err)

shouldWrite := flagx.MustGetBool(cmd, "write")
for _, file := range files {
content, err := ioutil.ReadFile(file)
cmdx.Must(err, `Unable to read file "%s" because: %s`, file, err)

output, err := formatter.Format(file, string(content), formatter.DefaultOptions())
cmdx.Must(err, `JSONNet file "%s" could not be formatted: %s`, file, err)

if shouldWrite {
err := ioutil.WriteFile(file, []byte(output), 0644)
cmdx.Must(err, `Could not write to file "%s" because: %s`, file, err)
} else {
fmt.Println(output)
}
}
}
},
}

func init() {
jsonnetCmd.AddCommand(jsonnetFormatCmd)
jsonnetFormatCmd.Flags().BoolP("write", "w", false, "Write formatted output back to file.")
}
48 changes: 48 additions & 0 deletions cmd/jsonnet_lint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package cmd

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"

"github.com/google/go-jsonnet"
"github.com/google/go-jsonnet/linter"
"github.com/spf13/cobra"

"github.com/ory/x/cmdx"
)

// jsonnetLintCmd represents the lint command
var jsonnetLintCmd = &cobra.Command{
Use: "lint path/to/files/*.jsonnet [more/files.jsonnet, [supports/**/{foo,bar}.jsonnet]]",
Long: `Lints JSONNet files using the official JSONNet linter and exits with a status code of 1 when issues are detected.
` + globHelp,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
for _, pattern := range args {
files, err := filepath.Glob(pattern)
cmdx.Must(err, `Glob path "%s" is not valid: %s`, pattern, err)

for _, file := range files {
content, err := ioutil.ReadFile(file)
cmdx.Must(err, `Unable to read file "%s" because: %s`, file, err)

node, err := jsonnet.SnippetToAST(file, string(content))
cmdx.Must(err, `Unable to parse JSONNet source "%s" because: %s`, file, err)

ew := &linter.ErrorWriter{Writer: os.Stderr}
linter.Lint(node, ew)
if ew.ErrorsFound {
_, _ = fmt.Fprintf(os.Stderr, "Linter found issues.")
os.Exit(1)
}
}
}
},
}

func init() {
jsonnetCmd.AddCommand(jsonnetLintCmd)
}
3 changes: 2 additions & 1 deletion cmd/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (

_ "github.com/mikefarah/yq"

_ "github.com/ory/sdk/swagutil"
_ "github.com/davidrjonas/semver-cli"

_ "github.com/ory/sdk/swagutil"
)

0 comments on commit 0a1b244

Please sign in to comment.