Debian Codegraph @

scripts/diff_shades_gha_helper.py

raw
1 """Helper script for psf/black's diff-shades Github Actions integration.
2
3 diff-shades is a tool for analyzing what happens when you run Black on
4 OSS code capturing it for comparisons or other usage. It's used here to
5 help measure the impact of a change *before* landing it (in particular
6 posting a comment on completion for PRs).
7
8 This script exists as a more maintainable alternative to using inline
9 Javascript in the workflow YAML files. The revision configuration and
10 resolving, caching, and PR comment logic is contained here.
11
12 For more information, please see the developer docs:
13
14 https://black.readthedocs.io/en/latest/contributing/gauging_changes.html#diff-shades
15 """
16
17 import json
18 import os
19 import platform
20 import pprint
21 import subprocess
22 import sys
23 from base64 import b64encode
24 from os.path import dirname, join
25 from pathlib import Path
26 from typing import Any, Final
27
28 import click
29 import urllib3
30 from packaging.version import Version
31
32 COMMENT_FILE: Final = ".pr-comment.md"
33 DIFF_STEP_NAME: Final = "Generate HTML diff report"
34 DOCS_URL: Final = (
35 "https://black.readthedocs.io/en/latest/contributing/gauging_changes.html#diff-shades"
36 )
37 SHA_LENGTH: Final = 10
38 GH_API_TOKEN: Final = os.getenv("GITHUB_TOKEN")
39 REPO: Final = os.getenv("GITHUB_REPOSITORY", default="psf/black")
40 USER_AGENT: Final = f"{REPO} diff-shades workflow via urllib3/{urllib3.__version__}"
41 http = urllib3.PoolManager()
42
43
44 def set_output(name: str, value: str) -> None:
45 if len(value) < 200:
46 print(f"[INFO]: setting '{name}' to '{value}'")
47 else:
48 print(f"[INFO]: setting '{name}' to [{len(value)} chars]")
49
50 if "GITHUB_OUTPUT" in os.environ:
51 if "\n" in value:
52 # https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#multiline-strings
53 delimiter = b64encode(os.urandom(16)).decode()
54 value = f"{delimiter}\n{value}\n{delimiter}"
55 command = f"{name}<<{value}"
56 else:
57 command = f"{name}={value}"
58 with open(os.environ["GITHUB_OUTPUT"], "a") as f:
59 print(command, file=f)
60
61
62 def http_get(url: str, *, is_json: bool = True, **kwargs: Any) -> Any:
63 headers = kwargs.get("headers") or {}
64 headers["User-Agent"] = USER_AGENT
65 if "github" in url:
66 if GH_API_TOKEN:
67 headers["Authorization"] = f"token {GH_API_TOKEN}"
68 headers["Accept"] = "application/vnd.github.v3+json"
69 kwargs["headers"] = headers
70
71 r = http.request("GET", url, **kwargs)
72 if is_json:
73 data = json.loads(r.data.decode("utf-8"))
74 else:
75 data = r.data
76 print(f"[INFO]: issued GET request for {r.geturl()}")
77 if not (200 <= r.status < 300):
78 pprint.pprint(dict(r.info()))
79 pprint.pprint(data)
80 raise RuntimeError(f"unexpected status code: {r.status}")
81
82 return data
83
84
85 def get_latest_revision(ref: str) -> str:
86 data = http_get(
87 f"https://api.github.com/repos/{REPO}/commits",
88 fields={"per_page": "1", "sha": ref},
89 )
90 assert isinstance(data[0]["sha"], str)
91 return data[0]["sha"]
92
93
94 def get_pr_branches(pr: int | None = None) -> tuple[Any, Any, int]:
95 if not pr:
96 pr_ref = os.getenv("GITHUB_REF")
97 assert pr_ref is not None
98 pr = int(pr_ref[10:-6])
99
100 data = http_get(f"https://api.github.com/repos/{REPO}/pulls/{pr}")
101 assert isinstance(data["base"]["sha"], str)
102 assert isinstance(data["head"]["sha"], str)
103 return data["base"], data["head"], pr
104
105
106 def get_pypi_version() -> Version:
107 data = http_get("https://pypi.org/pypi/black/json")
108 versions = [Version(v) for v in data["releases"]]
109 sorted_versions = sorted(versions, reverse=True)
110 return sorted_versions[0]
111
112
113 @click.group()
114 def main() -> None:
115 pass
116
117
118 @main.command("config", help="Acquire run configuration and metadata.")
119 def config() -> None:
120 import diff_shades # type: ignore[import-not-found]
121
122 jobs = [{"mode": "preview-new-changes", "style": "preview"}]
123
124 event = os.getenv("GITHUB_EVENT_NAME")
125 if event == "push":
126 # Push on main, let's use PyPI Black as the baseline.
127 baseline_name = str(get_pypi_version())
128 baseline_cmd = f"git checkout {baseline_name}"
129
130 target_rev = os.getenv("GITHUB_SHA")
131 assert target_rev is not None
132 target_name = "main-" + target_rev[:SHA_LENGTH]
133 target_cmd = f"git checkout {target_rev}"
134
135 elif event == "pull_request":
136 jobs.insert(0, {"mode": "assert-no-changes", "style": "stable"})
137 # PR, let's use the PR base as the baseline.
138 base, head, pr_num = get_pr_branches()
139
140 baseline_rev = get_latest_revision(base["ref"])
141 baseline_name = f"{base['ref']}-{baseline_rev[:SHA_LENGTH]}"
142 baseline_cmd = f"git checkout {baseline_rev}"
143
144 target_name = f"pr-{pr_num}-{head['sha'][:SHA_LENGTH]}"
145 target_cmd = f"gh pr checkout {pr_num}\ngit merge origin/{base['ref']}"
146 else:
147 raise ValueError(f"Unknown event {event}")
148
149 env = f"{platform.system()}-{platform.python_version()}-{diff_shades.__version__}"
150 for entry in jobs:
151 entry["baseline-analysis"] = f"{entry['style']}-{baseline_name}.json"
152 entry["baseline-setup-cmd"] = baseline_cmd
153 entry["baseline-cache-key"] = f"{env}-{baseline_name}-{entry['style']}"
154
155 entry["target-analysis"] = f"{entry['style']}-{target_name}.json"
156 entry["target-setup-cmd"] = target_cmd
157
158 set_output("matrix", json.dumps(jobs, indent=None))
159 pprint.pprint(jobs)
160
161
162 @main.command("comment-body", help="Generate the body for a summary PR comment.")
163 @click.argument("baseline", type=click.Path(exists=True, path_type=Path))
164 @click.argument("target", type=click.Path(exists=True, path_type=Path))
165 @click.argument("style")
166 @click.argument("mode")
167 def comment_body(baseline: Path, target: Path, style: str, mode: str) -> None:
168 cmd = (
169 f"{sys.executable} -m diff_shades --no-color "
170 f"compare {baseline} {target} --quiet --check"
171 ).split(" ")
172 proc = subprocess.run(cmd, stdout=subprocess.PIPE, encoding="utf-8")
173 if proc.returncode:
174 run_id = os.getenv("GITHUB_RUN_ID")
175 jobs = http_get(
176 f"https://api.github.com/repos/{REPO}/actions/runs/{run_id}/jobs",
177 )["jobs"]
178 job = next(j for j in jobs if j["name"] == f"compare / {mode}")
179 diff_step = next(s for s in job["steps"] if s["name"] == DIFF_STEP_NAME)
180 diff_url = f"{job['html_url']}#step:{diff_step['number']}:1"
181
182 body = (
183 "<details>"
184 f"<summary><b><code>--{style}</code> style</b> "
185 f'(<a href="{diff_url}">View full diff</a>):</summary>'
186 f"<pre>{proc.stdout.strip()}</pre>"
187 "</details>"
188 )
189 else:
190 body = f"<b><code>--{style}</code> style</b>: no changes"
191
192 filename = f".{style}{COMMENT_FILE}"
193 print(f"[INFO]: writing comment details to {filename}")
194 with open(filename, "w", encoding="utf-8") as f:
195 f.write(body)
196
197
198 @main.command("comment-details", help="Get PR comment resources from a workflow run.")
199 @click.argument("pr")
200 @click.argument("run-id")
201 @click.argument("styles", nargs=-1)
202 def comment_details(pr: int, run_id: str, styles: tuple[str, ...]) -> None:
203 base, head, _ = get_pr_branches(pr)
204
205 lines = [
206 f"**diff-shades** results comparing this PR ({head['sha']}) to {base['ref']}"
207 f" ({base['sha']}):"
208 ]
209 for style_file in styles:
210 with open(
211 join(dirname(__file__), "..", style_file),
212 "r",
213 encoding="utf-8",
214 ) as f:
215 content = f.read()
216 lines.append(content)
217
218 lines.append("---")
219
220 lines.append(
221 f"[**What is this?**]({DOCS_URL}) | "
222 f"[Workflow run](https://github.com/psf/black/actions/runs/{run_id}) | "
223 "[diff-shades documentation](https://github.com/ichard26/diff-shades#readme)"
224 )
225
226 body = "\n\n".join(lines)
227 set_output("comment-body", body)
228
229
230 if __name__ == "__main__":
231 main()