all repos

anpi @ 1a0c16f

yaml to anki importer

anpi/parser/parser.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
fix linter errors, 1 year ago
1
package parser
2
3
import (
4
	"errors"
5
	"maps"
6
7
	"gopkg.in/yaml.v3"
8
)
9
10
type DeckImport struct {
11
	Deck   string            `yaml:"deck"`
12
	Type   string            `yaml:"type"`
13
	Tags   []string          `yaml:"tags"`
14
	Fields map[string]string `yaml:"fields"`
15
	Notes  []Note            `yaml:"notes"`
16
17
	// fieldLookUp internal reserve mapping of [Fields]
18
	fieldLookUp map[string]string
19
}
20
21
func (d *DeckImport) FieldLookUp(field string) string {
22
	// TODO: use ok notation here
23
24
	val := d.fieldLookUp[field]
25
	return val
26
}
27
28
func (d *DeckImport) Validate() error {
29
	return nil
30
}
31
32
func (d *DeckImport) buildLookUpTable() {
33
	d.fieldLookUp = make(map[string]string)
34
	maps.Copy(d.Fields, d.fieldLookUp)
35
}
36
37
type Note struct {
38
	Fields map[string]string
39
	Tags   []string
40
}
41
42
func (n *Note) UnmarshalYAML(value *yaml.Node) error {
43
	var raw map[string]any
44
	if err := value.Decode(&raw); err != nil {
45
		return err
46
	}
47
48
	n.Fields = make(map[string]string)
49
	for k, v := range raw {
50
		if k == "tags" {
51
			if tags, ok := v.([]string); ok {
52
				n.Tags = append(n.Tags, tags...)
53
			}
54
		}
55
56
		if str, ok := v.(string); ok {
57
			n.Fields[k] = str
58
		}
59
	}
60
61
	return nil
62
}
63
64
var ErrInvalidFileFormat = errors.New("invalid file format")
65
66
func Parse(inp []byte) ([]DeckImport, error) {
67
	var listRes []DeckImport
68
	if err := yaml.Unmarshal(inp, &listRes); err == nil {
69
		for i := range listRes {
70
			listRes[i].buildLookUpTable()
71
		}
72
		return listRes, nil
73
	}
74
75
	var single DeckImport
76
	if err := yaml.Unmarshal(inp, &single); err == nil {
77
		single.buildLookUpTable()
78
		return []DeckImport{single}, nil
79
	}
80
81
	return nil, ErrInvalidFileFormat
82
}