@@ -3,30 +3,62 @@ package watcher
3
3
import (
4
4
"github.com/cmuench/inotify-proxy/internal/profile/validator"
5
5
"github.com/gookit/color"
6
+ "github.com/karrick/godirwalk"
6
7
"os"
7
- "path/filepath"
8
8
"time"
9
9
)
10
10
11
+ func visit (osPathname string , de * godirwalk.Dirent ) error {
12
+ // we only process files
13
+ if de .IsDir () {
14
+ return nil
15
+ }
16
+
17
+ if ! validator .IsPathValid (osPathname , selectedProfile ) {
18
+ return godirwalk .SkipThis
19
+ }
20
+
21
+ fileChanged := isFileChanged (osPathname )
22
+ if fileChanged {
23
+ color.Style {color .FgGreen , color .OpBold }.Printf ("Changed: %s | %s\n " , osPathname , time .Now ().Format ("2006-01-02T15:04:05" ))
24
+ }
25
+
26
+ return nil
27
+ }
28
+
11
29
func Watch (includedDirectories []string , watchFrequenceSeconds int , profile string ) {
12
30
selectedProfile = profile
13
31
32
+ i := 0
33
+
14
34
for {
15
35
for _ , directoryToWalk := range includedDirectories {
16
- err := filepath .Walk (directoryToWalk , visit )
36
+ err := godirwalk .Walk (directoryToWalk , & godirwalk.Options {
37
+ Callback : visit ,
38
+ Unsorted : true ,
39
+ })
17
40
18
41
if err != nil {
19
42
panic (err )
20
43
}
21
44
}
22
45
23
46
time .Sleep (time .Duration (watchFrequenceSeconds ) * time .Second )
47
+
48
+ if i % 10 == 0 {
49
+ garbageCollection ()
50
+ color .Info .Printf ("Watching %d files ...\n " , len (fileMap ))
51
+ }
52
+
53
+ i ++
24
54
}
25
55
}
26
56
27
- func isFileChanged (path string , fileInfo os.FileInfo ) bool {
57
+ func isFileChanged (path string ) bool {
58
+ fileInfo , err := os .Stat (path )
28
59
29
- if ! validator .IsPathValid (path , selectedProfile ) {
60
+ if err != nil {
61
+ color .Errorf ("Cannot stat file %s\n " , path )
30
62
return false
31
63
}
32
64
@@ -64,21 +96,21 @@ func isFileChanged(path string, fileInfo os.FileInfo) bool {
64
96
return changed
65
97
}
66
98
67
- func visit (path string , fileInfo os.FileInfo , err error ) error {
68
-
69
- if err != nil {
70
- return err
71
- }
72
-
73
- if fileInfo .IsDir () {
74
- return nil
99
+ func garbageCollection () {
100
+ for path , _ := range fileMap {
101
+ if ! fileExists (path ) {
102
+ delete (fileMap , path )
103
+ color.Style {color .FgGray }.Printf ("Deleted: %s\n " , path )
104
+ }
75
105
}
106
+ }
76
107
77
- fileChanged := isFileChanged (path , fileInfo )
108
+ func fileExists (path string ) bool {
109
+ info , err := os .Stat (path )
78
110
79
- if fileChanged {
80
- color. Style { color . FgGreen , color . OpBold }. Printf ( "Changed: %s | %s \n " , path , time . Now (). Format ( "2006-01-02T15:04:05" ))
111
+ if os . IsNotExist ( err ) {
112
+ return false
81
113
}
82
114
83
- return nil
115
+ return ! info . IsDir ()
84
116
}
0 commit comments