From 78cc83dfe84c934f31d6abc7c43071f7c311b20a Mon Sep 17 00:00:00 2001 From: Ankur Dave Date: Wed, 1 Nov 2023 22:43:21 -0400 Subject: [PATCH] Sort meta keys before printing to fix tests broken by Beancount 2.3.6 --- beancount_import/journal_editor.py | 4 +++- beancount_import/sorted_entry_printer.py | 19 +++++++++++++++++++ beancount_import/test_util.py | 5 +++-- 3 files changed, 25 insertions(+), 3 deletions(-) create mode 100644 beancount_import/sorted_entry_printer.py diff --git a/beancount_import/journal_editor.py b/beancount_import/journal_editor.py index cb1a2557..11d542b1 100644 --- a/beancount_import/journal_editor.py +++ b/beancount_import/journal_editor.py @@ -37,6 +37,8 @@ import beancount.parser.booking from beancount.core.number import MISSING +from .sorted_entry_printer import SortedEntryPrinter + # Inclusive starting original line, exclusive ending original line. LineRange = Tuple[int, int] @@ -820,7 +822,7 @@ def get_diff(self) -> JournalDiff: new_entries = [] old_entries = [] - printer = beancount.parser.printer.EntryPrinter() + printer = SortedEntryPrinter() for filename, changed_entries in self.changed_entries.items(): changed_entries.sort(key=lambda x: float('inf') diff --git a/beancount_import/sorted_entry_printer.py b/beancount_import/sorted_entry_printer.py new file mode 100644 index 00000000..95ce3b48 --- /dev/null +++ b/beancount_import/sorted_entry_printer.py @@ -0,0 +1,19 @@ +import beancount.parser.printer + + +class SortedEntryPrinter(beancount.parser.printer.EntryPrinter): + """A subclass of EntryPrinter that sorts the meta keys before printing. + + This preserves the behavior of EntryPrinter from Beancount 2.3.5 and + earlier. + + """ + def __init__(self, **kwargs): + super().__init__(**kwargs) + + def write_metadata(self, meta, oss, prefix=None): + if meta is None: + sorted_meta = None + else: + sorted_meta = dict(sorted(meta.items())) + super().write_metadata(sorted_meta, oss, prefix) diff --git a/beancount_import/test_util.py b/beancount_import/test_util.py index 1e7691bf..a4c4095a 100644 --- a/beancount_import/test_util.py +++ b/beancount_import/test_util.py @@ -10,6 +10,8 @@ import beancount.parser.printer from beancount.core.data import Directive, Entries, Posting, Transaction, Meta +from .sorted_entry_printer import SortedEntryPrinter + def parse(text: str) -> Entries: entries, errors, options = beancount.parser.parser.parse_string( @@ -19,8 +21,7 @@ def parse(text: str) -> Entries: def format_entries(entries: Entries, indent=0): - result = '\n\n'.join( - beancount.parser.printer.format_entry(e) for e in entries) + result = '\n\n'.join(SortedEntryPrinter()(e) for e in entries) indent_str = ' ' * indent return '\n'.join(indent_str + x.rstrip() for x in result.split('\n'))