2020-11-29 09:25:47 +00:00
|
|
|
package yqlib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2021-01-11 22:55:55 +00:00
|
|
|
type writeInPlaceHandler interface {
|
2020-11-29 09:25:47 +00:00
|
|
|
CreateTempFile() (*os.File, error)
|
2022-01-14 04:40:20 +00:00
|
|
|
FinishWriteInPlace(evaluatedSuccessfully bool) error
|
2020-11-29 09:25:47 +00:00
|
|
|
}
|
|
|
|
|
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) {
|
2021-07-18 02:28:46 +00:00
|
|
|
file, err := createTempFile()
|
|
|
|
|
2020-11-29 09:25:47 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-07-18 02:28:46 +00:00
|
|
|
info, err := os.Stat(w.inputFilename)
|
|
|
|
if err != nil {
|
2020-11-29 09:25:47 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2021-07-18 02:28:46 +00:00
|
|
|
err = os.Chmod(file.Name(), info.Mode())
|
2020-11-29 09:25:47 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-01-03 04:52:01 +00:00
|
|
|
|
|
|
|
if err = changeOwner(info, file); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-07-18 02:28:46 +00:00
|
|
|
log.Debug("WriteInPlaceHandler: writing to tempfile: %v", file.Name())
|
2020-11-29 09:25:47 +00:00
|
|
|
w.tempFile = file
|
|
|
|
return file, err
|
|
|
|
}
|
|
|
|
|
2022-01-14 04:40:20 +00:00
|
|
|
func (w *writeInPlaceHandlerImpl) FinishWriteInPlace(evaluatedSuccessfully bool) error {
|
2023-09-18 23:52:36 +00:00
|
|
|
log.Debug("Going to write in place, evaluatedSuccessfully=%v, target=%v", evaluatedSuccessfully, w.inputFilename)
|
2020-11-29 09:25:47 +00:00
|
|
|
safelyCloseFile(w.tempFile)
|
|
|
|
if evaluatedSuccessfully {
|
2021-07-18 02:28:46 +00:00
|
|
|
log.Debug("Moving temp file to target")
|
2022-01-14 04:40:20 +00:00
|
|
|
return tryRenameFile(w.tempFile.Name(), w.inputFilename)
|
2020-11-29 09:25:47 +00:00
|
|
|
}
|
2022-01-14 04:40:20 +00:00
|
|
|
tryRemoveTempFile(w.tempFile.Name())
|
|
|
|
|
|
|
|
return nil
|
2020-11-29 09:25:47 +00:00
|
|
|
}
|