from git import Repo, Remote from injectable import injectable from app.config import GitConfig, get_settings @injectable(singleton=True) class GitService: def __init__(self): self._settings = get_settings() self._repo = self._check_preconditions(self._settings.git) if self._repo.head.ref.name != self._settings.git.branch: self._repo.git.checkout(self._settings.git.branch) self._origin: Remote = self._repo.remotes.origin @staticmethod def _check_preconditions(config: GitConfig) -> Repo: def clone(): return Repo.clone_from(config.url, config.path, branch=config.branch) import os if not config.path.exists(): return clone() if not (config.path / ".git").exists(): os.rmdir(config.path) return clone() return Repo(config.path) def checkout(self, sha: str): self._origin.fetch() self._repo.git.checkout(sha)