From d473c39a44094da9c87e52c2385b9dc5211e8d50 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Wed, 10 Jun 2020 16:54:08 +1000 Subject: [PATCH] Added exit flag --- cmd/constant.go | 1 + cmd/read.go | 6 ++++++ cmd/read_test.go | 18 ++++++++++++++++++ yq.go | 3 --- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/cmd/constant.go b/cmd/constant.go index 4a61890..b148f12 100644 --- a/cmd/constant.go +++ b/cmd/constant.go @@ -16,6 +16,7 @@ var writeInplace = false var writeScript = "" var sourceYamlFile = "" var outputToJSON = false +var exitStatus = false var prettyPrint = false var explodeAnchors = false var colorsEnabled = false diff --git a/cmd/read.go b/cmd/read.go index 48e4034..64e8902 100644 --- a/cmd/read.go +++ b/cmd/read.go @@ -31,6 +31,7 @@ yq r -- things.yaml '--key-starting-with-dashes.blah' cmdRead.PersistentFlags().BoolVarP(&unwrapScalar, "unwrapScalar", "", true, "unwrap scalar, print the value with no quotes, colors or comments") cmdRead.PersistentFlags().BoolVarP(&stripComments, "stripComments", "", false, "print yaml without any comments") cmdRead.PersistentFlags().BoolVarP(&explodeAnchors, "explodeAnchors", "X", false, "explode anchors") + cmdRead.PersistentFlags().BoolVarP(&exitStatus, "exitStatus", "e", false, "set exit status if no matches are found") return cmdRead } @@ -50,6 +51,11 @@ func readProperty(cmd *cobra.Command, args []string) error { matchingNodes, errorReadingStream := readYamlFile(args[0], path, updateAll, docIndexInt) + if exitStatus { + cmd.SilenceUsage = true + return errors.New("No matches found") + } + if errorReadingStream != nil { return errorReadingStream } diff --git a/cmd/read_test.go b/cmd/read_test.go index 57ae7bc..1906bfd 100644 --- a/cmd/read_test.go +++ b/cmd/read_test.go @@ -882,6 +882,24 @@ b: test.AssertResult(t, expectedOutput, result.Output) } +func TestReadNotFoundWithExitStatus(t *testing.T) { + cmd := getRootCommand() + result := test.RunCmd(cmd, "read ../examples/sample.yaml adsf -e") + if result.Error == nil { + t.Error("Expected command to fail") + } + expectedOutput := `No matches found` + test.AssertResult(t, expectedOutput, result.Error.Error()) +} + +func TestReadNotFoundWithoutExitStatus(t *testing.T) { + cmd := getRootCommand() + result := test.RunCmd(cmd, "read ../examples/sample.yaml adsf") + if result.Error != nil { + t.Error("Expected command to succeed!") + } +} + func TestReadPrettyPrintWithIndentCmd(t *testing.T) { cmd := getRootCommand() result := test.RunCmd(cmd, "read -P -I4 ../examples/sample.json") diff --git a/yq.go b/yq.go index fcfe4e5..b409fab 100644 --- a/yq.go +++ b/yq.go @@ -4,14 +4,11 @@ import ( "os" command "github.com/mikefarah/yq/v3/cmd" - logging "gopkg.in/op/go-logging.v1" ) func main() { cmd := command.New() - log := logging.MustGetLogger("yq") if err := cmd.Execute(); err != nil { - log.Error(err.Error()) os.Exit(1) } }