|
| 1 | +from os import makedirs |
| 2 | +from os.path import dirname, join |
| 3 | +from shutil import copy, rmtree |
| 4 | + |
| 5 | +from git import Repo |
| 6 | +from github import Github, AuthenticatedUser, Repository |
| 7 | + |
| 8 | +from manager_environment import EnvironmentManager as EM |
| 9 | + |
| 10 | + |
| 11 | +class GitHubManager: |
| 12 | + USER: AuthenticatedUser |
| 13 | + REPO: Repo |
| 14 | + REMOTE: Repository |
| 15 | + |
| 16 | + _REMOTE_NAME: str |
| 17 | + _REMOTE_PATH: str |
| 18 | + _SINGLE_COMMIT_BRANCH = "latest_branch" |
| 19 | + |
| 20 | + @staticmethod |
| 21 | + def prepare_github_env(cls): |
| 22 | + """ |
| 23 | + Download and store for future use: |
| 24 | + - Current GitHub user. |
| 25 | + - Named repo of the user [username]/[username]. |
| 26 | + - Clone of the named repo. |
| 27 | + """ |
| 28 | + github = Github(EM.GH_TOKEN) |
| 29 | + clone_path = "repo" |
| 30 | + cls.USER = github.get_user() |
| 31 | + rmtree(clone_path, ignore_errors=True) |
| 32 | + |
| 33 | + cls._REMOTE_NAME = f"{cls.USER.login}/{EM.REPO_NAME}" |
| 34 | + cls._REPO_PATH = f"https://{EM.GH_TOKEN}@github.com/{cls._REMOTE_NAME}.git" |
| 35 | + |
| 36 | + cls.REMOTE = github.get_repo(cls._REMOTE_NAME) |
| 37 | + cls.REPO = Repo.clone_from(cls._REPO_PATH, to_path=clone_path) |
| 38 | + |
| 39 | + @staticmethod |
| 40 | + def branch(cls, requested_branch: str) -> str: |
| 41 | + """ |
| 42 | + Gets requested branch name or the default branch name if requested branch wasn't found. |
| 43 | + The default branch name is regularly, 'main' or 'master'. |
| 44 | +
|
| 45 | + :param requested_branch: Requested branch name. |
| 46 | + :returns: Commit author. |
| 47 | + """ |
| 48 | + return cls.REMOTE.default_branch if requested_branch == "" else requested_branch |
| 49 | + |
| 50 | + @staticmethod |
| 51 | + def _copy_file_and_add_to_repo(src_path: str): |
| 52 | + """ |
| 53 | + Copies file to repository folder, creating path if needed and adds file to git. |
| 54 | + The copied file relative to repository root path will be equal the source file |
| 55 | + relative to work directory path. |
| 56 | +
|
| 57 | + :param src_path: Source file path. |
| 58 | + """ |
| 59 | + dst_path = join(GitHubManager.REPO.working_tree_dir, src_path) |
| 60 | + makedirs(dirname(dst_path), exist_ok=True) |
| 61 | + copy(src_path, dst_path) |
| 62 | + GitHubManager.REPO.git.add(dst_path) |
0 commit comments