/
write_in_place_handler.go
56 lines (45 loc) · 1.24 KB
/
write_in_place_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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 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
}