From 699fce9da43f674afeebd5ea162a17fecd60ba4d Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Mon, 3 Feb 2020 10:13:48 +1100 Subject: [PATCH] Added default value flag - for printing out a value when reading and there are no matches --- cmd/commands_test.go | 14 ++++++++++++++ cmd/constant.go | 1 + cmd/read.go | 1 + cmd/utils.go | 3 +++ 4 files changed, 19 insertions(+) diff --git a/cmd/commands_test.go b/cmd/commands_test.go index 7be6ebf4..f74d677e 100644 --- a/cmd/commands_test.go +++ b/cmd/commands_test.go @@ -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") diff --git a/cmd/constant.go b/cmd/constant.go index 476987d7..49043371 100644 --- a/cmd/constant.go +++ b/cmd/constant.go @@ -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 diff --git a/cmd/read.go b/cmd/read.go index 4c22937e..f8a392e6 100644 --- a/cmd/read.go +++ b/cmd/read.go @@ -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 } diff --git a/cmd/utils.go b/cmd/utils.go index aa6de02f..878f0dee 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -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 }