-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
133 lines (113 loc) · 1.96 KB
/
file.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package main
import (
"context"
"io"
"os"
"path"
"path/filepath"
"sync"
"time"
"go.atomizer.io/stream"
"go.devnw.com/gen"
)
// ReadFiles reads the files at the path provided
// and returns a channel of io.ReadCloser where it
// deposits the open file.
func ReadFiles(
ctx context.Context,
logger Logger,
files <-chan string,
) <-chan io.ReadCloser {
s := stream.Scaler[string, io.ReadCloser]{
Wait: time.Nanosecond,
Life: time.Millisecond,
Fn: func(
_ context.Context,
path string,
) (io.ReadCloser, bool) {
data, err := os.Open(path)
if err != nil {
return nil, false
}
return data, true
},
}
out, err := s.Exec(ctx, files)
if err != nil {
logger.Errorw(
"error reading files",
"error", err,
)
}
return out
}
// ReadDirectory recursively reads through the directory structure
// providing a channel of file paths.
func ReadDirectory(
ctx context.Context,
logger Logger,
dir string,
exts ...string,
) <-chan string {
out := make(chan string)
go func() {
defer close(out)
files, err := os.ReadDir(dir)
if err != nil {
logger.Errorw(
"error reading directory",
"dir", dir,
"error", err,
)
return
}
wg := sync.WaitGroup{}
for _, file := range files {
if !file.IsDir() {
i, err := file.Info()
if err != nil {
logger.Errorw(
"error reading file info",
"dir", dir,
"file", file.Name(),
"error", err,
)
continue
}
if len(exts) > 0 {
if !gen.Has(exts, filepath.Ext(i.Name())) {
continue
}
}
select {
case <-ctx.Done():
return
case out <- path.Join(dir, i.Name()):
}
continue
}
i, err := file.Info()
if err != nil {
return
}
wg.Add(1)
go func(d os.FileInfo) {
defer wg.Done()
stream.Pipe(
ctx,
ReadDirectory(
ctx,
logger,
path.Join(
dir,
d.Name(),
),
),
out,
)
}(i)
}
wg.Wait()
}()
return out
}