-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclasses.go
91 lines (75 loc) · 1.82 KB
/
classes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"regexp"
"strings"
)
var keynames = []string{"items", "species"}
var whitespace = regexp.MustCompile(`\s+`)
var cSuffix = regexp.MustCompile(`_C$`)
type classSpec struct {
Name string `json:"name"`
Blueprint string `json:"bp"`
}
type Class struct {
Name string
Id int
}
type ClassMap struct {
Map map[string]Class
nextId int
}
func (cm *ClassMap) Get(bpName string) *Class {
if class, ok := cm.Map[bpName]; ok {
return &class
}
return nil
}
func (cm *ClassMap) Add(bpName string) *Class {
class := Class{
Name: cSuffix.ReplaceAllString(bpName, ""),
Id: cm.nextId,
}
cm.Map[bpName] = class
cm.nextId++
return &class
}
func readSpecFiles(paths ...string) (*ClassMap, error) {
classCount := 1 // leave 0 for "none"
classNames := make(map[string]Class)
for _, path := range paths {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("Opening spec file %f:\n%w", path, err)
}
jsonData, err := io.ReadAll(f)
if err != nil {
return nil, fmt.Errorf("Reading spec file %f:\n%w", path, err)
}
var values map[string]json.RawMessage
if err := json.Unmarshal(jsonData, &values); err != nil {
return nil, fmt.Errorf("Loading spec file %f:\n%w", path, err)
}
for _, key := range keynames {
if raw, ok := values[key]; ok {
var specs []classSpec
if err := json.Unmarshal(raw, &specs); err != nil {
return nil, fmt.Errorf("Loading specs from file %f:\n%w", path, err)
}
for _, spec := range specs {
parts := strings.Split(spec.Blueprint, ".")
className := parts[len(parts)-1]
classNames[className] = Class{
Name: whitespace.ReplaceAllString(spec.Name, " "),
Id: classCount,
}
classCount++
}
}
}
}
return &ClassMap{Map: classNames, nextId: classCount}, nil
}