/
schema.go
70 lines (56 loc) · 1.31 KB
/
schema.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
// Copyright 2021-2024 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
package index
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"path/filepath"
"github.com/cerbos/cerbos/internal/schema"
"github.com/cerbos/cerbos/internal/util"
)
type SchemaLoader struct {
err error
fsys fs.FS
}
func NewSchemaLoader(fsys fs.FS, rootDir string) *SchemaLoader {
schemaDir := filepath.Join(rootDir, schema.Directory)
schemaFS, err := fs.Sub(fsys, schemaDir)
if err != nil {
return &SchemaLoader{err: err}
}
return &SchemaLoader{fsys: schemaFS}
}
func (sl *SchemaLoader) ListIDs(_ context.Context) ([]string, error) {
var schemaIDs []string
err := fs.WalkDir(sl.fsys, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return fs.SkipDir
}
return err
}
if d.IsDir() {
if util.IsHidden(d.Name()) {
return fs.SkipDir
}
return nil
}
if !util.IsHidden(d.Name()) && util.IsJSONFileTypeExt(d.Name()) {
schemaIDs = append(schemaIDs, path)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to walk schemas directory: %w", err)
}
return schemaIDs, nil
}
func (sl *SchemaLoader) Load(_ context.Context, id string) (io.ReadCloser, error) {
if sl.err != nil {
return nil, sl.err
}
return sl.fsys.Open(id)
}