yq/pkg/yqlib/write_in_place_handler.go
Copilot 7d8d3ab902
Replace gopkg.in/op/go-logging.v1 with log/slog (#2635)
* Initial plan

* Replace gopkg.in/op/go-logging.v1 with log/slog

Co-authored-by: mikefarah <1151925+mikefarah@users.noreply.github.com>
Agent-Logs-Url: https://github.com/mikefarah/yq/sessions/aa9c12f4-21b9-4633-9868-6b56585b247f

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: mikefarah <1151925+mikefarah@users.noreply.github.com>
2026-03-26 20:41:54 +11:00

57 lines
1.2 KiB
Go

package yqlib
import (
"os"
)
type writeInPlaceHandler interface {
CreateTempFile() (*os.File, error)
FinishWriteInPlace(evaluatedSuccessfully bool) error
}
type writeInPlaceHandlerImpl struct {
inputFilename string
tempFile *os.File
}
func NewWriteInPlaceHandler(inputFile string) writeInPlaceHandler {
return &writeInPlaceHandlerImpl{inputFile, nil}
}
func (w *writeInPlaceHandlerImpl) CreateTempFile() (*os.File, error) {
file, err := createTempFile()
if err != nil {
return nil, err
}
info, err := os.Stat(w.inputFilename)
if err != nil {
return nil, err
}
err = os.Chmod(file.Name(), info.Mode())
if err != nil {
return nil, err
}
if err = changeOwner(info, file); err != nil {
return nil, err
}
log.Debugf("WriteInPlaceHandler: writing to tempfile: %v", file.Name())
w.tempFile = file
return file, err
}
func (w *writeInPlaceHandlerImpl) FinishWriteInPlace(evaluatedSuccessfully bool) error {
log.Debugf("Going to write in place, evaluatedSuccessfully=%v, target=%v", evaluatedSuccessfully, w.inputFilename)
safelyCloseFile(w.tempFile)
if evaluatedSuccessfully {
log.Debug("Moving temp file to target")
return tryRenameFile(w.tempFile.Name(), w.inputFilename)
}
tryRemoveTempFile(w.tempFile.Name())
return nil
}