forked from egh/ledger-autosync
/
ledgerwrap.py
301 lines (265 loc) · 10.1 KB
/
ledgerwrap.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
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# Copyright (c) 2013, 2014 Erik Hetzner
#
# This file is part of ledger-autosync
#
# ledger-autosync is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# ledger-autosync is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ledger-autosync. If not, see
# <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
import xml.etree.ElementTree as ET
import os
import re
import distutils.spawn
import subprocess
from subprocess import Popen, PIPE
from threading import Thread
from Queue import Queue, Empty
from ledgerautosync.converter import Converter
import logging
from fuzzywuzzy import process
def hledger_clean(a):
def clean_str(s):
s = s.replace('(', '\(')
s = s.replace(')', '\)')
return s
return [clean_str(s) for s in a]
def pipe_clean(a):
def clean_str(s):
s = s.replace('/', '\\\\/')
s = s.replace('%', '')
if not(re.match(r"^\w+$", s)):
s = "\"%s\"" % (s)
return s
return [clean_str(s) for s in a]
def windows_clean(a):
def clean_str(s):
s = s.replace('%', '')
s = s.replace(' ', '\ ')
s = s.replace('/', '\/')
return s
return [clean_str(s) for s in a]
def clean_payee(s):
s = s.replace('%', '')
s = s.replace('/', '\/')
s = s.replace("'", "")
return s
def all_or_none(seq):
"""Returns the first value of seq if all values of seq are equal, or \
returns None."""
if len(seq) == 0:
return None
def f(x, y):
if (x == y):
return x
else:
return None
return reduce(f, seq, seq[0])
def mk_ledger(ledger_file):
try:
import ledger
return LedgerPython(ledger_file, string_read=False)
except ImportError:
if ((distutils.spawn.find_executable('ledger') is not None) and
(Popen(["ledger", "--version"], stdout=PIPE).
communicate()[0]).startswith("Ledger 3")):
return Ledger(ledger_file)
elif distutils.spawn.find_executable('hledger') is not None:
return HLedger(ledger_file)
else:
raise Exception("Neither ledger 3 nor hledger found!")
class Ledger(object):
allTransactions = None
def __init__(self, ledger_file=None, no_pipe=True):
if distutils.spawn.find_executable('ledger') is None:
raise Exception("ledger was not found in $PATH")
self._item = ""
def enqueue_output(out, queue):
buff = ""
while (buff is not None):
buff = out.read(1)
if (buff is not None):
self._item += buff
if self._item.endswith("] "): # prompt
queue.put(self._item[0:-2])
self._item = ""
out.close()
self.use_pipe = (os.name == 'posix') and not(no_pipe)
self.args = ["ledger"]
if ledger_file is not None:
self.args += ["-f", ledger_file]
if self.use_pipe:
self.p = Popen(self.args, bufsize=1, stdin=PIPE, stdout=PIPE,
close_fds=True)
self.q = Queue()
self.t = Thread(target=enqueue_output, args=(self.p.stdout, self.q))
self.t.daemon = True # thread dies with the program
self.t.start()
# read output until prompt
try:
self.q.get(True, 5)
except Empty:
logging.error("Could not get prompt (]) from ledger!")
logging.error("Received: %s" % (self._item))
exit(1)
def run(self, cmd):
if self.use_pipe:
self.p.stdin.write("xml ")
self.p.stdin.write(" ".join(pipe_clean(cmd)))
self.p.stdin.write("\n")
logging.debug(" ".join(pipe_clean(cmd)))
try:
return ET.fromstring(self.q.get(True, 5))
except Empty:
logging.error("Could not get prompt from ledger!")
exit(1)
else:
cmd = self.args + ["xml"] + cmd
if os.name == 'nt':
cmd = windows_clean(cmd)
return ET.fromstring(subprocess.check_output(cmd))
def get_transaction(self, q):
d = self.run(q).findall('.//transactions/transaction')
if len(d) == 0:
return None
else:
return d[0]
def check_transaction_by_id(self, key, value):
clean_id = Converter.clean_id(value)
return (clean_id is not None) and (self.get_transaction(
["-E", "meta", "%s=%s" % (key, clean_id)])
is not None)
def xact_account(self, payee, date=None, index=-1):
from difflib import SequenceMatcher
if Ledger.allTransactions is None:
txn = self.run([""])
Ledger.allTransactions = txn.findall('.//transactions/transaction')
# scores = []
maxScore = 0
for t in Ledger.allTransactions:
tdate = [node.text for node in t.findall('.//date')]
tpayee = [node.text for node in t.findall('.//payee')]
if len(tpayee) > 0:
a = b = None
if len(tdate) > 0 and not date is None:
a = "%s %s" % (tdate[0], tpayee[0])
b = "%s %s" % (date, payee)
else:
a = "%s" % (tpayee[0])
b = "%s" % (payee)
score = SequenceMatcher(None, a, b).ratio()
if score > maxScore:
# scores.append((score, t))
maxScore = score
maxTransaction = t
if maxScore > 0.5:
# print "payee:%s tpayee:%s score:%s" % (payee,[node.text for node in maxTransaction.findall('.//payee')],maxScore)
accts = [node.text for node in
maxTransaction.findall('.//postings/posting/account/name')]
if accts and len(accts) > index:
return accts[index]
return None
def most_similar_account(self, account):
txn = self.run(["--real", account])
if txn is None:
return None
else:
accts = [node.text for node in
txn.findall('.//transactions/transaction/postings/posting/account/name')]
if accts:
return accts[-1]
else:
return None
def get_account_by_payee(self, payee, exclude):
payee_regex = clean_payee(payee).replace("*", "\\\\*")
try:
txn = self.run(["--real", "payee", payee_regex])
if txn is None:
return None
else:
accts = [node.text for node in
txn.findall('.//transactions/transaction/postings/posting/account/name')]
accts_filtered = [a for a in accts if a != exclude]
if accts_filtered:
return accts_filtered[-1]
else:
return None
except:
logging.error("Error checking --real payee for %s" %
(payee_regex))
class LedgerPython(object):
def __init__(self, ledger_file=None, string_read=True):
# sanity check for ledger python interface
try:
import ledger
except ImportError:
raise Exception("Ledger python interface not found!")
if ledger_file is None:
# TODO - better loading
raise Exception
else:
if string_read:
self.session = ledger.Session()
self.journal = self.session.read_journal_from_string(
open(ledger_file).read())
else:
self.journal = ledger.read_journal(ledger_file)
self.load_payees()
def load_payees(self):
self.payees = []
for xact in self.journal:
self.payees.append(xact.payee)
def check_transaction_by_id(self, key, value):
q = self.journal.query("-E meta %s=\"%s\"" %
(key, Converter.clean_id(value)))
return len(q) > 0
def get_account_by_payee(self, payee, exclude):
fuzzed_payee = process.extractOne(payee, self.payees)[0]
q = self.journal.query("--real payee '%s'" % (clean_payee(fuzzed_payee)))
accts = [p.account for p in q]
accts_filtered = [a for a in accts if a.fullname() != exclude]
if accts_filtered:
return str(accts_filtered[-1])
else:
return None
def most_similar_account(self, account):
q = self.journal.query("%s" % (clean_payee(account)))
accts = [p.account for p in q]
if accts:
return str(accts[-1])
else:
return None
class HLedger(object):
def __init__(self, ledger_file=None):
if distutils.spawn.find_executable('hledger') is None:
raise Exception("hledger was not found in $PATH")
self.args = ["hledger"]
if ledger_file is not None:
self.args += ["-f", ledger_file]
def run(self, cmd):
cmd = hledger_clean(self.args + cmd)
if os.name == 'nt':
cmd = windows_clean(cmd)
logging.debug(" ".join(cmd))
return subprocess.check_output(cmd)
def check_transaction_by_id(self, key, value):
cmd = ["reg", "tag:%s=%s" % (key, Converter.clean_id(value))]
return self.run(cmd) != ''
def get_account_by_payee(self, payee, exclude):
cmd = ["reg", "-w200", "desc:%s" % (payee)]
lines = self.run(cmd).splitlines()
accts = [l[92:172].strip() for l in lines]
accts_filtered = [a for a in accts if a != exclude]
if accts_filtered:
return accts_filtered[-1]
else:
return None