Skip to content

Commit

Permalink
helper for loading schemas from an embed.FS
Browse files Browse the repository at this point in the history
  • Loading branch information
bnewbold committed Dec 24, 2024
1 parent a8f53f6 commit b50b014
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions atproto/lexicon/catalog.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package lexicon

import (
"embed"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -46,6 +47,9 @@ func (c *BaseCatalog) Resolve(ref string) (*Schema, error) {

// Inserts a schema loaded from a JSON file in to the catalog.
func (c *BaseCatalog) AddSchemaFile(sf SchemaFile) error {
if sf.Lexicon != 1 {
return fmt.Errorf("unsupported lexicon language version: %d", sf.Lexicon)
}
base := sf.ID
for frag, def := range sf.Defs {
if len(frag) == 0 || strings.Contains(frag, "#") || strings.Contains(frag, ".") {
Expand Down Expand Up @@ -114,3 +118,38 @@ func (c *BaseCatalog) LoadDirectory(dirPath string) error {
return nil
})
}

// Recursively loads all '.json' files from an embed.FS
func (c *BaseCatalog) LoadEmbedFS(efs embed.FS) error {
return fs.WalkDir(efs, ".", func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if !strings.HasSuffix(p, ".json") {
return nil
}
slog.Debug("loading Lexicon schema JSON from static embed", "path", p)
f, err := os.Open(p)
if err != nil {
return err
}
defer func() { _ = f.Close() }()

b, err := io.ReadAll(f)
if err != nil {
return err
}

var sf SchemaFile
if err = json.Unmarshal(b, &sf); err != nil {
return err
}
if err = c.AddSchemaFile(sf); err != nil {
return err
}
return nil
})
}

0 comments on commit b50b014

Please # to comment.