-
Notifications
You must be signed in to change notification settings - Fork 37
/
file_resources.go
91 lines (72 loc) · 1.85 KB
/
file_resources.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
package resources
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
)
var (
fileResourcesAllowedExts = []string{".json", ".yaml", ".yml"} // matches kubectl
)
type FileResource struct {
fileSrc FileSource
}
func NewFileResources(file string, recursive bool) ([]FileResource, error) {
var fileRs []FileResource
switch {
case file == "-":
fileRs = append(fileRs, FileResource{NewStdinSource()})
case strings.HasPrefix(file, "http://") || strings.HasPrefix(file, "https://"):
fileRs = append(fileRs, FileResource{NewHTTPFileSource(file)})
default:
fileInfo, err := os.Stat(file)
if err != nil {
return nil, fmt.Errorf("Checking file '%s'", file)
}
if fileInfo.IsDir() {
if !recursive {
return nil, fmt.Errorf("Expected file '%s' to not be a directory", file)
}
var paths []string
err := filepath.Walk(file, func(path string, fi os.FileInfo, err error) error {
if err != nil || fi.IsDir() {
return err
}
ext := filepath.Ext(path)
for _, allowedExt := range fileResourcesAllowedExts {
if allowedExt == ext {
paths = append(paths, path)
}
}
return nil
})
if err != nil {
return nil, fmt.Errorf("Listing files '%s'", file)
}
sort.Strings(paths)
for _, path := range paths {
fileRs = append(fileRs, FileResource{NewLocalFileSource(path)})
}
} else {
fileRs = append(fileRs, FileResource{NewLocalFileSource(file)})
}
}
return fileRs, nil
}
func (r FileResource) Description() string { return r.fileSrc.Description() }
func (r FileResource) Resources() ([]Resource, error) {
docs, err := NewYAMLFile(r.fileSrc).Docs()
if err != nil {
return nil, err
}
var resources []Resource
for _, doc := range docs {
rs, err := NewResourcesFromBytes(doc)
if err != nil {
return nil, err
}
resources = append(resources, rs...)
}
return resources, nil
}