/
reader.go
85 lines (68 loc) · 1.41 KB
/
reader.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
package input
import (
"bytes"
"os"
"path/filepath"
"github.com/spf13/afero"
)
type Reader interface {
ReadAll(root string) ([]byte, error)
}
type ReaderImpl struct {
fs afero.Fs
}
func NewReader(fs afero.Fs) *ReaderImpl {
return &ReaderImpl{
fs,
}
}
func (r ReaderImpl) ReadAll(root string) ([]byte, error) {
var err error
// find all files
yamlFiles, err := r.FindFiles(root)
if err != nil {
return nil, err
}
// read all of the files
allBytes := []byte{}
for _, name := range yamlFiles {
f, err := r.fs.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
b, err := afero.ReadAll(f)
if err != nil {
return nil, err
}
allBytes = append(allBytes, b...)
// if the last byte is not a newline, append one so the yaml can unmarshal properly
if !bytes.HasSuffix(allBytes, []byte{'\n'}) {
allBytes = append(allBytes, byte('\n'))
}
}
return allBytes, nil
}
func (r ReaderImpl) FindFiles(root string) ([]string, error) {
var files []string
err := afero.Walk(r.fs, root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// no need for directories
if info.IsDir() {
return nil
}
// match by extension
ext := filepath.Ext(info.Name())
if ext == ".yaml" || ext == ".yml" || ext == ".comp" {
files = append(files, path)
}
// no match found
return nil
})
if err != nil {
return nil, err
}
return files, nil
}