forked from openshift/installer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filefetcher.go
59 lines (49 loc) · 1.44 KB
/
filefetcher.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
package asset
import (
"io/ioutil"
"path/filepath"
"sort"
)
//go:generate mockgen -source=./filefetcher.go -destination=./mock/filefetcher_generated.go -package=mock
// FileFetcher fetches the asset files from disk.
type FileFetcher interface {
// FetchByName returns the file with the given name.
FetchByName(string) (*File, error)
// FetchByPattern returns the files whose name match the given glob.
FetchByPattern(pattern string) ([]*File, error)
}
type fileFetcher struct {
directory string
}
// FetchByName returns the file with the given name.
func (f *fileFetcher) FetchByName(name string) (*File, error) {
data, err := ioutil.ReadFile(filepath.Join(f.directory, name))
if err != nil {
return nil, err
}
return &File{Filename: name, Data: data}, nil
}
// FetchByPattern returns the files whose name match the given regexp.
func (f *fileFetcher) FetchByPattern(pattern string) (files []*File, err error) {
matches, err := filepath.Glob(filepath.Join(f.directory, pattern))
if err != nil {
return nil, err
}
files = make([]*File, 0, len(matches))
for _, path := range matches {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
filename, err := filepath.Rel(f.directory, path)
if err != nil {
return nil, err
}
files = append(files, &File{
Filename: filename,
Data: data,
})
}
sort.Slice(files, func(i, j int) bool { return files[i].Filename < files[j].Filename })
return files, nil
}