-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace.go
54 lines (47 loc) · 1.26 KB
/
replace.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
package generator
import (
"errors"
"fmt"
"os"
)
// doAll executes a slice of function pointers, in LIFO order.
func doAll(funcs []func()) {
for i := len(funcs) - 1; i >= 0; i-- {
funcs[i]()
}
}
// AtomicFileReplace overwrites a series of files, but in a safe manner. If any
// of the file operations fail, they are all rolled back to their original
// state.
func AtomicFileReplace(src, dest []string) error {
if len(src) != len(dest) {
return errors.New("mismatched number of source and destination files")
}
commit := make([]func(), 0, len(dest))
rollback := make([]func(), 0, len(dest)*2)
// Move any existing destination files out of the way
for i := range dest {
_, err := os.Stat(dest[i])
if err == nil {
tmpFilename := fmt.Sprintf("%s.%d", dest[i], os.Getpid())
err = os.Rename(dest[i], tmpFilename)
if err != nil {
doAll(rollback)
return err
}
rollback = append(rollback, func() { os.Rename(tmpFilename, dest[i]) })
commit = append(commit, func() { os.Remove(tmpFilename) })
}
}
// Move new files into place
for i := range src {
err := os.Rename(src[i], dest[i])
if err != nil {
doAll(rollback)
return err
}
rollback = append(rollback, func() { os.Rename(dest[i], src[i]) })
}
doAll(commit)
return nil
}