From b50b0146375940ec8e2cddfbcd01059378b3e182 Mon Sep 17 00:00:00 2001 From: bryan newbold Date: Mon, 23 Dec 2024 18:04:39 -0800 Subject: [PATCH] helper for loading schemas from an embed.FS --- atproto/lexicon/catalog.go | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/atproto/lexicon/catalog.go b/atproto/lexicon/catalog.go index 524ef81a..cff5f25c 100644 --- a/atproto/lexicon/catalog.go +++ b/atproto/lexicon/catalog.go @@ -1,6 +1,7 @@ package lexicon import ( + "embed" "encoding/json" "fmt" "io" @@ -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, ".") { @@ -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 + }) +}