|
20 | 20 | """ |
21 | 21 |
|
22 | 22 | import os |
23 | | -from typing import Union |
| 23 | +from typing import Optional, Union |
24 | 24 |
|
25 | | -from git import RemoteProgress, Repo |
| 25 | +from git import GitCommandError, RemoteProgress, Repo |
26 | 26 | from tqdm import tqdm |
27 | 27 |
|
28 | 28 | from ._repositories import REPOSITORIES |
@@ -63,28 +63,42 @@ def update( |
63 | 63 | self.progress.refresh() |
64 | 64 |
|
65 | 65 |
|
66 | | -def clone_to_directory(repo_url: str, target_dir: str) -> Repo: |
| 66 | +def clone_to_directory( |
| 67 | + repo_url: str, target_dir: str, commit: Optional[str] = None |
| 68 | +) -> Repo: |
67 | 69 | """ |
68 | 70 | Clone a git repository to a designated directory. |
69 | 71 |
|
70 | 72 | Args: |
71 | 73 | repo_url: URL to the git repository to clone. |
72 | 74 | target_dir: Directory to clone the repository to. |
| 75 | + commit: Optional commit to check out after cloning. |
73 | 76 |
|
74 | 77 | Returns: |
75 | 78 | Cloned git repository. |
76 | 79 | """ |
77 | 80 | if os.path.exists(target_dir): |
78 | | - return Repo(target_dir) |
79 | | - |
80 | | - print(f"Cloning {repo_url}...") |
81 | | - os.makedirs(target_dir) |
82 | | - progress_bar = CloneProgressBar() |
83 | | - return Repo.clone_from( |
84 | | - repo_url, |
85 | | - target_dir, |
86 | | - progress=progress_bar.update, |
87 | | - ) |
| 81 | + clone = Repo(target_dir) |
| 82 | + else: |
| 83 | + print(f"Cloning {repo_url}...") |
| 84 | + os.makedirs(target_dir) |
| 85 | + progress_bar = CloneProgressBar() |
| 86 | + clone = Repo.clone_from( |
| 87 | + repo_url, |
| 88 | + target_dir, |
| 89 | + progress=progress_bar.update, |
| 90 | + ) |
| 91 | + if commit is not None: |
| 92 | + try: |
| 93 | + clone.git.checkout(commit) |
| 94 | + except GitCommandError: |
| 95 | + print( |
| 96 | + f"Commit {commit} not found, " |
| 97 | + "let's fetch origin and try again..." |
| 98 | + ) |
| 99 | + clone.git.fetch("origin") |
| 100 | + clone.git.checkout(commit) |
| 101 | + return clone |
88 | 102 |
|
89 | 103 |
|
90 | 104 | def clone_to_cache(description_name: str) -> str: |
@@ -116,6 +130,7 @@ def clone_to_cache(description_name: str) -> str: |
116 | 130 | ) |
117 | 131 |
|
118 | 132 | target_dir = os.path.join(cache_dir, repository.cache_path) |
119 | | - clone = clone_to_directory(repository.url, target_dir) |
120 | | - clone.git.checkout(repository.commit) |
| 133 | + clone = clone_to_directory( |
| 134 | + repository.url, target_dir, commit=repository.commit |
| 135 | + ) |
121 | 136 | return str(clone.working_dir) |
0 commit comments