Skip to content

Commit a9aea14

Browse files
compiler: add ResourceExistsError
1 parent 610eb82 commit a9aea14

File tree

2 files changed

+47
-6
lines changed

2 files changed

+47
-6
lines changed

compiler.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,12 @@ func (c *Compiler) AddResource(url string, doc any) error {
122122
if err != nil {
123123
return err
124124
}
125-
c.roots.loader.add(uf.url, doc)
125+
if isMeta(string(uf.url)) {
126+
return &ResourceExistsError{string(uf.url)}
127+
}
128+
if !c.roots.loader.add(uf.url, doc) {
129+
return &ResourceExistsError{string(uf.url)}
130+
}
126131
return nil
127132
}
128133

loader.go

+41-5
Original file line numberDiff line numberDiff line change
@@ -78,14 +78,14 @@ func (l SchemeURLLoader) Load(url string) (any, error) {
7878
//go:embed metaschemas
7979
var metaFS embed.FS
8080

81-
func loadMeta(url string) (any, error) {
81+
func openMeta(url string) (fs.File, error) {
8282
u, meta := strings.CutPrefix(url, "http://json-schema.org/")
8383
if !meta {
8484
u, meta = strings.CutPrefix(url, "https://json-schema.org/")
8585
}
8686
if meta {
8787
if u == "schema" {
88-
return loadMeta(draftLatest.url)
88+
return openMeta(draftLatest.url)
8989
}
9090
f, err := metaFS.Open("metaschemas/" + u)
9191
if err != nil {
@@ -94,9 +94,34 @@ func loadMeta(url string) (any, error) {
9494
}
9595
return nil, err
9696
}
97-
return UnmarshalJSON(f)
97+
return f, err
9898
}
9999
return nil, nil
100+
101+
}
102+
103+
func isMeta(url string) bool {
104+
f, err := openMeta(url)
105+
if err != nil {
106+
return true
107+
}
108+
if f != nil {
109+
f.Close()
110+
return true
111+
}
112+
return false
113+
}
114+
115+
func loadMeta(url string) (any, error) {
116+
f, err := openMeta(url)
117+
if err != nil {
118+
return nil, err
119+
}
120+
if f == nil {
121+
return nil, nil
122+
}
123+
defer f.Close()
124+
return UnmarshalJSON(f)
100125
}
101126

102127
// --
@@ -106,11 +131,12 @@ type defaultLoader struct {
106131
loader URLLoader
107132
}
108133

109-
func (l *defaultLoader) add(url url, doc any) {
134+
func (l *defaultLoader) add(url url, doc any) bool {
110135
if _, ok := l.docs[url]; ok {
111-
return
136+
return false
112137
}
113138
l.docs[url] = doc
139+
return true
114140
}
115141

116142
func (l *defaultLoader) load(url url) (any, error) {
@@ -214,6 +240,16 @@ func (e *UnsupportedURLSchemeError) Error() string {
214240

215241
// --
216242

243+
type ResourceExistsError struct {
244+
url string
245+
}
246+
247+
func (e *ResourceExistsError) Error() string {
248+
return fmt.Sprintf("resource for %q already exists", e.url)
249+
}
250+
251+
// --
252+
217253
// UnmarshalJSON unmarshals into [any] without losing
218254
// number precision using [json.Number].
219255
func UnmarshalJSON(r io.Reader) (any, error) {

0 commit comments

Comments
 (0)