Philipp Schrader | 37fdbb6 | 2021-12-18 00:30:37 -0800 | [diff] [blame^] | 1 | """Provides helper functions for mirroring Go repositories.""" |
| 2 | |
| 3 | import unittest.mock |
| 4 | from typing import List, Dict |
| 5 | |
| 6 | |
| 7 | def read_file(filepath: str) -> str: |
| 8 | """Reads an entire file by returning its contents as a string.""" |
| 9 | with open(filepath, "r") as file: |
| 10 | return file.read() |
| 11 | |
| 12 | def parse_go_repositories(filepath: str) -> List[Dict[str, str]]: |
| 13 | """Parses the top-level go_deps.bzl file. |
| 14 | |
| 15 | This function can parse both the original version of the file generated by |
| 16 | gazelle as well as the tweaked version generated by |
| 17 | tweak_gazelle_go_deps.py. The two versions are identical other than what function they call. |
| 18 | """ |
| 19 | global_functions = { |
| 20 | "load": unittest.mock.MagicMock(), |
| 21 | # The gazelle generated version uses go_repository(). |
| 22 | "go_repository": unittest.mock.MagicMock(), |
| 23 | # The tweak_gazelle_go_deps.py generated version uses |
| 24 | # maybe_override_go_dep(). |
| 25 | "maybe_override_go_dep": unittest.mock.MagicMock() |
| 26 | } |
| 27 | compiled_code = compile(read_file(filepath), filepath, "exec") |
| 28 | eval(compiled_code, global_functions) |
| 29 | |
| 30 | # Extract the repositories defined in the go_dependencies() function from |
| 31 | # go_deps.bzl. |
| 32 | global_functions["go_dependencies"]() |
| 33 | |
| 34 | repositories = [] |
| 35 | for repo_kind in ("go_repository", "maybe_override_go_dep"): |
| 36 | for repo in global_functions[repo_kind].mock_calls: |
| 37 | _, _, kwargs = repo |
| 38 | repositories.append(kwargs) |
| 39 | |
| 40 | return repositories |
| 41 | |