forked from norwoodj/helm-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiles.go
136 lines (108 loc) · 2.3 KB
/
files.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
134
135
136
package document
import (
"encoding/base64"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/gobwas/glob"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
// Near identical to https://github.com/helm/helm/blob/main/pkg/engine/files.go as to preserve the interface.
type fileEntry struct {
Path string
data []byte
}
func (f *fileEntry) GetData() []byte {
if f.data == nil {
data, err := ioutil.ReadFile(f.Path)
if err != nil {
log.Warnf("Error reading file contents for %s: %s", f.Path, err.Error())
return []byte{}
}
f.data = data
}
return f.data
}
type files map[string]*fileEntry
func getFiles(dir string) (files, error) {
result := make(files)
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
result[path] = &fileEntry{Path: path}
return nil
})
if err != nil {
return map[string]*fileEntry{}, err
}
return result, nil
}
func (f files) GetBytes(name string) []byte {
if v, ok := f[name]; ok {
return v.GetData()
}
return []byte{}
}
func (f files) Get(name string) string {
return string(f.GetBytes(name))
}
func (f files) Glob(pattern string) files {
result := make(files)
g, err := glob.Compile(pattern, '/')
if err != nil {
log.Warnf("Error compiling Glob patten %s: %s", pattern, err.Error())
return result
}
for filePath, entry := range f {
if g.Match(filePath) {
result[filePath] = entry
}
}
return result
}
func (f files) AsConfig() string {
if f == nil {
return ""
}
m := make(map[string]string)
// Explicitly convert to strings, and file names
for k, v := range f {
m[path.Base(k)] = string(v.GetData())
}
return toYAML(m)
}
func (f files) AsSecrets() string {
if f == nil {
return ""
}
m := make(map[string]string)
for k, v := range f {
m[path.Base(k)] = base64.StdEncoding.EncodeToString(v.GetData())
}
return toYAML(m)
}
func (f files) Lines(path string) []string {
if f == nil {
return []string{}
}
entry, exists := f[path]
if !exists {
return []string{}
}
return strings.Split(string(entry.GetData()), "\n")
}
func toYAML(v interface{}) string {
data, err := yaml.Marshal(v)
if err != nil {
// Swallow errors inside a template.
return ""
}
return strings.TrimSuffix(string(data), "\n")
}