Added default value flag - for printing out a value when reading and there are no matches

This commit is contained in:
Mike Farah 2020-02-03 10:13:48 +11:00
parent f52de57652
commit 699fce9da4
4 changed files with 19 additions and 0 deletions

View File

@ -356,6 +356,20 @@ func TestReadEmptyContentCmd(t *testing.T) {
test.AssertResult(t, expectedOutput, result.Output)
}
func TestReadEmptyContentWithDefaultValueCmd(t *testing.T) {
content := ``
filename := test.WriteTempYamlFile(content)
defer test.RemoveTempYamlFile(filename)
cmd := getRootCommand()
result := test.RunCmd(cmd, fmt.Sprintf("read --defaultValue things %s", filename))
if result.Error != nil {
t.Error(result.Error)
}
expectedOutput := `things`
test.AssertResult(t, expectedOutput, result.Output)
}
func TestReadPrettyPrintCmd(t *testing.T) {
cmd := getRootCommand()
result := test.RunCmd(cmd, "read -P ../examples/sample.json")

View File

@ -11,6 +11,7 @@ var writeInplace = false
var writeScript = ""
var outputToJSON = false
var prettyPrint = false
var defaultValue = ""
var overwriteFlag = false
var autoCreateFlag = true
var allowEmptyFlag = false

View File

@ -26,6 +26,7 @@ yq r -- things.yaml '--key-starting-with-dashes.blah'
cmdRead.PersistentFlags().StringVarP(&docIndex, "doc", "d", "0", "process document index number (0 based, * for all documents)")
cmdRead.PersistentFlags().StringVarP(&printMode, "printMode", "p", "v", "print mode (v (values, default), p (paths), pv (path and value pairs)")
cmdRead.PersistentFlags().BoolVarP(&prettyPrint, "prettyPrint", "P", false, "pretty print (does not have an affect with json output)")
cmdRead.PersistentFlags().StringVarP(&defaultValue, "defaultValue", "D", "", "default value printed when there are no results")
return cmdRead
}

View File

@ -104,6 +104,9 @@ func updateStyleOfNode(node *yaml.Node, style yaml.Style) {
func printResults(matchingNodes []*yqlib.NodeContext, cmd *cobra.Command) error {
if len(matchingNodes) == 0 {
log.Debug("no matching results, nothing to print")
if defaultValue != "" {
cmd.Print(defaultValue)
}
return nil
}