-
Notifications
You must be signed in to change notification settings - Fork 1
/
safeio.go
101 lines (82 loc) · 2.11 KB
/
safeio.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Package safeio provides functions to perform atomic, fsync-safe disk
// operations.
package safeio
import (
"io"
"os"
"path/filepath"
"runtime"
)
// WriteToFile consumes the provided io.Reader and writes it to a temp
// file in the provided directory.
func WriteToFile(src io.Reader, path string, perm os.FileMode) (written int64, err error) {
tempName, written, err := writeToTempFile(src, path, perm)
if err == nil {
err = Rename(tempName, path)
}
return written, err
}
// writeToTempFile consumes the provided io.Reader and writes it to a
// temp file in the same directory as path.
func writeToTempFile(src io.Reader, path string, perm os.FileMode) (tempName string, written int64, err error) {
dir := filepath.Dir(path)
name := filepath.Base(path)
f, err := os.CreateTemp(dir, name+".tmp")
if err != nil {
return "", 0, err
}
tempName = f.Name()
cleanup := func(written int64, err error) (string, int64, error) {
_ = f.Close()
_ = os.Remove(tempName)
return "", written, err
}
if err = f.Chmod(perm); err != nil {
return cleanup(0, err)
}
written, err = io.Copy(f, src)
if err != nil {
return cleanup(written, err)
}
if err := f.Sync(); err != nil {
return cleanup(written, err)
}
if err := f.Close(); err != nil {
return cleanup(written, err)
}
return tempName, written, nil
}
// Remove is just like os.Remove, except this also calls sync on the
// parent directory.
func Remove(fn string) error {
err := os.Remove(fn)
if err != nil {
return err
}
// fsync the dir
return syncParentDir(fn)
}
// Rename renames the file using os.Rename and fsyncs the NEW parent
// directory. It should only be used if both oldname and newname are in
// the same directory.
func Rename(oldname, newname string) error {
err := os.Rename(oldname, newname)
if err != nil {
return err
}
// fsync the dir
return syncParentDir(newname)
}
func syncParentDir(name string) error {
// Skipping sync dir for windows
// because it is not supported.
if runtime.GOOS == "windows" {
return nil
}
f, err := os.Open(filepath.Dir(name))
if err != nil {
return err
}
defer f.Close()
return f.Sync()
}