-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
rolodex_file_loader.go
395 lines (339 loc) · 9.8 KB
/
rolodex_file_loader.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT
package index
import (
"fmt"
"github.com/pb33f/libopenapi/datamodel"
"golang.org/x/sync/syncmap"
"gopkg.in/yaml.v3"
"io"
"io/fs"
"log/slog"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
)
// LocalFS is a file system that indexes local files.
type LocalFS struct {
fsConfig *LocalFSConfig
indexConfig *SpecIndexConfig
entryPointDirectory string
baseDirectory string
Files syncmap.Map
extractedFiles map[string]RolodexFile
logger *slog.Logger
fileLock sync.Mutex
readingErrors []error
}
// GetFiles returns the files that have been indexed. A map of RolodexFile objects keyed by the full path of the file.
func (l *LocalFS) GetFiles() map[string]RolodexFile {
files := make(map[string]RolodexFile)
l.Files.Range(func(key, value interface{}) bool {
files[key.(string)] = value.(*LocalFile)
return true
})
l.extractedFiles = files
return files
}
// GetErrors returns any errors that occurred during the indexing process.
func (l *LocalFS) GetErrors() []error {
return l.readingErrors
}
// Open opens a file, returning it or an error. If the file is not found, the error is of type *PathError.
func (l *LocalFS) Open(name string) (fs.File, error) {
if l.indexConfig != nil && !l.indexConfig.AllowFileLookup {
return nil, &fs.PathError{Op: "open", Path: name,
Err: fmt.Errorf("file lookup for '%s' not allowed, set the index configuration "+
"to AllowFileLookup to be true", name)}
}
if !filepath.IsAbs(name) {
name, _ = filepath.Abs(filepath.Join(l.baseDirectory, name))
}
if f, ok := l.Files.Load(name); ok {
return f.(*LocalFile), nil
} else {
if l.fsConfig != nil && l.fsConfig.DirFS == nil {
var extractedFile *LocalFile
var extErr error
// attempt to open the file from the local filesystem
extractedFile, extErr = l.extractFile(name)
if extErr != nil {
return nil, extErr
}
if extractedFile != nil {
// in this mode, we need the index config to be set.
if l.indexConfig != nil {
copiedCfg := *l.indexConfig
copiedCfg.SpecAbsolutePath = name
copiedCfg.AvoidBuildIndex = true
idx, idxError := extractedFile.Index(&copiedCfg)
if idxError != nil && idx == nil {
extractedFile.readingErrors = append(l.readingErrors, idxError)
} else {
// for each index, we need a resolver
resolver := NewResolver(idx)
idx.resolver = resolver
idx.BuildIndex()
}
if len(extractedFile.data) > 0 {
l.logger.Debug("successfully loaded and indexed file", "file", name)
}
return extractedFile, nil
}
}
}
}
return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist}
}
// LocalFile is a file that has been indexed by the LocalFS. It implements the RolodexFile interface.
type LocalFile struct {
filename string
name string
extension FileExtension
data []byte
fullPath string
lastModified time.Time
readingErrors []error
index *SpecIndex
parsed *yaml.Node
offset int64
}
// GetIndex returns the *SpecIndex for the file.
func (l *LocalFile) GetIndex() *SpecIndex {
return l.index
}
// Index returns the *SpecIndex for the file. If the index has not been created, it will be created (indexed)
func (l *LocalFile) Index(config *SpecIndexConfig) (*SpecIndex, error) {
if l.index != nil {
return l.index, nil
}
content := l.data
// first, we must parse the content of the file
info, err := datamodel.ExtractSpecInfoWithDocumentCheck(content, true)
if err != nil {
return nil, err
}
index := NewSpecIndexWithConfig(info.RootNode, config)
index.specAbsolutePath = l.fullPath
l.index = index
return index, nil
}
// GetContent returns the content of the file as a string.
func (l *LocalFile) GetContent() string {
return string(l.data)
}
// GetContentAsYAMLNode returns the content of the file as a *yaml.Node. If something went wrong
// then an error is returned.
func (l *LocalFile) GetContentAsYAMLNode() (*yaml.Node, error) {
if l.parsed != nil {
return l.parsed, nil
}
if l.index != nil && l.index.root != nil {
return l.index.root, nil
}
if l.data == nil {
return nil, fmt.Errorf("no data to parse for file: %s", l.fullPath)
}
var root yaml.Node
err := yaml.Unmarshal(l.data, &root)
if err != nil {
return nil, err
}
if l.index != nil && l.index.root == nil {
l.index.root = &root
}
l.parsed = &root
return &root, nil
}
// GetFileExtension returns the FileExtension of the file.
func (l *LocalFile) GetFileExtension() FileExtension {
return l.extension
}
// GetFullPath returns the full path of the file.
func (l *LocalFile) GetFullPath() string {
return l.fullPath
}
// GetErrors returns any errors that occurred during the indexing process.
func (l *LocalFile) GetErrors() []error {
return l.readingErrors
}
// FullPath returns the full path of the file.
func (l *LocalFile) FullPath() string {
return l.fullPath
}
// Name returns the name of the file.
func (l *LocalFile) Name() string {
return l.name
}
// Size returns the size of the file.
func (l *LocalFile) Size() int64 {
return int64(len(l.data))
}
// Mode returns the file mode bits for the file.
func (l *LocalFile) Mode() fs.FileMode {
return fs.FileMode(0)
}
// ModTime returns the modification time of the file.
func (l *LocalFile) ModTime() time.Time {
return l.lastModified
}
// IsDir returns true if the file is a directory, it always returns false
func (l *LocalFile) IsDir() bool {
return false
}
// Sys returns the underlying data source (always returns nil)
func (l *LocalFile) Sys() interface{} {
return nil
}
// Close closes the file (doesn't do anything, returns no error)
func (l *LocalFile) Close() error {
return nil
}
// Stat returns the FileInfo for the file.
func (l *LocalFile) Stat() (fs.FileInfo, error) {
return l, nil
}
// Read reads the file into a byte slice, makes it compatible with io.Reader.
func (l *LocalFile) Read(b []byte) (int, error) {
if l.offset >= int64(len(l.GetContent())) {
return 0, io.EOF
}
if l.offset < 0 {
return 0, &fs.PathError{Op: "read", Path: l.GetFullPath(), Err: fs.ErrInvalid}
}
n := copy(b, l.GetContent()[l.offset:])
l.offset += int64(n)
return n, nil
}
// LocalFSConfig is the configuration for the LocalFS.
type LocalFSConfig struct {
// the base directory to index
BaseDirectory string
// supply your own logger
Logger *slog.Logger
// supply a list of specific files to index only
FileFilters []string
// supply a custom fs.FS to use
DirFS fs.FS
// supply an index configuration to use
IndexConfig *SpecIndexConfig
}
// NewLocalFSWithConfig creates a new LocalFS with the supplied configuration.
func NewLocalFSWithConfig(config *LocalFSConfig) (*LocalFS, error) {
var allErrors []error
log := config.Logger
if log == nil {
log = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelError,
}))
}
// if the basedir is an absolute file, we're just going to index that file.
ext := filepath.Ext(config.BaseDirectory)
file := filepath.Base(config.BaseDirectory)
var absBaseDir string
absBaseDir, _ = filepath.Abs(config.BaseDirectory)
localFS := &LocalFS{
indexConfig: config.IndexConfig,
fsConfig: config,
logger: log,
baseDirectory: absBaseDir,
entryPointDirectory: config.BaseDirectory,
}
// if a directory filesystem is supplied, use that to walk the directory and pick up everything it finds.
if config.DirFS != nil {
walkErr := fs.WalkDir(config.DirFS, ".", func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
// we don't care about directories, or errors, just read everything we can.
if d.IsDir() {
return nil
}
if len(ext) > 2 && p != file {
return nil
}
if strings.HasPrefix(p, ".") {
return nil
}
if len(config.FileFilters) > 0 {
if !slices.Contains(config.FileFilters, p) {
return nil
}
}
_, fErr := localFS.extractFile(p)
return fErr
})
if walkErr != nil {
return nil, walkErr
}
}
localFS.readingErrors = allErrors
return localFS, nil
}
func (l *LocalFS) extractFile(p string) (*LocalFile, error) {
extension := ExtractFileType(p)
var readingErrors []error
abs := p
config := l.fsConfig
if !filepath.IsAbs(p) {
if config != nil && config.BaseDirectory != "" {
abs, _ = filepath.Abs(filepath.Join(config.BaseDirectory, p))
} else {
abs, _ = filepath.Abs(p)
}
}
var fileData []byte
switch extension {
case YAML, JSON:
var file fs.File
var fileError error
if config != nil && config.DirFS != nil {
file, _ = config.DirFS.Open(p)
} else {
file, fileError = os.Open(abs)
}
// if reading without a directory FS, error out on any error, do not continue.
if fileError != nil {
readingErrors = append(readingErrors, fileError)
return nil, fileError
}
modTime := time.Now()
stat, _ := file.Stat()
if stat != nil {
modTime = stat.ModTime()
}
fileData, _ = io.ReadAll(file)
if config != nil && config.DirFS != nil {
l.logger.Debug("collecting JSON/YAML file", "file", abs)
} else {
l.logger.Debug("parsing file", "file", abs)
}
lf := &LocalFile{
filename: p,
name: filepath.Base(p),
extension: ExtractFileType(p),
data: fileData,
fullPath: abs,
lastModified: modTime,
readingErrors: readingErrors,
}
l.Files.Store(abs, lf)
return lf, nil
case UNSUPPORTED:
if config != nil && config.DirFS != nil {
l.logger.Debug("skipping non JSON/YAML file", "file", abs)
}
}
return nil, nil
}
// NewLocalFS creates a new LocalFS with the supplied base directory.
func NewLocalFS(baseDir string, dirFS fs.FS) (*LocalFS, error) {
config := &LocalFSConfig{
BaseDirectory: baseDir,
DirFS: dirFS,
}
return NewLocalFSWithConfig(config)
}