From a703ee821d678b3d692a0b1accae476197872d13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Thu, 19 Jul 2018 14:56:59 +0200 Subject: [PATCH] Fix SnapshotProvider initialization stuff --- lib/tfw/components/snapshot_provider.py | 62 ++++++++++++++++++------- 1 file changed, 44 insertions(+), 18 deletions(-) diff --git a/lib/tfw/components/snapshot_provider.py b/lib/tfw/components/snapshot_provider.py index 4ce61eb..0b3b008 100644 --- a/lib/tfw/components/snapshot_provider.py +++ b/lib/tfw/components/snapshot_provider.py @@ -22,13 +22,52 @@ class SnapshotProvider: 'GIT_PAGER': 'cat' } - self._check_environment() + self._init_repo() self.__last_valid_branch = self._branch - self._init_repo_if_needed() + + def _init_repo(self): + self._check_environment() + + if not self._repo_is_initialized: + self._run(('git', 'init')) + + if self._number_of_commits == 0: + self._snapshot() + + self._check_head_not_detached() def _check_environment(self): if not isdir(self.gitenv['GIT_DIR']) or not isdir(self.gitenv['GIT_WORK_TREE']): raise EnvironmentError('Directories "directory" and "git_dir" must exist!') + + @property + def _repo_is_initialized(self): + return self._run( + ('git', 'status'), + check=False + ).returncode == 0 + + @property + def _number_of_commits(self): + return int( + self._get_stdout(( + 'git', 'rev-list', + '--all', + '--count' + )) + ) + + def _snapshot(self): + self._run(( + 'git', 'add', + '-A' + )) + self._run(( + 'git', 'commit', + '-m', 'Snapshot' + )) + + def _check_head_not_detached(self): if self._head_detached: raise EnvironmentError(f'{self.__class__.__name__} cannot init from detached HEAD state!') @@ -49,29 +88,16 @@ class SnapshotProvider: return stdout_bytes.decode().rstrip('\n') def _run(self, *args, **kwargs): - kwargs['check'] = True + if 'check' not in kwargs: + kwargs['check'] = True if 'env' not in kwargs: kwargs['env'] = self.gitenv return run(*args, **kwargs) - def _init_repo_if_needed(self): - if not self._repo_is_initialized(): - self._run(('git', 'init')) - - def _repo_is_initialized(self): - return self._run(('git', 'status')).returncode == 0 - def take_snapshot(self): if self._head_detached: self._checkout_new_branch_from_head() - self._run(( - 'git', 'add', - '-A' - )) - self._run(( - 'git', 'commit', - '-m', 'Snapshot' - )) + self._snapshot() def _checkout_new_branch_from_head(self): branch_name = uuid4()