/
visit_files_in_directory.go
96 lines (90 loc) · 2.58 KB
/
visit_files_in_directory.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
package medorg
import (
"io/fs"
"log"
"sync"
)
// VisitFilesInDirectories: You should default to using this utility function where you can
// It's probably what you want!
// You can supply a visitor and get the fileStruct associated with the file in question
// Any changes you make to that will be reflected on disk
// Note it only visits files that already have an entry (This might need to be fixed?)
func VisitFilesInDirectories(
directories []string,
registerFunc func(dt *DirTracker),
someVisitFunc func(dm DirectoryMap, dir, fn string, d fs.DirEntry, fileStruct FileStruct, fileInfo fs.FileInfo) error,
) <-chan error {
dts := AutoVisitFilesInDirectories(directories, someVisitFunc)
return errHandler(dts, registerFunc)
}
func errHandler(
dts []*DirTracker,
registerFunc func(dt *DirTracker),
) <-chan error {
if registerFunc == nil {
registerFunc = func(dt *DirTracker) {}
}
errChan := make(chan error)
var wg sync.WaitGroup
wg.Add(len(dts))
for _, ndt := range dts {
registerFunc(ndt)
go func(ndt *DirTracker) {
for err := range ndt.ErrChan() {
log.Println("Error received", err)
if err != nil {
errChan <- err
}
}
wg.Done()
}(ndt)
}
go func() {
wg.Wait()
close(errChan)
}()
return errChan
}
func AutoVisitFilesInDirectories(
directories []string,
someVisitFunc func(dm DirectoryMap, dir, fn string, d fs.DirEntry, fileStruct FileStruct, fileInfo fs.FileInfo) error,
) []*DirTracker {
if someVisitFunc == nil {
someVisitFunc = func(dm DirectoryMap, dir, fn string, d fs.DirEntry, fileStruct FileStruct, fileInfo fs.FileInfo) error {
return nil
}
}
visitFunc := func(dm DirectoryMap, dir, fn string, d fs.DirEntry) error {
if fn == Md5FileName {
return nil
}
fileStruct, ok := dm.Get(fn)
if !ok {
var err error
// FIXME we could use the fileInfo from below if we had the option
fileStruct, err = NewFileStruct(dir, fn)
if err != nil {
return err
}
dm.Add(fileStruct)
}
fileInfo, err := d.Info()
if err != nil {
return err
}
return someVisitFunc(dm, dir, fn, d, fileStruct, fileInfo)
}
makerFunc := func(dir string) (DirectoryTrackerInterface, error) {
mkFk := func(dir string) (DirectoryEntryInterface, error) {
dm, err := DirectoryMapFromDir(dir)
dm.VisitFunc = visitFunc
return dm, err
}
return NewDirectoryEntry(dir, mkFk)
}
retArray := make([]*DirTracker, len(directories))
for i, targetDir := range directories {
retArray[i] = NewDirTracker(targetDir, makerFunc)
}
return retArray
}