Skip to content

Instantly share code, notes, and snippets.

@amarjen
Created March 16, 2021 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amarjen/a76c38bc880714ffbf88116a0b104e2d to your computer and use it in GitHub Desktop.
Save amarjen/a76c38bc880714ffbf88116a0b104e2d to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# coding: utf-8
"""
hledger-rep2mkd
version: 0.1
MIT LICENSE ( https://https://mit-license.org/ )
2021 (c) Tony M. Jenkins
Parses csv output from is / bs / bse / cf / reg / areg hledger reports to markdown file.
Requirements:
- Pandoc for mkd to pdf conversion.
Example:
$ hledger bse -O csv | python3 ldg-rep2mkd.py && pandoc output.mkd -o output.pdf && zathura output.pdf
"""
import csv
import sys
lines = [row for row in csv.reader(sys.stdin.readlines())]
cols = len(lines[0])
## document metadata
if lines[0][0][0:6] == 'txnidx':
bsreport = False
output = r"""---
title: register report
fontfamily: libertinus
header-includes: \usepackage[a4paper,margin=1in,landscape]{geometry}
...
"""
else:
bsreport = True
output = r"""---
title: ledger report
fontfamily: libertinus
header-includes: \usepackage[a4paper,margin=1in]{geometry}
...
"""
for ix, line in enumerate(lines):
extra = ''
try:
## set bold style for report keywords
if line[0] in ['Revenues','Expenses','Assets','Liabilities','Equity', 'Cash flows','Total:', 'Net:']:
extra = '**'
except:
print('please check that stdin is being fed by proper csv data')
sys.exit(1)
if ix == 0 and bsreport:
## document title. Only for bs kind reports (bs/is/bse)
output += f'## {line[0]}\n'
output +='\n'
elif (ix == 0 and not bsreport) or (ix == 1 and bsreport):
## header table.
output += ''.join([f'|**{line[n]}**' for n in range(cols)]) + '|\n'
output += '|---|' + (cols-1)*'--:|' + '\n'
else:
## data rows
if line[0] in ('Liabilities','Equity','Expenses','Net:'):
output += cols*'|'+'\n'
output += ''.join([f'|{extra}{line[n]}{extra}' for n in range(cols)]) + '|\n'
with open('output.mkd','w') as f:
f.writelines(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment