anpi/parser/parser.go (view raw)
| 1 | package parser |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | |
| 6 | "gopkg.in/yaml.v3" |
| 7 | ) |
| 8 | |
| 9 | type DeckImport struct { |
| 10 | Deck string `yaml:"deck"` |
| 11 | Type string `yaml:"type"` |
| 12 | Tags []string `yaml:"tags"` |
| 13 | Fields map[string]string `yaml:"fields"` |
| 14 | Notes []Note `yaml:"notes"` |
| 15 | } |
| 16 | |
| 17 | type Note struct { |
| 18 | Fields map[string]string |
| 19 | Tags []string |
| 20 | } |
| 21 | |
| 22 | func (n *Note) UnmarshalYAML(value *yaml.Node) error { |
| 23 | var raw map[string]any |
| 24 | if err := value.Decode(&raw); err != nil { |
| 25 | return err |
| 26 | } |
| 27 | |
| 28 | n.Fields = make(map[string]string) |
| 29 | for k, v := range raw { |
| 30 | if k == "tags" { |
| 31 | if tags, ok := v.([]string); ok { |
| 32 | n.Tags = append(n.Tags, tags...) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | if str, ok := v.(string); ok { |
| 37 | n.Fields[k] = str |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | return nil |
| 42 | } |
| 43 | |
| 44 | func (d *DeckImport) Validate() error { |
| 45 | return nil |
| 46 | } |
| 47 | |
| 48 | func Parse(inp []byte) ([]DeckImport, error) { |
| 49 | var listRes []DeckImport |
| 50 | if err := yaml.Unmarshal(inp, &listRes); err == nil { |
| 51 | return listRes, nil |
| 52 | } |
| 53 | |
| 54 | var single DeckImport |
| 55 | if err := yaml.Unmarshal(inp, &single); err == nil { |
| 56 | return []DeckImport{single}, nil |
| 57 | } |
| 58 | |
| 59 | return nil, fmt.Errorf("invalid file format") |
| 60 | } |