diff options
Diffstat (limited to 'internal/object/item_store.go')
| -rw-r--r-- | internal/object/item_store.go | 56 |
1 files changed, 36 insertions, 20 deletions
diff --git a/internal/object/item_store.go b/internal/object/item_store.go index 9e932ba..d75179f 100644 --- a/internal/object/item_store.go +++ b/internal/object/item_store.go @@ -4,28 +4,34 @@ import ( "fmt" "os" "path/filepath" - "strings" + "thehouseoficarus/internal/action" "gopkg.in/yaml.v3" ) type ItemStore struct { - dataDir string - cache map[string]*ItemDef + dataDir string + pathIndex map[string]string + cache map[string]*ItemDef } func NewItemStore(dataDir string) *ItemStore { - return &ItemStore{ - dataDir: dataDir, - cache: make(map[string]*ItemDef), + s := &ItemStore{ + dataDir: dataDir, + pathIndex: action.BuildPathIndex(filepath.Join(dataDir, "items")), + cache: make(map[string]*ItemDef), } + return s } func (s *ItemStore) Load(id string) (*ItemDef, error) { if def, ok := s.cache[id]; ok { return def, nil } - path := filepath.Join(s.dataDir, "items", id+".yaml") + path, ok := s.pathIndex[id] + if !ok { + return nil, fmt.Errorf("read item %s: no such item", id) + } data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("read item %s: %w", id, err) @@ -40,21 +46,31 @@ func (s *ItemStore) Load(id string) (*ItemDef, error) { func (s *ItemStore) LoadAll() ([]*ItemDef, error) { dir := filepath.Join(s.dataDir, "items") - entries, err := os.ReadDir(dir) - if err != nil { - return nil, err - } var defs []*ItemDef - for _, e := range entries { - if e.IsDir() || filepath.Ext(e.Name()) != ".yaml" { - continue + err := action.WalkYAMLDir(dir, func(path, id string, data []byte) error { + if def, ok := s.cache[id]; ok { + defs = append(defs, def) + return nil } - id := strings.TrimSuffix(e.Name(), ".yaml") - def, err := s.Load(id) - if err != nil { - continue + var def ItemDef + if err := yaml.Unmarshal(data, &def); err != nil { + return nil } - defs = append(defs, def) + s.cache[id] = &def + defs = append(defs, &def) + return nil + }) + return defs, err +} + +func (s *ItemStore) PathIndex() map[string]string { + return s.pathIndex +} + +func (s *ItemStore) IDSet() map[string]bool { + ids := make(map[string]bool) + for id := range s.pathIndex { + ids[id] = true } - return defs, nil + return ids } |
