yq/pkg/yqlib/write_in_place_handler.go
Mike Farah 18cdea3f88
Build constraint not working for non linux (#1481)
* Build constraint not working for non linux

* Go Build Constraint: Fix Non-Linux Filename (#1494)

Correct the filename pkg/yqlib/chown_not_linux.go to escape the
default OS detection in filename format `*_GOOS[_test].go`.

Add an extra word after `linux` to resolve the issue.
pkg/yqlib/chown_not_linux_os.go

Signed-off-by: Bhargav Ravuri <vaguecoder0to.n@gmail.com>

Signed-off-by: Bhargav Ravuri <vaguecoder0to.n@gmail.com>

Signed-off-by: Bhargav Ravuri <vaguecoder0to.n@gmail.com>
Co-authored-by: Bhargav Ravuri <saibhargavravuri@gmail.com>
2023-01-03 15:52:01 +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.Debug("WriteInPlaceHandler: writing to tempfile: %v", file.Name())
w.tempFile = file
return file, err
}
func (w *writeInPlaceHandlerImpl) FinishWriteInPlace(evaluatedSuccessfully bool) error {
log.Debug("Going to write-inplace, 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
}