-
-
Notifications
You must be signed in to change notification settings - Fork 556
/
write_in_place_handler.go
51 lines (42 loc) · 1.15 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
package yqlib
import (
"os"
)
type writeInPlaceHandler interface {
CreateTempFile() (*os.File, error)
FinishWriteInPlace(evaluatedSuccessfully bool)
}
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
}
log.Debug("WriteInPlaceHandler: writing to tempfile: %v", file.Name())
w.tempFile = file
return file, err
}
func (w *writeInPlaceHandlerImpl) FinishWriteInPlace(evaluatedSuccessfully bool) {
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")
tryRenameFile(w.tempFile.Name(), w.inputFilename)
} else {
tryRemoveTempFile(w.tempFile.Name())
}
}