-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathio_atomic.go
More file actions
41 lines (35 loc) · 903 Bytes
/
Copy pathio_atomic.go
File metadata and controls
41 lines (35 loc) · 903 Bytes
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
package contexting
import (
"fmt"
"os"
"path/filepath"
)
func writeFileAtomic(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("create directory: %w", err)
}
tmpFile, err := os.CreateTemp(dir, ".tmp-*.json")
if err != nil {
return fmt.Errorf("create temp file: %w", err)
}
tmpPath := tmpFile.Name()
defer func() {
_ = os.Remove(tmpPath)
}()
if _, err := tmpFile.Write(data); err != nil {
_ = tmpFile.Close()
return fmt.Errorf("write temp file: %w", err)
}
if err := tmpFile.Chmod(perm); err != nil {
_ = tmpFile.Close()
return fmt.Errorf("chmod temp file: %w", err)
}
if err := tmpFile.Close(); err != nil {
return fmt.Errorf("close temp file: %w", err)
}
if err := os.Rename(tmpPath, path); err != nil {
return fmt.Errorf("replace file: %w", err)
}
return nil
}