~mendelmaleh/pfin

ref: 10792cb77b6ea4b339bc433ca1cf641a57012f71 pfin/util/dir.go -rw-r--r-- 1.0 KiB
10792cb7Mendel E Parallelize account parsing 3 months 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package util

import (
	"fmt"
	"os"
	"path/filepath"
	"sort"

	"git.sr.ht/~mendelmaleh/pfin"
)

type ErrNoMatches struct {
	path string
}

func (e ErrNoMatches) Error() string {
	return fmt.Sprintf("pfin/parser/util: no matches for path %q", e.path)
}

func ParseDir(acc pfin.Account, root string) ([]pfin.Transaction, error) {
	var txns []pfin.Transaction

	filetype, err := pfin.Filetype(acc.Type)
	if err != nil {
		return txns, err
	}

	path := filepath.Join(root, acc.Name)

	if path[len(path)-1] != filepath.Separator {
		path += string(filepath.Separator)
	}

	matches, err := filepath.Glob(path + "*." + filetype)
	if err != nil {
		return txns, err
	}

	if len(matches) == 0 {
		return txns, ErrNoMatches{path}
	}

	// sort oldest first
	sort.Strings(matches)

	for _, f := range matches {
		file, err := os.ReadFile(f)
		if err != nil {
			return txns, err
		}

		tx, err := pfin.Parse(acc, filepath.Base(f), file)
		if err != nil {
			return txns, err
		}

		// TODO: use copy(), consider parallelizing
		txns = append(txns, tx...)
	}

	return txns, nil
}