Interesting! I had my own need for this recently, but with a requirement to "fix" currency columns/spacing. The script gets pretty short if you leverage some internal methods, but this also ends up stripping comments and filling in empty/inferred posting amounts. It looks like yours would preserve more context by more or less splitting on date. I ended up with this plus some messy logic to regextract my fava currency-column option:
import sys
from beancount.loader import load_file
from beancount.parser import printer
from beancount.scripts import format
def main(file):
entries, errors, options = load_file(file)
entries_sorted = sorted(entries, key=lambda x: x.date)
# Or if you don't need formatting, just printer.print_entries(entries_sorted, file=file)
with open(file, 'w') as f:
# Enumerate to get "last" entry to skip extra inter-directive newline
for i, entry in enumerate(entries_sorted):
printed = printer.format_entry(entry)
# Align the printed entry with a currency column, set or grab from options (e.g. Fava)
formatted = format.align_beancount(printed, currency_column=61)
f.write(formatted)
if i != len(entries_sorted) - 1:
f.write('\n')
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python bean-sort.py <beancount-file>")
sys.exit(1)
main(sys.argv[1])
Thanks for sharing!
Paul