diff options
| author | historia <[not public]> | 2026-06-25 15:40:48 -0400 |
|---|---|---|
| committer | historia <[not public]> | 2026-06-25 15:40:48 -0400 |
| commit | abd612c15799f604e671e83dc7c410ed2b44185f (patch) | |
| tree | 0597ca92350de73aac2a7cf26b2f2d6595dac0cc /internal/item/store.go | |
| parent | 2725e2927a1595c7b100d942d1f14146252adeb7 (diff) | |
| download | thehouseoficarus-abd612c15799f604e671e83dc7c410ed2b44185f.tar.gz | |
slop refactor
Diffstat (limited to 'internal/item/store.go')
| -rw-r--r-- | internal/item/store.go | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/internal/item/store.go b/internal/item/store.go new file mode 100644 index 0000000..d73d6fe --- /dev/null +++ b/internal/item/store.go @@ -0,0 +1,78 @@ +package item + +import ( + "fmt" + "os" + "path/filepath" + + "gopkg.in/yaml.v3" + "thehouseoficarus/internal/behavior" +) + +type ItemStore struct { + dataDir string + pathIndex map[string]string + cache map[string]*ItemDef +} + +func NewItemStore(dataDir string) *ItemStore { + s := &ItemStore{ + dataDir: dataDir, + pathIndex: behavior.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, 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) + } + var def ItemDef + if err := yaml.Unmarshal(data, &def); err != nil { + return nil, fmt.Errorf("parse item %s: %w", id, err) + } + def.ID = id + s.cache[id] = &def + return &def, nil +} + +func (s *ItemStore) LoadAll() ([]*ItemDef, error) { + dir := filepath.Join(s.dataDir, "items") + var defs []*ItemDef + err := behavior.WalkYAMLDir(dir, func(path, id string, data []byte) error { + if def, ok := s.cache[id]; ok { + defs = append(defs, def) + return nil + } + var def ItemDef + if err := yaml.Unmarshal(data, &def); err != nil { + return fmt.Errorf("parse item %s: %w", id, err) + } + def.ID = id + 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 ids +} |
