Skip to content

Instantly share code, notes, and snippets.

@tubaman
Last active February 27, 2023 16:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tubaman/0e80cec388d3d5d61e3f300e2477a9ae to your computer and use it in GitHub Desktop.
Save tubaman/0e80cec388d3d5d61e3f300e2477a9ae to your computer and use it in GitHub Desktop.
ledgerparser
"""ledger journal parser
We use this to parse the ledger file because we want to preserve the
exact format of the file including spaces, etc. It maps the parsed
transaction to the origin lines of the file.
"""
import ledger
def include_lines(ledger_file, xacts):
"""Generator to match the journal lines with the xact"""
journal_lines = enumerate(ledger_file, 1)
for xact in xacts:
lines = []
while True:
linenum, line = next(journal_lines)
lines.append(line)
if linenum == xact.pos.end_line:
break
yield lines, xact
def include_trailing_lines(ledger_file, xacts):
"""Generator to add any trailing lines to the last transaction's lines"""
prev = None
for lines, xact in xacts:
if prev:
yield prev
prev = lines, xact
if prev:
lines, xact = prev
lines += list(ledger_file)
yield lines, xact
def parse_xacts(ledger_file):
session = ledger.Session()
xacts = session.read_journal_from_string(ledger_file.read()).xacts()
ledger_file.seek(0)
xacts = include_lines(ledger_file, xacts)
xacts = include_trailing_lines(ledger_file, xacts)
return xacts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment