|
| 1 | +"""Fetch dependent repositories defined in repos.json.""" |
| 2 | + |
| 3 | +import json |
1 | 4 | import os |
2 | 5 | import subprocess |
3 | | -import json |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | + |
| 9 | +def _run_git(args): |
| 10 | + subprocess.run(['git', *args], check=True) |
| 11 | + |
| 12 | + |
| 13 | +def _maybe_update_submodules(repo_path: Path) -> None: |
| 14 | + if (repo_path / '.gitmodules').is_file(): |
| 15 | + _run_git(['-C', str(repo_path), 'submodule', 'update', '--init', '--recursive']) |
4 | 16 |
|
5 | 17 |
|
6 | 18 | def clone_or_update_repo(repo_url, path, branch): |
7 | | - command = [] |
8 | | - command.append('git') |
9 | | - command.append('clone') |
10 | | - |
| 19 | + repo_path = Path(path) |
| 20 | + |
| 21 | + if repo_path.is_dir(): |
| 22 | + _run_git(['-C', str(repo_path), 'fetch', '--prune']) |
| 23 | + |
| 24 | + if branch: |
| 25 | + _run_git(['-C', str(repo_path), 'checkout', branch]) |
| 26 | + |
| 27 | + remote_ref = subprocess.run( |
| 28 | + ['git', '-C', str(repo_path), 'show-ref', '--verify', f'refs/remotes/origin/{branch}'], |
| 29 | + stdout=subprocess.DEVNULL, |
| 30 | + stderr=subprocess.DEVNULL, |
| 31 | + check=False, |
| 32 | + ) |
| 33 | + |
| 34 | + if remote_ref.returncode == 0: |
| 35 | + _run_git(['-C', str(repo_path), 'reset', '--hard', f'origin/{branch}']) |
| 36 | + else: |
| 37 | + _run_git(['-C', str(repo_path), 'pull', '--ff-only']) |
| 38 | + |
| 39 | + _maybe_update_submodules(repo_path) |
| 40 | + return |
| 41 | + |
| 42 | + command = ['clone'] |
| 43 | + |
11 | 44 | if branch: |
12 | | - command.append('-b') |
13 | | - command.append(branch) |
| 45 | + command.extend(['-b', branch]) |
14 | 46 |
|
15 | | - command.append(repo_url) |
16 | | - command.append(path) |
| 47 | + command.extend([repo_url, str(repo_path)]) |
17 | 48 |
|
18 | | - subprocess.run(command) |
| 49 | + _run_git(command) |
| 50 | + _maybe_update_submodules(repo_path) |
19 | 51 |
|
20 | 52 | def main(): |
21 | 53 | script_dir = os.path.dirname(os.path.abspath(__file__)) |
|
0 commit comments