carlos / platform Public

Clone
git clone https://amadan.net/carlos/platform

Plain git — no account needed to clone.

Download

Download this file

1//go:build !linux
2
3package safefile
4
5import (
6 "fmt"
7 "io"
8 "os"
9 "path/filepath"
10)
11
12func MkdirAll(path string, mode os.FileMode) error { return os.MkdirAll(path, mode) }
13func OpenFile(path string, flags int, mode os.FileMode) (*os.File, error) {
14 return os.OpenFile(path, flags, mode)
15}
16func Remove(path string) error { return os.Remove(path) }
17func Write(path string, mode os.FileMode, write func(io.Writer) error) error {
18 f, err := os.CreateTemp(filepath.Dir(path), ".carlos-write-*")
19 if err != nil {
20 return err
21 }
22 defer os.Remove(f.Name())
23 defer f.Close()
24 if err := write(f); err != nil {
25 return err
26 }
27 if err := f.Chmod(mode); err != nil {
28 return err
29 }
30 if err := f.Sync(); err != nil {
31 return err
32 }
33 if err := f.Close(); err != nil {
34 return err
35 }
36 return os.Rename(f.Name(), path)
37}
38
39func OpenDir(path string) (*os.File, error) {
40 st, err := os.Lstat(path)
41 if err != nil {
42 return nil, err
43 }
44 if !st.IsDir() {
45 return nil, fmt.Errorf("%s is not a directory", path)
46 }
47 f, err := os.Open(path)
48 if err != nil {
49 return nil, err
50 }
51 st, err = f.Stat()
52 if err != nil {
53 f.Close()
54 return nil, err
55 }
56 if !st.IsDir() {
57 f.Close()
58 return nil, fmt.Errorf("%s is not a directory", path)
59 }
60 return f, nil
61}
62