-
Notifications
You must be signed in to change notification settings - Fork 0
/
chmod.go
81 lines (68 loc) · 1.61 KB
/
chmod.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
package fshelper
import (
"errors"
"fmt"
"os"
"path/filepath"
)
type FlagsChmod uint
const (
ChmodChanges FlagsChmod = 1 << iota
ChmodVerbose
ChmodRecursive
ChmodOnlyDirs
ChmodOnlyFiles
)
var (
ErrSkipFile = errors.New("skip file")
ErrSkipDir = errors.New("skip dir")
ErrIncompatibleFlags = errors.New("incompatible combination of flags")
)
func Chmod(flags FlagsChmod, mode os.FileMode, path string) error {
if ChmodOnlyFiles&flags != 0 && ChmodOnlyDirs&flags != 0 {
return ErrIncompatibleFlags
}
if ChmodVerbose&flags != 0 && ChmodChanges&flags != 0 {
flags &= ^ChmodChanges
}
if ChmodRecursive&flags != 0 {
return filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
chmod(flags, mode, info, path)
// TODO: may be errors count (except skips)
return nil
})
}
info, err := os.Stat(path)
if err != nil {
return err
}
return chmod(flags, mode, info, path)
}
func chmod(flags FlagsChmod, mode os.FileMode, info os.FileInfo, path string) (err error) {
defer func() {
if err != nil && (ChmodVerbose|ChmodChanges)&flags == 0 {
fmt.Printf("%s: %s\n", path, err)
}
}()
if info.IsDir() {
if ChmodOnlyFiles&flags != 0 {
return ErrSkipDir
}
} else {
if ChmodOnlyDirs&flags != 0 {
return ErrSkipFile
}
}
currentMode := info.Mode()
if currentMode != mode {
if ChmodChanges&flags != 0 || ChmodVerbose&flags != 0 {
fmt.Printf("%s: %v -> %v\n", path, currentMode, mode)
}
} else if ChmodVerbose&flags != 0 {
fmt.Printf("%s: already %v\n", path, currentMode)
}
return os.Chmod(path, mode)
}