From 6f0a329331f953e74fff813e3e917ae719ae7f83 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Wed, 15 Apr 2020 11:48:11 +1000 Subject: [PATCH] Fixed inplace errors clearing out original file --- cmd/commands_test.go | 16 ++++++++++++++++ cmd/utils.go | 9 +++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/cmd/commands_test.go b/cmd/commands_test.go index 00f27267..baa723cd 100644 --- a/cmd/commands_test.go +++ b/cmd/commands_test.go @@ -1927,6 +1927,22 @@ func TestWriteCmd_Inplace(t *testing.T) { test.AssertResult(t, expectedOutput, strings.Trim(gotOutput, "\n ")) } +func TestWriteCmd_InplaceError(t *testing.T) { + content := `b: cat + c: 3 +` + filename := test.WriteTempYamlFile(content) + defer test.RemoveTempYamlFile(filename) + + cmd := getRootCommand() + result := test.RunCmd(cmd, fmt.Sprintf("write -i %s b.c 7", filename)) + if result.Error == nil { + t.Error("Expected Error to occur!") + } + gotOutput := test.ReadTempYamlFile(filename) + test.AssertResult(t, content, gotOutput) +} + func TestWriteCmd_Append(t *testing.T) { content := `b: - foo diff --git a/cmd/utils.go b/cmd/utils.go index 658657a3..29b56b89 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -351,6 +351,7 @@ func updateDoc(inputFile string, updateCommands []yqlib.UpdateCommand, writer io func readAndUpdate(stdOut io.Writer, inputFile string, updateData updateDataFn) error { var destination io.Writer var destinationName string + var completedSuccessfully = false if writeInplace { info, err := os.Stat(inputFile) if err != nil { @@ -368,7 +369,9 @@ func readAndUpdate(stdOut io.Writer, inputFile string, updateData updateDataFn) destination = tempFile defer func() { safelyCloseFile(tempFile) - safelyRenameFile(tempFile.Name(), inputFile) + if completedSuccessfully { + safelyRenameFile(tempFile.Name(), inputFile) + } }() } else { destination = stdOut @@ -387,7 +390,9 @@ func readAndUpdate(stdOut io.Writer, inputFile string, updateData updateDataFn) encoder = yqlib.NewYamlEncoder(bufferedWriter, indent, colorsEnabled) } - return readStream(inputFile, mapYamlDecoder(updateData, encoder)) + var errorProcessing = readStream(inputFile, mapYamlDecoder(updateData, encoder)) + completedSuccessfully = errorProcessing == nil + return errorProcessing } type updateCommandParsed struct {