-
Notifications
You must be signed in to change notification settings - Fork 0
/
ledger.py
executable file
·96 lines (74 loc) · 2.46 KB
/
ledger.py
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
#!/usr/bin/python
#
# A hacked together script for parsing jwiegley's Ledger files
#
# Author: Brett Hutley <brett@hutley.net>
import sys
import datetime
class Split:
def __init__(self, account, amount):
self.account = account
self.amount = amount
def __str__(self):
return "\t%s\t%.2f\n" % (self.account, self.amount)
class Xact:
def __init__(self, date, desc):
self.date = date
self.desc = desc
self.splits = []
self.account_splits = {}
def add_split(self, split):
if self.account_splits.has_key(split.account):
raise Exception("Can't have multiple splits with the same account ('%s') in the same transaction" % (split.account, ))
self.splits.append(split)
self.account_splits[split.account] = split
def is_account_in_xact(self, account):
return self.account_splits.has_key(account)
def split_for_account(self, account):
return self.account_splits[account]
def __str__(self):
str = "%d-%02d-%02d\t%s\n" % (self.date.year, self.date.month, self.date.day, self.desc)
for split in self.splits:
str += split.__str__()
return str
def parse_xact(line):
dt = line[0:10]
desc = line[10:len(line)].strip()
year, mon, day = dt.split('-')
date = datetime.date(int(year), int(mon), int(day))
return Xact(date, desc)
def load_ledger_file(filename):
file = open(filename, 'r')
WAITING_FOR_XACT = 0
IN_XACT = 1
state = WAITING_FOR_XACT
xacts = []
curr_xact = None
linenum = 0
for line in file:
linenum += 1
if line.startswith(';'):
continue
line = line.rstrip()
if state == WAITING_FOR_XACT:
if len(line) > 10:
state = IN_XACT
curr_xact = parse_xact(line)
xacts.append(curr_xact)
else:
# in XACT
if len(line) > 10:
fields = line.split("\t")
if len(fields) != 3:
print("Error in split at line: %s" % line)
exit(0)
split = Split(fields[1], float(fields[2]))
try:
curr_xact.add_split(split)
except:
print("Caught exception adding split at line number %d" % (linenum, ))
exit(0)
else:
state = WAITING_FOR_XACT
file.close()
return xacts