-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
188 lines (160 loc) · 3.82 KB
/
main.go
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package main
import (
"bufio"
"context"
"flag"
"fmt"
"os"
"path"
"runtime/debug"
"strings"
"time"
"golang.org/x/oauth2"
"budgetbridge/ynab"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
const (
ynabCacheName = "ynab_cache.json"
)
func getBudgetID(ctx context.Context, ynabClient ynabClient, config Config) (string, error) {
if config.BudgetID != nil {
log.Debug().Msg("using pre-configured budget_id")
return *config.BudgetID, nil
}
log.Debug().Msg("no budget_id configured, fetching")
res, err := ynabClient.Budgets(ctx)
if err != nil {
return "", fmt.Errorf("fetch budget_id: %s", err)
}
if len(res.Budgets) == 1 {
return res.Budgets[0].Id, nil
}
if res.DefaultBudget != nil {
return res.DefaultBudget.Id, nil
}
return "", fmt.Errorf("no default budget available")
}
func newYNABClient(ctx context.Context, accessToken string) *ynab.Client {
httpClient := oauth2.NewClient(ctx, oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: accessToken,
}))
return ynab.NewClient(httpClient)
}
func initLogging() func() error {
level := zerolog.InfoLevel
if envlevel, ok := getLogLevelEnv(); ok {
level = envlevel
}
zerolog.SetGlobalLevel(level)
w := bufio.NewWriter(os.Stderr)
log.Logger = zerolog.
New(w).
With().
Timestamp().
Logger()
return w.Flush
}
func getLogLevelEnv() (zerolog.Level, bool) {
var level zerolog.Level
lvlstr := os.Getenv("LOG")
if lvlstr == "" {
return level, false
}
if level, err := zerolog.ParseLevel(lvlstr); err == nil {
return level, true
}
return level, false
}
type dateFlag struct {
time time.Time
layout string
}
func (f *dateFlag) Set(value string) error {
var t time.Time
var err error
if t, err = time.Parse(f.layout, value); err != nil {
return err
}
f.time = t
return nil
}
func (f *dateFlag) String() string {
return f.time.Format(f.layout)
}
func main() {
configPath := flag.String("config", "config.json", "the path of your config.json file")
dryRun := flag.Bool("dry", false, "emit the transactions but do not create them.")
lastUpdateHint := dateFlag{
layout: "2006-01-02",
}
flag.Var(&lastUpdateHint, "since", "how far to look back for transactions.")
flag.Parse()
flush := initLogging()
defer flush()
defer defaultPanicHandler()
var config Config
err := config.Providers.SetRegistry(map[string]NewProvider{
"splitwise": &SplitwiseOptions{},
})
check(err)
err = config.load(*configPath)
check(err)
ctx := context.Background()
ynabCache := &FileCache{
path: path.Join(config.Cache.Dir, ynabCacheName),
createMissing: config.Cache.CreateMissingDir,
}
check(ynabCache.Open())
ynabClient := &CachingClient{
client: newYNABClient(ctx, config.AccessToken),
cache: ynabCache,
}
if config.Cache.CreateMissingDir {
err = os.MkdirAll(config.Cache.Dir, os.ModePerm)
check(err)
}
budgetID, err := getBudgetID(ctx, ynabClient, config)
check(err)
res, err := ynabClient.Categories(ctx, ynab.CategoriesRequest{BudgetID: budgetID})
check(err)
var categories []ynab.Category
for _, group := range res.CategoryGroups {
categories = append(categories, group.Categories...)
}
providers := config.Providers.initAll(ctx)
if len(providers) == 0 {
log.Warn().Msg("no providers are configured")
return
}
bridge := BudgetBridge{
budgetID,
config.LookBackDays,
ynabClient,
providers,
categories,
*dryRun,
}
err = bridge.ImportAll(ctx, config)
check(err)
}
func defaultPanicHandler() {
if v := recover(); v != nil {
var event *zerolog.Event
if e, ok := v.(error); ok {
event = log.Err(e)
} else if e, ok := v.(string); ok {
event = log.Error().Str("error", e)
}
stack := strings.Split(string(debug.Stack()), "\n")
event.
Str("type", fmt.Sprintf("%T\n", v)).
Strs("stack", stack).
Msg("exiting due to panic")
}
}
func check(err error) {
if err != nil {
panic(err)
}
}