|
| 1 | +import os |
| 2 | +import subprocess |
| 3 | + |
| 4 | +from exercise_utils.cli import run_command |
| 5 | +from exercise_utils.file import create_or_update_file, append_to_file |
| 6 | +from exercise_utils.git import add, init, commit, add_origin |
| 7 | + |
| 8 | +__requires_git__ = True |
| 9 | +__requires_github__ = True |
| 10 | + |
| 11 | +REPO_NAME = "gitmastery-things" |
| 12 | + |
| 13 | + |
| 14 | +def download(verbose: bool): |
| 15 | + _setup_local_repository(verbose) |
| 16 | + _setup_remote_repository(verbose) |
| 17 | + _link_repositories(verbose) |
| 18 | + |
| 19 | + |
| 20 | +def _setup_local_repository(verbose: bool): |
| 21 | + _initialize_workspace() |
| 22 | + init(verbose) |
| 23 | + _create_and_commit_fruits_file(verbose) |
| 24 | + _update_fruits_file(verbose) |
| 25 | + _add_additional_files(verbose) |
| 26 | + |
| 27 | + |
| 28 | +def _setup_remote_repository(verbose: bool): |
| 29 | + username = _get_github_username(verbose) |
| 30 | + _ensure_clean_repository(verbose) |
| 31 | + |
| 32 | + |
| 33 | +def _link_repositories(verbose: bool): |
| 34 | + remote_url = _build_remote_url(verbose) |
| 35 | + add_origin(remote_url, verbose) |
| 36 | + |
| 37 | + |
| 38 | +def _initialize_workspace(): |
| 39 | + os.makedirs("things") |
| 40 | + os.chdir("things") |
| 41 | + |
| 42 | + |
| 43 | +def _create_and_commit_fruits_file(verbose: bool): |
| 44 | + content = """ |
| 45 | + apples |
| 46 | + bananas |
| 47 | + cherries |
| 48 | + dragon fruits |
| 49 | + """ |
| 50 | + create_or_update_file("fruits.txt", content) |
| 51 | + add(["fruits.txt"], verbose) |
| 52 | + |
| 53 | + |
| 54 | +def _update_fruits_file(verbose: bool): |
| 55 | + append_to_file("fruits.txt", "figs") |
| 56 | + add(["fruits.txt"], verbose) |
| 57 | + commit("Insert figs into fruits.txt", verbose) |
| 58 | + |
| 59 | + |
| 60 | +def _add_additional_files(verbose: bool): |
| 61 | + create_or_update_file("colours.txt", """ |
| 62 | + a file for colours |
| 63 | + """) |
| 64 | + create_or_update_file("shapes.txt", """ |
| 65 | + a file for shapes |
| 66 | + """) |
| 67 | + add(["colours.txt", "shapes.txt"], verbose) |
| 68 | + commit("Add colours.txt, shapes.txt", verbose) |
| 69 | + |
| 70 | + |
| 71 | +def _get_github_username(verbose: bool) -> str: |
| 72 | + return run_command(["gh", "api", "user", "-q", ".login"], verbose).strip() |
| 73 | + |
| 74 | + |
| 75 | +def _ensure_clean_repository(verbose: bool): |
| 76 | + result = subprocess.run(["gh", "api", "user", "-q", ".login"], capture_output=True, text=True) |
| 77 | + |
| 78 | + if result.returncode == 0: |
| 79 | + run_command(["gh", "repo", "delete", REPO_NAME, "--yes"], verbose) |
| 80 | + |
| 81 | + run_command(["gh", "repo", "create", REPO_NAME, "--public"], verbose) |
| 82 | + |
| 83 | + |
| 84 | +def _build_remote_url(verbose: bool) -> str: |
| 85 | + username = _get_github_username(verbose) |
| 86 | + return f"https://github.com/{username}/{REPO_NAME}.git" |
0 commit comments