yq/pkg/yqlib/write_in_place_handler.go

63 lines
1.4 KiB
Go
Raw Normal View History

2020-11-29 09:25:47 +00:00
package yqlib
import (
"io/ioutil"
"os"
)
2021-01-11 22:55:55 +00:00
type writeInPlaceHandler interface {
2020-11-29 09:25:47 +00:00
CreateTempFile() (*os.File, error)
FinishWriteInPlace(evaluatedSuccessfully bool)
}
2021-01-11 22:55:55 +00:00
type writeInPlaceHandlerImpl struct {
2020-11-29 09:25:47 +00:00
inputFilename string
tempFile *os.File
}
2021-01-11 22:55:55 +00:00
func NewWriteInPlaceHandler(inputFile string) writeInPlaceHandler {
2020-11-29 09:25:47 +00:00
2021-01-11 22:55:55 +00:00
return &writeInPlaceHandlerImpl{inputFile, nil}
2020-11-29 09:25:47 +00:00
}
2021-01-11 22:55:55 +00:00
func (w *writeInPlaceHandlerImpl) CreateTempFile() (*os.File, error) {
2020-11-29 09:25:47 +00:00
info, err := os.Stat(w.inputFilename)
if err != nil {
return nil, err
}
_, err = os.Stat(os.TempDir())
if os.IsNotExist(err) {
err = os.Mkdir(os.TempDir(), 0700)
if err != nil {
return nil, err
}
} else if err != nil {
return nil, err
}
file, err := ioutil.TempFile("", "temp")
if err != nil {
return nil, err
}
err = os.Chmod(file.Name(), info.Mode())
2020-11-30 05:05:07 +00:00
log.Debug("writing to tempfile: %v", file.Name())
2020-11-29 09:25:47 +00:00
w.tempFile = file
return file, err
}
2021-01-11 22:55:55 +00:00
func (w *writeInPlaceHandlerImpl) FinishWriteInPlace(evaluatedSuccessfully bool) {
2020-11-30 05:05:07 +00:00
log.Debug("Going to write-inplace, evaluatedSuccessfully=%v, target=%v", evaluatedSuccessfully, w.inputFilename)
2020-11-29 09:25:47 +00:00
safelyCloseFile(w.tempFile)
if evaluatedSuccessfully {
2020-11-30 05:05:07 +00:00
log.Debug("moved temp file to target")
2020-11-29 09:25:47 +00:00
safelyRenameFile(w.tempFile.Name(), w.inputFilename)
} else {
2020-11-30 05:05:07 +00:00
log.Debug("removed temp file")
removeErr := os.Remove(w.tempFile.Name())
if removeErr != nil {
log.Errorf("failed removing temp file: %s", w.tempFile.Name())
}
2020-11-29 09:25:47 +00:00
}
}