-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileUtils.go
68 lines (62 loc) · 1.34 KB
/
fileUtils.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
// os.RemoveAll not work correctly on windows platform,
// if there a file which attribute is read only, the RemoveAll function will fail.
// so i wrote a RemoveAllEx function to fix it.
package fileUtils
import (
"log"
"os"
"path/filepath"
)
// remove the given path, if the path is a file
// remove sub folders and all files in the path, if the path is a directory
func RemoveAllEx(path string) error {
err := resetReadOnlyFlagAll(path)
if err != nil {
return err
}
return os.RemoveAll(path)
}
// check the given file exists or not
func FileExists(path string) bool {
fi, err := os.Stat(path)
if err != nil {
return false
}
return !fi.IsDir()
}
// check the given directory exists or not
func DirectoryExists(path string) bool {
fi, err := os.Stat(path)
if err != nil {
return false
}
return fi.IsDir()
}
func resetReadOnlyFlagAll(path string) error {
fi, err := os.Stat(path)
if err != nil {
//the directory not exists
if os.IsNotExist(err) {
return nil
}
return err
}
if !fi.IsDir() {
err := os.Chmod(path, 0666)
if err != nil {
return err
}
}
fd, err := os.Open(path)
if err != nil {
return err
}
defer fd.Close()
names, _ := fd.Readdirnames(-1)
for _, name := range names {
newNames := filepath.Join(path, name)
log.Println("the sub name is", newNames)
resetReadOnlyFlagAll(newNames)
}
return nil
}