@@ -3,30 +3,62 @@ package watcher
33import (
44 "github.com/cmuench/inotify-proxy/internal/profile/validator"
55 "github.com/gookit/color"
6+ "github.com/karrick/godirwalk"
67 "os"
7- "path/filepath"
88 "time"
99)
1010
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+
1129func Watch (includedDirectories []string , watchFrequenceSeconds int , profile string ) {
1230 selectedProfile = profile
1331
32+ i := 0
33+
1434 for {
1535 for _ , directoryToWalk := range includedDirectories {
16- err := filepath .Walk (directoryToWalk , visit )
36+ err := godirwalk .Walk (directoryToWalk , & godirwalk.Options {
37+ Callback : visit ,
38+ Unsorted : true ,
39+ })
1740
1841 if err != nil {
1942 panic (err )
2043 }
2144 }
2245
2346 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 ++
2454 }
2555}
2656
27- func isFileChanged (path string , fileInfo os.FileInfo ) bool {
57+ func isFileChanged (path string ) bool {
58+ fileInfo , err := os .Stat (path )
2859
29- if ! validator .IsPathValid (path , selectedProfile ) {
60+ if err != nil {
61+ color .Errorf ("Cannot stat file %s\n " , path )
3062 return false
3163 }
3264
@@ -64,21 +96,21 @@ func isFileChanged(path string, fileInfo os.FileInfo) bool {
6496 return changed
6597}
6698
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+ }
75105 }
106+ }
76107
77- fileChanged := isFileChanged (path , fileInfo )
108+ func fileExists (path string ) bool {
109+ info , err := os .Stat (path )
78110
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
81113 }
82114
83- return nil
115+ return ! info . IsDir ()
84116}
0 commit comments