-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_scan.go
95 lines (86 loc) · 1.62 KB
/
file_scan.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
package main
import (
"io/ioutil"
"os"
"path/filepath"
"time"
)
type FileScanner struct {
paths []string
Files chan string
interval int
include string
exclude string
stop chan struct{}
}
func NewFileScanner(paths []string, interval int, include, exclude string) *FileScanner {
files := make(chan string)
stop := make(chan struct{})
return &FileScanner{paths: paths, Files: files, interval: interval, include: include, exclude: exclude, stop: stop}
}
func (s *FileScanner) Start() {
go func() {
for {
select {
case <-s.stop:
return
default:
}
for _, p := range s.paths {
s.scan(p)
}
time.Sleep(time.Duration(s.interval) * time.Second)
}
}()
}
func (s *FileScanner) Stop() {
s.stop <- struct{}{}
}
func (s *FileScanner) scan(path string) error {
matches, err := filepath.Glob(path)
if err != nil {
return err
}
if matches != nil {
for _, p := range matches {
s.walk(p)
}
}
return nil
}
func (s *FileScanner) walk(path string) {
stat, err := os.Stat(path)
if err != nil {
return
}
if stat.IsDir() {
dir, err := ioutil.ReadDir(path)
if err == nil {
for _, st := range dir {
if st.IsDir() {
s.walk(filepath.Join(path, st.Name()))
}
}
}
} else {
if filepath.IsAbs(path) && stat.Mode().IsRegular() {
s.accept(path)
}
}
}
func (s *FileScanner) accept(path string) {
if s.exclude != "" {
excluded, err := filepath.Match(s.exclude, path)
if err != nil || excluded {
return
}
}
if s.include != "" {
included, err := filepath.Match(s.include, path)
if err == nil && included {
s.Files <- path
}
} else {
s.Files <- path
}
}