-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.go
More file actions
76 lines (69 loc) · 1.97 KB
/
Copy pathloader.go
File metadata and controls
76 lines (69 loc) · 1.97 KB
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
package gatekit
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"time"
)
// loadedSource pairs a parsed Source with the file-level facts Evaluate
// needs but that don't belong in the JSON schema itself: the file's own
// mtime (the freshness signal a module cannot lie about) and whether it
// parsed at all.
type loadedSource struct {
Source
mtime time.Time
parsed bool
warning string // set when parsed is false, or the module field mismatches
}
// loadSources reads every sources/*.json file in dir. A file that fails to
// parse is never fatal to the whole Evaluate call -- it becomes a
// loadedSource with parsed=false, zero items, and a warning, so one broken
// module can never take down every other module's reporting.
func loadSources(dir string) ([]loadedSource, error) {
entries, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
var out []loadedSource
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") {
continue
}
path := filepath.Join(dir, e.Name())
stem := strings.TrimSuffix(e.Name(), ".json")
info, err := e.Info()
if err != nil {
continue // vanished between ReadDir and Info; next Evaluate will see it or not
}
ls := loadedSource{mtime: info.ModTime()}
b, err := os.ReadFile(path)
if err != nil {
ls.Module = stem
ls.warning = stem + ": could not read source file: " + err.Error()
out = append(out, ls)
continue
}
var s Source
if err := json.Unmarshal(b, &s); err != nil {
ls.Module = stem
ls.warning = stem + ": could not parse source file: " + err.Error()
out = append(out, ls)
continue
}
ls.Source = s
ls.parsed = true
if s.Module == "" {
ls.Module = stem
} else if s.Module != stem {
ls.warning = "source file " + e.Name() + " declares module \"" + s.Module +
"\", which does not match its filename; grouping by filename"
ls.Module = stem
}
out = append(out, ls)
}
return out, nil
}