|
2 | 2 | from __future__ import annotations |
3 | 3 |
|
4 | 4 |
|
| 5 | +import contextlib |
5 | 6 | import datetime |
6 | 7 | from pathlib import Path |
7 | 8 | import shutil |
@@ -137,23 +138,32 @@ def clone( |
137 | 138 | url: str, |
138 | 139 | *, |
139 | 140 | branch: str | None = None, |
140 | | - depth: int | None = None, |
| 141 | + depth: int = 1, |
141 | 142 | ) -> None: |
| 143 | + is_hash = re.match(r"^[0-9a-f]{40}$", branch) if branch else False |
| 144 | + |
142 | 145 | dirname = Path(dirname) |
143 | 146 | if dirname.is_dir(): |
144 | | - if ( |
145 | | - branch is not None |
146 | | - and re.match(r"^[0-9a-f]{40}$", branch) |
147 | | - and (dirname / ".git").is_dir() |
148 | | - and get_git_hash(dirname) == branch |
149 | | - ): |
| 147 | + if is_hash and (dirname / ".git").is_dir() and get_git_hash(dirname) == branch: |
150 | 148 | # This is a git repo, and the hash matches |
151 | 149 | return |
152 | 150 | shutil.rmtree(dirname) |
153 | 151 |
|
154 | | - args = ["git", "clone", url, str(dirname)] |
155 | | - if branch is not None: |
156 | | - args += ["--branch", branch] |
157 | | - if depth is not None: |
158 | | - args += ["--depth", str(depth)] |
159 | | - subprocess.check_call(args) |
| 152 | + # Fetching a hash and fetching a branch require different approaches |
| 153 | + |
| 154 | + if is_hash: |
| 155 | + assert branch is not None |
| 156 | + dirname.mkdir() |
| 157 | + with contextlib.chdir(dirname): |
| 158 | + subprocess.check_call(["git", "init"]) |
| 159 | + subprocess.check_call(["git", "remote", "add", "origin", url]) |
| 160 | + subprocess.check_call( |
| 161 | + ["git", "fetch", "--depth", str(depth), "origin", branch] |
| 162 | + ) |
| 163 | + else: |
| 164 | + args = ["git", "clone", url, str(dirname)] |
| 165 | + if branch is not None: |
| 166 | + args += ["--branch", branch] |
| 167 | + if depth is not None: |
| 168 | + args += ["--depth", str(depth)] |
| 169 | + subprocess.check_call(args) |
0 commit comments