-
Notifications
You must be signed in to change notification settings - Fork 123
/
filesystem.go
233 lines (189 loc) · 5.88 KB
/
filesystem.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Copyright 2021-2023 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
package util
import (
"archive/zip"
"compress/gzip"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/nlepage/go-tarfs"
"go.uber.org/multierr"
"google.golang.org/protobuf/proto"
)
var supportedFileTypes = map[string]struct{}{".yaml": {}, ".yml": {}, ".json": {}}
var ErrNoMatchingFiles = errors.New("no matching files")
// SchemasDirectory is the name of the special directory containing schemas. It is defined here to avoid an import loop.
const SchemasDirectory = "_schemas"
// TestDataDirectory is the name of the special directory containing test fixtures. It is defined here to avoid an import loop.
const TestDataDirectory = "testdata"
// IsSupportedTestFile return true if the given file is a supported test file name, i.e. "*_test.{yaml,yml,json}".
func IsSupportedTestFile(fileName string) bool {
if ext, ok := IsSupportedFileTypeExt(fileName); ok {
f := strings.ToLower(fileName)
return strings.HasSuffix(f[:len(f)-len(ext)], "_test")
}
return false
}
// IsSupportedFileTypeExt returns true and a file extension if the given file has a supported file extension.
func IsSupportedFileTypeExt(fileName string) (string, bool) {
ext := strings.ToLower(filepath.Ext(fileName))
_, exists := supportedFileTypes[ext]
return ext, exists
}
// IsJSONFileTypeExt returns true if the given file has a json file extension.
func IsJSONFileTypeExt(fileName string) bool {
ext := strings.ToLower(filepath.Ext(fileName))
return ext == ".json"
}
// IsSupportedFileType returns true if the given file has a supported file extension.
func IsSupportedFileType(fileName string) bool {
_, ok := IsSupportedFileTypeExt(fileName)
return ok
}
func IsHidden(fileName string) bool {
switch fileName {
case ".", "..":
return false
default:
return strings.HasPrefix(fileName, ".")
}
}
func IsZip(fileName string) bool {
return strings.HasSuffix(fileName, ".zip")
}
func IsTar(fileName string) bool {
return strings.HasSuffix(fileName, ".tar")
}
func IsGzip(fileName string) bool {
return strings.HasSuffix(fileName, ".tar.gz") || strings.HasSuffix(fileName, ".tgz")
}
func IsArchiveFile(fileName string) bool {
return IsZip(fileName) || IsTar(fileName) || IsGzip(fileName)
}
func getFsFromTar(r io.Reader, closers ...io.Closer) (fs.FS, error) {
tfs, err := tarfs.New(r)
if err != nil {
for _, c := range closers {
_ = c.Close()
}
return nil, fmt.Errorf("failed to open tar file: %w", err)
}
return ClosableFS{FS: tfs, closers: closers}, nil
}
type ClosableFS struct {
fs.FS
io.Closer
closers []io.Closer
}
func (cfs ClosableFS) Close() (outErr error) {
for _, c := range cfs.closers {
outErr = multierr.Append(outErr, c.Close())
}
return outErr
}
// OpenDirectoryFS attempts to open a directory FS at the given location. It'll initially check if the target file is an archive,
// and if so, will return the appropriate type which implements the fs.FS interface.
func OpenDirectoryFS(path string) (fs.FS, error) {
// We don't use `switch filepath.Ext(path)` here because it only suffixes from the final `.`, so `.tar.gz` won't be
// correctly handled
switch {
case IsZip(path):
zr, err := zip.OpenReader(path)
if err != nil {
return nil, fmt.Errorf("failed to open zip file: %w", err)
}
return ClosableFS{FS: zr, closers: []io.Closer{zr}}, nil
case IsTar(path):
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("failed to open tar file: %w", err)
}
return getFsFromTar(f, f)
case IsGzip(path):
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("failed to open gzip file: %w", err)
}
gzr, err := gzip.NewReader(f)
if err != nil {
_ = f.Close()
return nil, fmt.Errorf("failed to open gzip file: %w", err)
}
return getFsFromTar(gzr, gzr, f)
}
return os.DirFS(path), nil
}
// LoadFromJSONOrYAML reads a JSON or YAML encoded protobuf from the given path.
func LoadFromJSONOrYAML(fsys fs.FS, path string, dest proto.Message) error {
f, err := fsys.Open(path)
if err != nil {
return fmt.Errorf("failed to open %s: %w", path, err)
}
defer f.Close()
return ReadJSONOrYAML(f, dest)
}
// OpenOneOfSupportedFiles attempts to open a fileName adding supported extensions.
func OpenOneOfSupportedFiles(fsys fs.FS, fileName string) (fs.File, error) {
matches, err := fs.Glob(fsys, fileName+".*")
if err != nil {
return nil, err
}
var filepath string
for _, match := range matches {
if IsSupportedFileType(match) {
filepath = match
break
}
}
if filepath == "" {
return nil, ErrNoMatchingFiles
}
file, err := fsys.Open(filepath)
if err != nil {
return nil, err
}
return file, nil
}
type IndexedFileType uint8
const (
FileTypeNotIndexed IndexedFileType = iota
FileTypePolicy
FileTypeSchema
)
// FileType categorizes the given path according to how it will be treated by the index.
// The path must be "/"-separated and relative to the root policies directory.
func FileType(path string) IndexedFileType {
segments := strings.Split(path, "/")
fileName := segments[len(segments)-1]
inSchemas := segments[0] == SchemasDirectory
for _, segment := range segments {
if IsHidden(segment) || (segment == TestDataDirectory && !inSchemas) {
return FileTypeNotIndexed
}
}
if inSchemas {
if IsJSONFileTypeExt(fileName) {
return FileTypeSchema
}
return FileTypeNotIndexed
}
if IsSupportedFileType(fileName) && !IsSupportedTestFile(fileName) {
return FileTypePolicy
}
return FileTypeNotIndexed
}
// RelativeSchemaPath returns the given path within the top-level schemas directory,
// and a flag to indicate whether the path was actually contained in that directory.
// The path must be "/"-separated and relative to the root policies directory.
func RelativeSchemaPath(path string) (string, bool) {
schemaPath := strings.TrimPrefix(path, SchemasDirectory+"/")
if schemaPath == path {
return "", false
}
return schemaPath, true
}