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