From f9ea7edae3d760f5613bd606afc7c3a12fbabe93 2020-07-29 19:46:14 From: Brett Smith Date: 2020-07-29 19:46:14 Subject: [PATCH] config: Add Config.books_repo() method. --- diff --git a/conservancy_beancount/config.py b/conservancy_beancount/config.py index b26737c35cec9e73a83150fde89643a48443f64f..a8fabf9f7353ad8071fcd994b2fa9c4243e7cb20 100644 --- a/conservancy_beancount/config.py +++ b/conservancy_beancount/config.py @@ -22,6 +22,7 @@ import os import re import urllib.parse as urlparse +import git # type:ignore[import] import requests.auth import rt @@ -128,6 +129,16 @@ class Config: def books_path(self) -> Optional[Path]: return self._abspath(self.file_config['Beancount'], 'books dir') + def books_repo(self) -> Optional[git.Repo]: + """Return a git.Repo object for the books directory + + Returns None if the books directory is not a valid Git repository. + """ + try: + return git.Repo(self.file_config['Beancount']['books dir']) + except (KeyError, git.exc.GitError): + return None + def cache_dir_path(self, name: str='conservancy_beancount') -> Optional[Path]: cache_root = self._path_from_environ('XDG_CACHE_HOME') return ( diff --git a/setup.py b/setup.py index fefae7df8bd4a80897882001781886d5c7734bd5..beb8920e9e4c93bd957c459e09222094e4dfd032 100755 --- a/setup.py +++ b/setup.py @@ -13,6 +13,7 @@ setup( install_requires=[ 'babel>=2.6', # Debian:python3-babel 'beancount>=2.2', # Debian:beancount + 'GitPython>=2.0', # Debian:python3-git # 1.4.1 crashes when trying to save some documents. 'odfpy>=1.4.0,!=1.4.1', # Debian:python3-odf 'PyYAML>=3.0', # Debian:python3-yaml diff --git a/tests/test_config.py b/tests/test_config.py index 0537d528f2672486ace2a27d0804dcf6abf2b640..4fd4d6ac6fcbc9a9f8d897f204f84f4fad1683c6 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -20,6 +20,8 @@ import operator import os import re +import git + from pathlib import Path import pytest @@ -422,3 +424,19 @@ def test_books_loader(): def test_books_loader_without_books(): assert config_mod.Config().books_loader() is None + +def test_books_repo(tmp_path): + repo_path = tmp_path / 'books_repo' + expected = git.Repo.init(repo_path) + config = config_mod.Config() + config.load_string(f'[Beancount]\nbooks dir = {repo_path}') + assert config.books_repo() == expected + +def test_books_repo_no_dir(): + config = config_mod.Config() + assert config.books_repo() is None + +def test_books_dir_not_repo(): + config = config_mod.Config() + config.load_string(f'[Beancount]\nbooks dir = {os.devnull}') + assert config.books_repo() is None