~mendelmaleh/pfin

ref: 95ffe938fcda9ea79264ad9b3fbfd09059af3b17 pfin/types.go -rw-r--r-- 1.5 KiB
95ffe938Mendel E Parallelize directory parsing 4 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package pfin

import (
	"os"
	"path/filepath"

	"github.com/pelletier/go-toml/v2"
)

type Config struct {
	Pfin struct {
		User string
		Root string
	}

	Account map[string]Account
}

type Account struct {
	Name string

	// parser type, inherited from account name if unset
	Type string

	// default user, inherited from config.Pfin.User if unset
	DefaultUser string `toml:"user"`

	// map of users to card identifier
	Users map[string]string
	Cards map[string]string
}

func (a Account) User(card string) string {
	if user, ok := a.Cards[card]; ok {
		return user
	}

	return a.DefaultUser
}

// ParseConfig will use default config location if path is empty
func ParseConfig(path string) (config Config, err error) {
	// default config path
	if path == "" {
		configpath, err := os.UserConfigDir()
		if err != nil {
			return config, err
		}

		path = filepath.Join(configpath, "pfin", "config.toml")
	}

	data, err := os.ReadFile(path)
	if err != nil {
		return
	}

	if err = toml.Unmarshal(data, &config); err != nil {
		return
	}

	// make root filepath absolute
	config.Pfin.Root = filepath.Clean(filepath.Join(filepath.Dir(path), config.Pfin.Root))

	for k, v := range config.Account {
		v.Name = k

		// set type to name if unset
		if v.Type == "" {
			v.Type = k
		}

		// set default user if unset
		if v.DefaultUser == "" {
			v.DefaultUser = config.Pfin.User
		}

		// set card to user map
		v.Cards = make(map[string]string)
		for user, card := range v.Users {
			v.Cards[card] = user
		}

		config.Account[k] = v
	}

	return
}