-
Notifications
You must be signed in to change notification settings - Fork 31
/
watcher.event.go
110 lines (99 loc) · 2.56 KB
/
watcher.event.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"fmt"
"os"
"path"
"strings"
"github.com/fsnotify/fsnotify"
)
const (
// WatcherEventCreate denotes a file/dir creation
WatcherEventCreate = "+"
// WatcherEventWrite denotes a file write
WatcherEventWrite = ">"
// WatcherEventRemove denotes removal of a file/dir
WatcherEventRemove = "-"
// WatcherEventRename denotes renaming of a file/dir
WatcherEventRename = "/"
// WatcherEventPermission denotes chmodding of a file/dir
WatcherEventPermission = "%"
// WatcherFileTypeDir indicates a directory
WatcherFileTypeDir = "dir"
// WatcherFileTypeErrored indicates an error
WatcherFileTypeErrored = "err"
// WatcherFileTypeDeleted indicates a deleted item
WatcherFileTypeDeleted = "rm"
)
var watcherEventType = []string{
"",
// 00001
WatcherEventCreate,
// 00010
WatcherEventWrite, "",
// 00100
WatcherEventRemove, "", "", "",
// 01000
WatcherEventRename, "", "", "", "", "", "", "",
// 10000
WatcherEventPermission,
}
// WatcherEvent provides some function candy for working with
// fsnotify more easily
type WatcherEvent fsnotify.Event
// EventType returns a symbol denoting the type of operation recorded
func (e *WatcherEvent) EventType() string {
eventType := ""
watcherEvents := []fsnotify.Op{1, 2, 4, 8, 16}
for _, event := range watcherEvents {
if e.Op|event == event {
eventType += watcherEventType[event]
}
}
return eventType
}
// FilePath returns the absolute path of the file/dir
func (e *WatcherEvent) FilePath() string {
return e.Name
}
// FileName returns the file/dir name
func (e *WatcherEvent) FileName() string {
return path.Base(e.Name)
}
// FileType returns the extension of the file if its a file,
// "dir" if its a dir, or "errored" if an error occurred
func (e *WatcherEvent) FileType() string {
var fileType string
if e.Op|fsnotify.Remove == fsnotify.Remove {
fileType = WatcherFileTypeDeleted
} else {
fileType = path.Ext(e.Name)
if len(fileType) == 0 {
fileInfo, err := os.Lstat(e.Name)
if err != nil {
fileType = WatcherFileTypeErrored
} else if fileInfo.IsDir() {
fileType = WatcherFileTypeDir
} else {
fileType = path.Base(e.Name)
}
}
}
return fileType
}
// IsAnyOf verifies that the file extension matches :theseTypes
func (e *WatcherEvent) IsAnyOf(theseTypes []string) bool {
for _, fileExtension := range theseTypes {
if strings.TrimLeft(e.FileType(), ".") == strings.TrimLeft(fileExtension, ".") {
return true
}
}
return false
}
func (e *WatcherEvent) String() string {
return fmt.Sprintf(
"[%s] %s at '%s'",
e.EventType(),
e.FileType(),
e.FilePath(),
)
}