Debian Codegraph @

scripts/check_pre_commit_rev_in_example.py

raw
1 """
2 Check that the rev value in the example pre-commit configuration matches
3 the latest version of Black. This saves us from forgetting to update that
4 during the release process.
5
6 Why can't we just use `rev: stable` and call it a day? Well pre-commit
7 won't auto update the hook as you may expect (and for good reasons, some
8 technical and some pragmatic). Encouraging bad practice is also just
9 not ideal. xref: https://github.com/psf/black/issues/420
10 """
11
12 import os
13 import sys
14
15 import commonmark
16 import yaml
17 from bs4 import BeautifulSoup
18
19
20 def main(changes: str, content: str, filename: str) -> None:
21 changes_html = commonmark.commonmark(changes)
22 changes_soup = BeautifulSoup(changes_html, "html.parser")
23 headers = changes_soup.find_all("h2")
24 latest_tag, *_ = (
25 (header.string or "").removeprefix("Version ")
26 for header in headers
27 if header.string != "Unreleased"
28 )
29
30 source_version_control_html = commonmark.commonmark(content)
31 source_version_control_soup = BeautifulSoup(
32 source_version_control_html, "html.parser"
33 )
34 codeblocks = source_version_control_soup.find_all(class_="language-yaml")
35
36 for codeblock in codeblocks:
37 parsed = yaml.safe_load(codeblock.string) # type: ignore[arg-type]
38 if not isinstance(parsed, dict):
39 return
40 pre_commit_rev = parsed["repos"][0]["rev"]
41 if not pre_commit_rev == latest_tag:
42 print(
43 f"Please set the rev in ``{filename}`` to be the latest one.\n"
44 f"Expected {latest_tag}, got {pre_commit_rev}.\n"
45 )
46 sys.exit(1)
47
48
49 if __name__ == "__main__":
50 with open("CHANGES.md", encoding="utf-8") as fd:
51 changes = fd.read()
52 with open(
53 os.path.join("docs", "integrations", "source_version_control.md"),
54 encoding="utf-8",
55 ) as fd:
56 content = fd.read()
57 main(changes, content, "source_version_control.md")
58 with open(
59 os.path.join("docs", "guides", "using_black_with_jupyter_notebooks.md"),
60 encoding="utf-8",
61 ) as fd:
62 content = fd.read()
63 main(changes, content, "using_black_with_jupyter_notebooks.md")