This commit is contained in:
Mike Farah 2022-01-14 15:22:55 +11:00
parent 84ddf1862f
commit 78b45a3eb0
4 changed files with 12 additions and 14 deletions

View File

@ -1,30 +1,28 @@
package yqlib
import (
"fmt"
"io"
"io/ioutil"
"os"
)
func safelyRenameFile(from string, to string) {
func tryRenameFile(from string, to string) {
if renameError := os.Rename(from, to); renameError != nil {
log.Debugf("Error renaming from %v to %v, attempting to copy contents", from, to)
log.Debug(renameError.Error())
log.Debug("going to try copying instead")
// can't do this rename when running in docker to a file targeted in a mounted volume,
// so gracefully degrade to copying the entire contents.
if copyError := copyFileContents(from, to); copyError != nil {
log.Errorf("Failed copying from %v to %v", from, to)
log.Error(copyError.Error())
panic(fmt.Errorf("failed copying from %v to %v: %w", from, to, copyError))
} else {
removeErr := os.Remove(from)
if removeErr != nil {
log.Errorf("failed removing original file: %s", from)
}
tryRemoveTempFile(from)
}
}
}
func tryRemoveFile(filename string) {
func tryRemoveTempFile(filename string) {
log.Debug("Removing temp file: %v", filename)
removeErr := os.Remove(filename)
if removeErr != nil {

View File

@ -33,7 +33,7 @@ func (f *frontMatterHandlerImpl) GetContentReader() io.Reader {
}
func (f *frontMatterHandlerImpl) CleanUp() {
tryRemoveFile(f.yamlFrontMatterFilename)
tryRemoveTempFile(f.yamlFrontMatterFilename)
}
// Splits the given file by yaml front matter

View File

@ -66,7 +66,7 @@ yaml: doc
}
test.AssertResult(t, expectedContent, string(contentBytes))
tryRemoveFile(file)
tryRemoveTempFile(file)
fmHandler.CleanUp()
}
@ -103,7 +103,7 @@ yaml: doc
}
test.AssertResult(t, expectedContent, string(contentBytes))
tryRemoveFile(file)
tryRemoveTempFile(file)
fmHandler.CleanUp()
}
@ -137,6 +137,6 @@ yaml: doc
}
test.AssertResult(t, expectedContent, string(contentBytes))
tryRemoveFile(file)
tryRemoveTempFile(file)
fmHandler.CleanUp()
}

View File

@ -44,8 +44,8 @@ func (w *writeInPlaceHandlerImpl) FinishWriteInPlace(evaluatedSuccessfully bool)
safelyCloseFile(w.tempFile)
if evaluatedSuccessfully {
log.Debug("Moving temp file to target")
safelyRenameFile(w.tempFile.Name(), w.inputFilename)
tryRenameFile(w.tempFile.Name(), w.inputFilename)
} else {
tryRemoveFile(w.tempFile.Name())
tryRemoveTempFile(w.tempFile.Name())
}
}