|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import argparse |
| 4 | +from collections.abc import Sequence |
| 5 | + |
| 6 | +import ruamel.yaml |
| 7 | + |
| 8 | +SUPPORTED = frozenset( |
| 9 | + ( |
| 10 | + "black", |
| 11 | + "flake8", |
| 12 | + ) |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +def main(argv: Sequence[str] | None = None) -> int: |
| 17 | + parser = argparse.ArgumentParser() |
| 18 | + parser.add_argument("filename", default=".pre-commit-config.yaml") |
| 19 | + |
| 20 | + args = parser.parse_args(argv) |
| 21 | + filename: str = args.filename |
| 22 | + |
| 23 | + # match pre-commit config as documented |
| 24 | + # TODO - support round-tripping |
| 25 | + yaml = ruamel.yaml.YAML() |
| 26 | + yaml.preserve_quotes = True |
| 27 | + yaml.indent(mapping=4, sequence=4) |
| 28 | + |
| 29 | + with open(filename) as f: |
| 30 | + loaded = yaml.load(f) |
| 31 | + |
| 32 | + # TODO - validate schema? |
| 33 | + versions = {} |
| 34 | + for repo in loaded["repos"]: |
| 35 | + for hook in repo["hooks"]: |
| 36 | + if (hid := hook["id"]) in SUPPORTED: |
| 37 | + versions[hid] = repo["rev"] |
| 38 | + |
| 39 | + updated = [] |
| 40 | + for repo in loaded["repos"]: |
| 41 | + for hook in repo["hooks"]: |
| 42 | + for i, dep in enumerate(hook.get("additional_dependencies", ())): |
| 43 | + name, _, cur_version = dep.partition("==") |
| 44 | + target_version = versions.get(name, cur_version) |
| 45 | + if target_version != cur_version: |
| 46 | + hook["additional_dependencies"][i] = f"{name}=={target_version}" |
| 47 | + updated.append((hook["id"], name)) |
| 48 | + |
| 49 | + if updated: |
| 50 | + print(f"Writing updates to {filename}:") |
| 51 | + for hid, name in updated: |
| 52 | + print(f"\tSetting {hid!r} dependency {name!r} to {versions[name]}") |
| 53 | + |
| 54 | + with open(filename, "w+") as f: |
| 55 | + yaml.dump(loaded, f) |
| 56 | + return 1 |
| 57 | + |
| 58 | + return 0 |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + raise SystemExit(main()) |
0 commit comments