-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
58 lines (42 loc) · 968 Bytes
/
file.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
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
)
func EnsureDir(fileName string) (err error) {
dirName := filepath.Dir(fileName)
if _, err := os.Stat(dirName); err != nil {
err = os.MkdirAll(dirName, os.ModePerm)
}
return err
}
func CreateFile(path, content string) (result CreateFileResult) {
result.path = path
err := EnsureDir(path)
if err == nil {
f, err := os.Create(path)
defer func() {
if err2 := f.Close(); err2 != nil && err == nil {
err = err2
result.error = err
}
}()
_, err = f.WriteString(content)
}
result.error = err
return result
}
func CreateDir(dirPath string) (err error) {
src, err := os.Stat(dirPath)
if err == nil && src.Mode().IsRegular() {
err = errors.New(fmt.Sprintf("%s already exist as a file.", dirPath))
return err
}
if !os.IsNotExist(err) {
return errors.New(fmt.Sprintf("%s already exist as a dir.", dirPath))
}
err = os.MkdirAll(dirPath, 0755)
return err
}