forked from deanishe/awgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
files.go
86 lines (76 loc) · 1.82 KB
/
files.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
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright (c) 2019 Dean Jackson <[email protected]>
// MIT Licence applies http://opensource.org/licenses/MIT
package util
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
)
// MustExist creates all specified directories and returns the last one.
// Panics if any directory cannot be created.
// All created directories have permission set to 0700.
func MustExist(dirpath ...string) string {
var path string
for _, path = range dirpath {
if err := os.MkdirAll(path, 0700); err != nil {
panic(fmt.Sprintf("create directory %q: %v", path, err))
}
}
return path
}
// PathExists checks for the existence of path.
// Panics if an error is encountered.
func PathExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
panic(err)
}
// ClearDirectory deletes all files within a directory, but not directory itself.
func ClearDirectory(p string) error {
if !PathExists(p) {
return nil
}
err := os.RemoveAll(p)
MustExist(p)
if err == nil {
log.Printf("deleted contents of %q", p)
}
return err
}
// WriteFile is an atomic version of ioutil.WriteFile.
// It first writes data to a temporary file and renames this to
// filename if the write is successful.
func WriteFile(filename string, data []byte, perm os.FileMode) error {
dir, name := filepath.Split(filename)
f, err := ioutil.TempFile(dir, name)
if err != nil {
return err
}
defer closeOrPanic(f)
name = f.Name()
defer func() {
// Ensure tempfile is deleted
if err := os.Remove(name); err != nil {
if !os.IsNotExist(err) {
log.Printf("[ERROR] tempfile: %v", err)
}
}
}()
if err := ioutil.WriteFile(name, data, perm); err != nil {
return err
}
return os.Rename(name, filename)
}
func closeOrPanic(c io.Closer) {
if err := c.Close(); err != nil {
panic(err)
}
}