-
Notifications
You must be signed in to change notification settings - Fork 12
/
atomic.go
73 lines (68 loc) · 2.13 KB
/
atomic.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
// package atomic provides functions to atomically change files.
package atomic
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
)
// WriteFile atomically writes the contents of r to the specified filepath. If
// an error occurs, the target file is guaranteed to be either fully written, or
// not written at all. WriteFile overwrites any file that exists at the
// location (but only if the write fully succeeds, otherwise the existing file
// is unmodified).
func WriteFile(filename string, r io.Reader) (err error) {
// write to a temp file first, then we'll atomically replace the target file
// with the temp file.
dir, file := filepath.Split(filename)
if dir == "" {
dir = "."
}
f, err := ioutil.TempFile(dir, file)
if err != nil {
return fmt.Errorf("cannot create temp file: %v", err)
}
defer func() {
if err != nil {
// Don't leave the temp file lying around on error.
_ = os.Remove(f.Name()) // yes, ignore the error, not much we can do about it.
}
}()
// ensure we always close f. Note that this does not conflict with the
// close below, as close is idempotent.
defer f.Close()
name := f.Name()
if _, err := io.Copy(f, r); err != nil {
return fmt.Errorf("cannot write data to tempfile %q: %v", name, err)
}
// fsync is important, otherwise os.Rename could rename a zero-length file
if err := f.Sync(); err != nil {
return fmt.Errorf("can't flush tempfile %q: %v", name, err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("can't close tempfile %q: %v", name, err)
}
// get the file mode from the original file and use that for the replacement
// file, too.
destInfo, err := os.Stat(filename)
if os.IsNotExist(err) {
// no original file
} else if err != nil {
return err
} else {
sourceInfo, err := os.Stat(name)
if err != nil {
return err
}
if sourceInfo.Mode() != destInfo.Mode() {
if err := os.Chmod(name, destInfo.Mode()); err != nil {
return fmt.Errorf("can't set filemode on tempfile %q: %v", name, err)
}
}
}
if err := ReplaceFile(name, filename); err != nil {
return fmt.Errorf("cannot replace %q with tempfile %q: %v", filename, name, err)
}
return nil
}