diff --git a/conservancy_beancount/books.py b/conservancy_beancount/books.py index 199b922d785ba9148edffa6a3af6d3541460d441..002f7ad4cdeb38e42e5b2757a695c0a91b479e04 100644 --- a/conservancy_beancount/books.py +++ b/conservancy_beancount/books.py @@ -110,54 +110,39 @@ class Loader: load for a given date range. """ self.books_root = books_root - self.opening_root = books_root / 'books' self.fiscal_year = fiscal_year def _iter_fy_books(self, fy_range: Iterable[int]) -> Iterator[Path]: - dir_path = self.opening_root for year in fy_range: - path = dir_path / f'{year}.beancount' + path = Path(self.books_root, 'books', f'{year}.beancount') if path.exists(): yield path - dir_path = self.books_root - def fy_range_string(self, - from_fy: Year, - to_fy: Optional[Year]=None, - ) -> str: - """Return a string to load books for a range of fiscal years + def load_fy_range(self, + from_fy: Year, + to_fy: Optional[Year]=None, + ) -> LoadResult: + """Load books for a range of fiscal years This method generates a range of fiscal years by calling FiscalYear.range() with its first two arguments. It returns a string of Beancount directives to load the books from the first available fiscal year through the end of the range. - - Pass the string to Loader.load_string() to actually load data from it. """ - paths = self._iter_fy_books(self.fiscal_year.range(from_fy, to_fy)) + fy_range = self.fiscal_year.range(from_fy, to_fy) + fy_paths = self._iter_fy_books(fy_range) try: - with next(paths).open() as opening_books: - lines = [opening_books.read()] + entries, errors, options_map = bc_loader.load_file(next(fy_paths)) except StopIteration: - return '' - for path in paths: - lines.append(f'include "../{path.name}"') - return '\n'.join(lines) - - def load_string(self, source: str) -> LoadResult: - """Load a generated string of Beancount directives - - This method takes a string generated by another Loader method, like - fy_range_string, and loads it through Beancount, setting up the - environment as necessary to do that. - """ - with workdir(self.opening_root): - retval: LoadResult = bc_loader.load_string(source) - return retval - - def load_fy_range(self, - from_fy: Year, - to_fy: Optional[Year]=None, - ) -> LoadResult: - """Load books for a range of fiscal years""" - return self.load_string(self.fy_range_string(from_fy, to_fy)) + entries, errors, options_map = [], [], {} + for load_path in fy_paths: + new_entries, new_errors, new_options = bc_loader.load_file(load_path) + # We only want transactions from the new fiscal year. + # We don't want the opening balance, duplicate definitions, etc. + fy_filename = str(load_path.parent.parent / load_path.name) + entries.extend( + entry for entry in new_entries + if entry.meta.get('filename') == fy_filename + ) + errors.extend(new_errors) + return entries, errors, options_map