all repos

anpi @ b372e68

yaml to anki importer

anpi/parser/parser.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
remove some not needed code, 1 year ago
1
package parser
2
3
import (
4
	"errors"
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
func (d *DeckImport) FieldLookUp(field string) string {
18
	// TODO: use ok notation here
19
20
	val := d.Fields[field]
21
	return val
22
}
23
24
func (d *DeckImport) Validate() error {
25
	return nil
26
}
27
28
type Note struct {
29
	Fields map[string]string
30
	Tags   []string
31
}
32
33
func (n *Note) UnmarshalYAML(value *yaml.Node) error {
34
	var raw map[string]any
35
	if err := value.Decode(&raw); err != nil {
36
		return err
37
	}
38
39
	n.Fields = make(map[string]string)
40
	for k, v := range raw {
41
		if k == "tags" {
42
			if tags, ok := v.([]string); ok {
43
				n.Tags = append(n.Tags, tags...)
44
			}
45
		}
46
47
		if str, ok := v.(string); ok {
48
			n.Fields[k] = str
49
		}
50
	}
51
52
	return nil
53
}
54
55
var ErrInvalidFileFormat = errors.New("invalid file format")
56
57
func Parse(inp []byte) ([]DeckImport, error) {
58
	var listRes []DeckImport
59
	if err := yaml.Unmarshal(inp, &listRes); err == nil {
60
		return listRes, nil
61
	}
62
63
	var single DeckImport
64
	if err := yaml.Unmarshal(inp, &single); err == nil {
65
		return []DeckImport{single}, nil
66
	}
67
68
	return nil, ErrInvalidFileFormat
69
}