Add lint command for basic linting

This commit is contained in:
Thad Craft 2019-10-04 10:59:06 -04:00
parent 7a6689eb40
commit f0bfde0b35
No known key found for this signature in database
GPG Key ID: DE50A1E7BB35F37E
3 changed files with 77 additions and 1 deletions

View File

@ -600,7 +600,7 @@ b:
func TestDeleteYamlArray(t *testing.T) {
content := `- 1
- 2
- 3
- 3
`
filename := writeTempYamlFile(content)
defer removeTempYamlFile(filename)
@ -862,3 +862,39 @@ c:
test: 1`
assertResult(t, expectedOutput, strings.Trim(gotOutput, "\n "))
}
func TestLintCmd_OK(t *testing.T) {
filename := writeTempYamlFile(readTempYamlFile("examples/data1.yaml"))
defer removeTempYamlFile(filename)
cmd := getRootCommand()
result := runCmd(cmd, fmt.Sprintf("lint %s", filename))
if result.Error != nil {
t.Error(result.Error)
}
assertResult(t, nil, result.Error)
}
func TestLintCmd_Failed(t *testing.T) {
filename := writeTempYamlFile(readTempYamlFile("examples/invalid.yaml"))
defer removeTempYamlFile(filename)
cmd := getRootCommand()
result := runCmd(cmd, fmt.Sprintf("lint %s", filename))
assertResult(t, "Failed lint", result.Error.Error())
}
func TestLintCmd_NoPath(t *testing.T) {
filename := writeTempYamlFile(readTempYamlFile("examples/invalid.yaml"))
defer removeTempYamlFile(filename)
cmd := getRootCommand()
result := runCmd(cmd, fmt.Sprint("lint"))
assertResult(t, "Must provide filename", result.Error.Error())
}
func TestLintCmd_FileNotFound(t *testing.T) {
cmd := getRootCommand()
result := runCmd(cmd, fmt.Sprint("lint not_found.yaml"))
assertResult(t, "open not_found.yaml: no such file or directory", result.Error.Error())
}

4
examples/invalid.yaml Normal file
View File

@ -0,0 +1,4 @@
a:
b:
c
d:

36
yq.go
View File

@ -76,6 +76,7 @@ func newCommandCLI() *cobra.Command {
createDeleteCmd(),
createNewCmd(),
createMergeCmd(),
createLintCmd(),
)
rootCmd.SetOutput(os.Stdout)
@ -210,6 +211,41 @@ Note that if you set both flags only overwrite will take effect.
return cmdMerge
}
func createLintCmd() *cobra.Command {
var cmdLint = &cobra.Command{
Use: "lint [yaml_file]",
Aliases: []string{"l"},
Short: "yq l sample.yaml",
Example: `
yq lint sample.yaml
yq l sample.yaml
`,
Long: "Does a basic lint on the file to see if it can be parsed",
RunE: lint,
}
return cmdLint
}
func lint(cmd *cobra.Command, args []string) error {
var path = ""
if len(args) < 1 {
return errors.New("Must provide filename")
} else if len(args) >= 1 {
path = args[0]
}
obj := make(map[string]interface{})
bytes, err := ioutil.ReadFile(path)
if err != nil {
return err
}
err = yaml.Unmarshal(bytes, &obj)
if err != nil {
return errors.New("Failed lint")
}
fmt.Println("ok")
return nil
}
func readProperty(cmd *cobra.Command, args []string) error {
var path = ""