~mendelmaleh/pfin

ref: 6b408c967e8864ab5e2d9d0b1049f2dc47185f7c pfin/parser.go -rw-r--r-- 965 bytes
6b408c96Mendel E Wrap parser error with account and filename a month ago
                                                                                
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
package pfin

import "fmt"

var parsers = make(map[string]Parser)

type ErrUnregisteredParser struct {
	parser string
}

func (e ErrUnregisteredParser) Error() string {
	return fmt.Sprintf("pfin: unregistered parser %q", e.parser)
}

type Parser interface {
	Parse(acc Account, filename string, data []byte) ([]Transaction, error)
	Filetype() string
}

func Register(name string, parser Parser) {
	parsers[name] = parser
}

func Parse(acc Account, filename string, data []byte) ([]Transaction, error) {
	if _, ok := parsers[acc.Type]; !ok {
		return []Transaction{}, ErrUnregisteredParser{acc.Type}
	}

	txns, err := parsers[acc.Type].Parse(acc, filename, data)
	if err != nil {
		return []Transaction{}, fmt.Errorf("error parsing %s/%s: %w", acc.Name, filename, err)
	}

	return txns, nil
}

func Filetype(parser string) (string, error) {
	if _, ok := parsers[parser]; !ok {
		return "", ErrUnregisteredParser{parser}
	}

	return parsers[parser].Filetype(), nil
}