|
| 1 | +""" |
| 2 | +Patch go.mod so that the lines 'go xxx' to 'toolchain xxx' are as in git's |
| 3 | +HEAD. |
| 4 | +
|
| 5 | +This is necessary since newer 'go mod tidy' versions tend to modify these |
| 6 | +lines. Since we check in CI that 'go mod tidy' does not change go.mod, this |
| 7 | +causes CI to fail. |
| 8 | +""" |
| 9 | + |
| 10 | +import subprocess |
| 11 | + |
| 12 | + |
| 13 | +def split_go_mod(contents: str) -> tuple[list[str], list[str], list[str]]: |
| 14 | + """ |
| 15 | + Given the contents of go.mod, splits it into three lists of lines |
| 16 | + (with endings): |
| 17 | + 1. The lines before 'go'; |
| 18 | + 2. The lines starting with 'go' and ending with 'toolchain'; |
| 19 | + 3. The lines after 'toolchain'. |
| 20 | + """ |
| 21 | + parts: tuple[list[str], list[str], list[str]] = ([], [], []) |
| 22 | + index = 0 |
| 23 | + for line in contents.splitlines(keepends=True): |
| 24 | + next_index = index |
| 25 | + if line.startswith('go '): |
| 26 | + index = next_index = 1 |
| 27 | + if line.startswith('toolchain '): |
| 28 | + next_index = 2 |
| 29 | + parts[index].append(line) |
| 30 | + index = next_index |
| 31 | + return parts |
| 32 | + |
| 33 | + |
| 34 | +def get_file_contents_from_git_revision(filename: str, revision: str) -> str: |
| 35 | + """ |
| 36 | + Get the file contents of ``filename`` from Git revision ``revision``. |
| 37 | + """ |
| 38 | + p = subprocess.run( |
| 39 | + ['git', 'show', f'{revision}:{filename}'], |
| 40 | + stdout=subprocess.PIPE, |
| 41 | + check=True, |
| 42 | + encoding='utf-8', |
| 43 | + ) |
| 44 | + return p.stdout |
| 45 | + |
| 46 | + |
| 47 | +def read_file(filename: str) -> str: |
| 48 | + """ |
| 49 | + Read the file's contents. |
| 50 | + """ |
| 51 | + with open(filename, 'r', encoding='utf-8') as f: |
| 52 | + return f.read() |
| 53 | + |
| 54 | + |
| 55 | +def write_file(filename: str, contents: str) -> None: |
| 56 | + """ |
| 57 | + Write the file's contents. |
| 58 | + """ |
| 59 | + with open(filename, 'w', encoding='utf-8') as f: |
| 60 | + f.write(contents) |
| 61 | + |
| 62 | + |
| 63 | +def main(): |
| 64 | + """ |
| 65 | + Patches go.mod. |
| 66 | + """ |
| 67 | + filename = 'go.mod' |
| 68 | + _, go_versions, __ = split_go_mod( |
| 69 | + get_file_contents_from_git_revision(filename, 'HEAD') |
| 70 | + ) |
| 71 | + head, _, tail = split_go_mod(read_file(filename)) |
| 72 | + lines = head + go_versions + tail |
| 73 | + write_file(filename, ''.join(lines)) |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == '__main__': |
| 77 | + main() |
0 commit comments