...

Source file src/github.com/ory/x/jsonnetx/lint.go

Documentation: github.com/ory/x/jsonnetx

     1  package jsonnetx
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  
     8  	"github.com/bmatcuk/doublestar/v2"
     9  	"github.com/google/go-jsonnet"
    10  	"github.com/google/go-jsonnet/linter"
    11  	"github.com/spf13/cobra"
    12  
    13  	"github.com/ory/x/flagx"
    14  
    15  	"github.com/ory/x/cmdx"
    16  )
    17  
    18  // LintCommand represents the lint command
    19  var LintCommand = &cobra.Command{
    20  	Use: "lint path/to/files/*.jsonnet [more/files.jsonnet, [supports/**/{foo,bar}.jsonnet]]",
    21  	Long: `Lints JSONNet files using the official JSONNet linter and exits with a status code of 1 when issues are detected.
    22  
    23  ` + GlobHelp,
    24  	Args: cobra.MinimumNArgs(1),
    25  	Run: func(cmd *cobra.Command, args []string) {
    26  		verbose := flagx.MustGetBool(cmd, "verbose")
    27  		for _, pattern := range args {
    28  			files, err := doublestar.Glob(pattern)
    29  			cmdx.Must(err, `Glob path "%s" is not valid: %s`, pattern, err)
    30  
    31  			for _, file := range files {
    32  				if fi, err := os.Stat(file); err != nil {
    33  					cmdx.Must(err, "Unable to stat file %s: %s", file, err)
    34  				} else if fi.IsDir() {
    35  					continue
    36  				}
    37  
    38  				if verbose {
    39  					fmt.Printf("Processing file: %s\n", file)
    40  				}
    41  
    42  				content, err := ioutil.ReadFile(file)
    43  				cmdx.Must(err, `Unable to read file "%s" because: %s`, file, err)
    44  
    45  				node, err := jsonnet.SnippetToAST(file, string(content))
    46  				cmdx.Must(err, `Unable to parse JSONNet source "%s" because: %s`, file, err)
    47  
    48  				ew := &linter.ErrorWriter{Writer: os.Stderr}
    49  				linter.Lint(node, ew)
    50  				if ew.ErrorsFound {
    51  					_, _ = fmt.Fprintf(os.Stderr, "Linter found issues.")
    52  					os.Exit(1)
    53  				}
    54  			}
    55  		}
    56  	},
    57  }
    58  
    59  func init() {
    60  	LintCommand.Flags().Bool("verbose", false, "Verbose output.")
    61  }
    62  

View as plain text