Added validate command

This commit is contained in:
Mike Farah 2020-01-30 16:34:43 +11:00
parent 6ec8386f9e
commit d1c1ab0a75
3 changed files with 62 additions and 1 deletions

View File

@ -94,6 +94,15 @@ func TestReadCmd(t *testing.T) {
test.AssertResult(t, "2", result.Output)
}
func TestValidateCmd(t *testing.T) {
cmd := getRootCommand()
result := test.RunCmd(cmd, "validate ../examples/sample.yaml b.c")
if result.Error != nil {
t.Error(result.Error)
}
test.AssertResult(t, "", result.Output)
}
func TestReadWithAdvancedFilterCmd(t *testing.T) {
cmd := getRootCommand()
result := test.RunCmd(cmd, "read -v ../examples/sample.yaml b.e(name==sam).value")
@ -547,7 +556,21 @@ func TestReadBadDataCmd(t *testing.T) {
cmd := getRootCommand()
result := test.RunCmd(cmd, fmt.Sprintf("read %s", filename))
if result.Error == nil {
t.Error("Expected command to fail due to invalid path")
t.Error("Expected command to fail")
}
expectedOutput := `yaml: line 1: did not find expected ',' or ']'`
test.AssertResult(t, expectedOutput, result.Error.Error())
}
func TestValidateBadDataCmd(t *testing.T) {
content := `[!Whatever]`
filename := test.WriteTempYamlFile(content)
defer test.RemoveTempYamlFile(filename)
cmd := getRootCommand()
result := test.RunCmd(cmd, fmt.Sprintf("validate %s", filename))
if result.Error == nil {
t.Error("Expected command to fail")
}
expectedOutput := `yaml: line 1: did not find expected ',' or ']'`
test.AssertResult(t, expectedOutput, result.Error.Error())

View File

@ -44,6 +44,7 @@ func New() *cobra.Command {
rootCmd.AddCommand(
createReadCmd(),
createValidateCmd(),
createWriteCmd(),
createPrefixCmd(),
createDeleteCmd(),

37
cmd/validate.go Normal file
View File

@ -0,0 +1,37 @@
package cmd
import (
errors "github.com/pkg/errors"
"github.com/spf13/cobra"
)
func createValidateCmd() *cobra.Command {
var cmdRead = &cobra.Command{
Use: "validate [yaml_file]",
Aliases: []string{"v"},
Short: "yq v sample.yaml",
Example: `
yq v - # reads from stdin
`,
RunE: validateProperty,
SilenceUsage: true,
SilenceErrors: true,
}
cmdRead.PersistentFlags().StringVarP(&docIndex, "doc", "d", "0", "process document index number (0 based, * for all documents)")
return cmdRead
}
func validateProperty(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("Must provide filename")
}
var updateAll, docIndexInt, errorParsingDocIndex = parseDocumentIndex()
if errorParsingDocIndex != nil {
return errorParsingDocIndex
}
_, errorReadingStream := readYamlFile(args[0], "", updateAll, docIndexInt)
return errorReadingStream
}