-
Notifications
You must be signed in to change notification settings - Fork 488
/
atomicfile.go
59 lines (54 loc) · 1.52 KB
/
atomicfile.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
// Package common provides the ability to write a file with an eventual
// rename on Close (using os.Rename). This allows for a file to always be in a
// consistent state and never represent an in-progress write.
//
// NOTE: `os.Rename` may not be atomic on your operating system.
package common
import (
"io/ioutil"
"os"
"path/filepath"
)
// AtomicFile behaves like os.File, but does an atomic rename operation at Close.
type AtomicFile struct {
*os.File
path string
}
// AtomicFileNew creates a new temporary file that will replace the file at the given
// path when Closed.
func AtomicFileNew(path string, mode os.FileMode) (*AtomicFile, error) {
f, err := ioutil.TempFile(filepath.Dir(path), filepath.Base(path))
if err != nil {
return nil, err
}
if err := os.Chmod(f.Name(), mode); err != nil {
_ = f.Close()
_ = os.Remove(f.Name())
return nil, err
}
return &AtomicFile{File: f, path: path}, nil
}
// Close the file replacing the configured file.
func (f *AtomicFile) Close() error {
if err := f.File.Close(); err != nil {
_ = os.Remove(f.File.Name())
return err
}
if err := os.Rename(f.Name(), f.path); err != nil {
return err
}
return nil
}
// Abort closes the file and removes it instead of replacing the configured
// file. This is useful if after starting to write to the file you decide you
// don't want it anymore.
func (f *AtomicFile) Abort() error {
if err := f.File.Close(); err != nil {
_ = os.Remove(f.Name())
return err
}
if err := os.Remove(f.Name()); err != nil {
return err
}
return nil
}