diff --git a/commands_test.go b/commands_test.go index 6bbc8bce..ee52333d 100644 --- a/commands_test.go +++ b/commands_test.go @@ -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()) +} diff --git a/examples/invalid.yaml b/examples/invalid.yaml new file mode 100644 index 00000000..339fe7a7 --- /dev/null +++ b/examples/invalid.yaml @@ -0,0 +1,4 @@ +a: + b: + c + d: diff --git a/yq.go b/yq.go index b21bb01d..473c70dc 100644 --- a/yq.go +++ b/yq.go @@ -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 = ""