all repos

anpi @ 8a8b00d

yaml to anki importer

anpi/parser/parser.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
add lookup of original type field, 1 year ago
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
	// fieldLookUp internal reserve mapping of [Fields]
17
	fieldLookUp map[string]string
18
}
19
20
func (d *DeckImport) FieldLookUp(field string) string {
21
	// TODO: use ok notation here
22
23
	val := d.fieldLookUp[field]
24
	return val
25
}
26
27
func (d *DeckImport) Validate() error {
28
	return nil
29
}
30
31
func (d *DeckImport) buildLookUpTable() {
32
	d.fieldLookUp = make(map[string]string)
33
	for k, v := range d.Fields {
34
		d.fieldLookUp[k] = v
35
	}
36
}
37
38
type Note struct {
39
	Fields map[string]string
40
	Tags   []string
41
}
42
43
func (n *Note) UnmarshalYAML(value *yaml.Node) error {
44
	var raw map[string]any
45
	if err := value.Decode(&raw); err != nil {
46
		return err
47
	}
48
49
	n.Fields = make(map[string]string)
50
	for k, v := range raw {
51
		if k == "tags" {
52
			if tags, ok := v.([]string); ok {
53
				n.Tags = append(n.Tags, tags...)
54
			}
55
		}
56
57
		if str, ok := v.(string); ok {
58
			n.Fields[k] = str
59
		}
60
	}
61
62
	return nil
63
}
64
65
func Parse(inp []byte) ([]DeckImport, error) {
66
	var listRes []DeckImport
67
	if err := yaml.Unmarshal(inp, &listRes); err == nil {
68
		for i := range listRes {
69
			listRes[i].buildLookUpTable()
70
		}
71
		return listRes, nil
72
	}
73
74
	var single DeckImport
75
	if err := yaml.Unmarshal(inp, &single); err == nil {
76
		single.buildLookUpTable()
77
		return []DeckImport{single}, nil
78
	}
79
80
	return nil, fmt.Errorf("invalid file format")
81
}