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 Jan 7, 2025
1 parent 98c6f96 commit 6ac44d9
Showing 1 changed file with 42 additions and 30 deletions.
72 changes: 42 additions & 30 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 @@ -80,37 +84,45 @@ func (c *BaseCatalog) AddSchemaFile(sf SchemaFile) error {
return nil
}

// internal helper for loading file paths (either real filesystem or embed.FS)
func (c *BaseCatalog) addDirEntry(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 file", "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
}

// Recursively loads all '.json' files from a directory in to the catalog.
func (c *BaseCatalog) LoadDirectory(dirPath string) error {
return filepath.WalkDir(dirPath, 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 file", "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
}
return filepath.WalkDir(dirPath, c.addDirEntry)
}

var sf SchemaFile
if err = json.Unmarshal(b, &sf); err != nil {
return err
}
if err = c.AddSchemaFile(sf); err != nil {
return err
}
return nil
})
// Recursively loads all '.json' files from an embed.FS
func (c *BaseCatalog) LoadEmbedFS(efs embed.FS) error {
return fs.WalkDir(efs, ".", c.addDirEntry)
}

0 comments on commit 6ac44d9

Please sign in to comment.