Skip to content

Commit 6f8c2a4

Browse files
authored
Merge pull request #924 from nathanchance/ruff-format
continuous-integration2: Switch to ruff for Python formatting
2 parents 815c834 + 734403e commit 6f8c2a4

16 files changed

Lines changed: 347 additions & 294 deletions

caching/check.py

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
we want to only cache on a "pass" or "fail" status as these mean that Tuxsuite
3737
actually completed its work and didnt timeout.
3838
"""
39+
3940
import argparse
4041
import json
4142
import os
@@ -48,7 +49,11 @@
4849
# pylint: disable-next=import-error
4950
import requests
5051

51-
from utils import get_patches_hash, get_workflow_name_to_var_name, update_repository_variable
52+
from utils import (
53+
get_patches_hash,
54+
get_workflow_name_to_var_name,
55+
update_repository_variable,
56+
)
5257

5358
OWNER = "ClangBuiltLinux"
5459
REPO = "continuous-integration2"
@@ -63,8 +68,7 @@
6368
TIMEOUT = 64
6469

6570

66-
class MalformedCacheError(Exception):
67-
...
71+
class MalformedCacheError(Exception): ...
6872

6973

7074
def parse_args():
@@ -107,17 +111,16 @@ def ___purge___cache___():
107111
list_response = requests.get(list_url, headers=headers, timeout=TIMEOUT)
108112
print(list_response.content)
109113
all_variables_keys = [
110-
x["name"] for x in json.loads(list_response.content)["variables"]
114+
x["name"]
115+
for x in json.loads(list_response.content)["variables"]
111116
if x["name"].startswith("_")
112117
]
113118

114119
for key in all_variables_keys:
115120
delete_url = (
116121
f"https://api.github.com/repos/{OWNER}/{REPO}/actions/variables/{key}"
117122
)
118-
delete_response = requests.delete(delete_url,
119-
headers=headers,
120-
timeout=TIMEOUT)
123+
delete_response = requests.delete(delete_url, headers=headers, timeout=TIMEOUT)
121124
if delete_response.status_code != 204:
122125
print(f"ERROR: Couldn't delete cache entry with key {key}")
123126
sys.exit(1)
@@ -154,16 +157,19 @@ def get_repository_variable_or_none(name: str) -> Optional[dict]:
154157
return json.loads(as_dict["value"])
155158

156159

157-
def create_repository_variable(name: str, linux_sha: str, clang_version: str,
158-
patches_hash: str) -> None:
160+
def create_repository_variable(
161+
name: str, linux_sha: str, clang_version: str, patches_hash: str
162+
) -> None:
159163
_url = f"https://api.github.com/repos/{OWNER}/{REPO}/actions/variables"
160164

161-
_value = json.dumps({
162-
"linux_sha": linux_sha,
163-
"clang_version": clang_version,
164-
"patches_hash": patches_hash,
165-
"build_status": "presuite",
166-
})
165+
_value = json.dumps(
166+
{
167+
"linux_sha": linux_sha,
168+
"clang_version": clang_version,
169+
"patches_hash": patches_hash,
170+
"build_status": "presuite",
171+
}
172+
)
167173
data = {"name": name, "value": _value}
168174

169175
resp = requests.post(_url, headers=headers, json=data, timeout=TIMEOUT)
@@ -199,8 +205,10 @@ def create_repository_variable(name: str, linux_sha: str, clang_version: str,
199205
# pull down repo variable
200206
result = get_repository_variable_or_none(VAR_NAME)
201207
if result is None:
202-
print(f"CACHE MISS: Did not find repo variable {VAR_NAME} "
203-
f"from workflow_name: {args.workflow_name}. Creating it now.")
208+
print(
209+
f"CACHE MISS: Did not find repo variable {VAR_NAME} "
210+
f"from workflow_name: {args.workflow_name}. Creating it now."
211+
)
204212
create_repository_variable(
205213
VAR_NAME,
206214
linux_sha=curr_sha,
@@ -219,14 +227,19 @@ def create_repository_variable(name: str, linux_sha: str, clang_version: str,
219227
raise MalformedCacheError(
220228
f"The cache with key {VAR_NAME} based on workflow '{args.workflow_name}' "
221229
f"is one or more fields. It's missing: {missing_fields}\n"
222-
f"The current cache looks as follows:\n{result}.")
230+
f"The current cache looks as follows:\n{result}."
231+
)
223232

224233
cached_sha = result["linux_sha"]
225234
cached_clang_version = result["clang_version"]
226235
cached_build_status = result["build_status"]
227236
cached_patches_hash = result.get("patches_hash", curr_patches_hash)
228237

229-
if cached_sha != curr_sha or cached_clang_version != curr_clang_version or cached_patches_hash != curr_patches_hash:
238+
if (
239+
cached_sha != curr_sha
240+
or cached_clang_version != curr_clang_version
241+
or cached_patches_hash != curr_patches_hash
242+
):
230243
print(f"""\
231244
CACHE MISS: current linux_sha is {curr_sha}, clang_version is {curr_clang_version},
232245
and current patches_hash is {curr_patches_hash} while {args.workflow_name} has
@@ -271,5 +284,4 @@ def create_repository_variable(name: str, linux_sha: str, clang_version: str,
271284
with open(env_file, "a", encoding="utf-8") as fd:
272285
fd.write(f"CACHE_PASS={cached_build_status.strip()}")
273286

274-
sys.exit(
275-
0) # signifies to the workflow that no jobs should run ('success')
287+
sys.exit(0) # signifies to the workflow that no jobs should run ('success')

caching/update.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@
2929
import urllib.request
3030
from pathlib import Path
3131

32-
from utils import get_patches_hash, get_workflow_name_to_var_name, update_repository_variable
32+
from utils import (
33+
get_patches_hash,
34+
get_workflow_name_to_var_name,
35+
update_repository_variable,
36+
)
3337

3438
if "GITHUB_WORKFLOW" not in os.environ:
3539
print("Couldn't find GITHUB_WORKFLOW in env. Not in a GitHub Workflow?")
@@ -38,15 +42,12 @@
3842
MOCK = "MOCK" in os.environ
3943

4044

41-
def update_cache(status: str, git_sha: str, clang_version: str,
42-
patches_hash: str):
45+
def update_cache(status: str, git_sha: str, clang_version: str, patches_hash: str):
4346
print(f"Trying to update cache with status: {status}")
44-
cache_entry_key = get_workflow_name_to_var_name(
45-
os.environ["GITHUB_WORKFLOW"])
47+
cache_entry_key = get_workflow_name_to_var_name(os.environ["GITHUB_WORKFLOW"])
4648

4749
if "REPO_SCOPED_PAT" not in os.environ:
48-
print(
49-
"Couldn't find REPO_SCOPED_PAT in env. Not in a GitHub Workflow?")
50+
print("Couldn't find REPO_SCOPED_PAT in env. Not in a GitHub Workflow?")
5051
sys.exit(1)
5152

5253
headers = {"Authorization": f"Bearer {os.environ['REPO_SCOPED_PAT']}"}
@@ -82,8 +83,7 @@ def main():
8283
for entry, build in builds.items():
8384
try:
8485
git_sha = build["git_sha"]
85-
clang_version = build["tuxmake_metadata"]["compiler"][
86-
"version_full"]
86+
clang_version = build["tuxmake_metadata"]["compiler"]["version_full"]
8787
break
8888
except KeyError:
8989
builds_that_are_missing_metadata.append(entry)
@@ -100,32 +100,32 @@ def main():
100100
build_log_raw = response.read().decode()
101101

102102
failed_pattern = (
103-
r"(?<=Apply patch set FAILED\s)[0-9A-Za-z._:/\-\s]*?(?=\serror: )")
103+
r"(?<=Apply patch set FAILED\s)[0-9A-Za-z._:/\-\s]*?(?=\serror: )"
104+
)
104105
failed_matches = re.findall(failed_pattern, build_log_raw)
105106
if len(failed_matches) == 0:
106107
print(
107108
f"No patches failed to apply yet the build status stated there were: {build['status_message']}"
108109
)
109-
sys.exit(
110-
0) # Not sure how we got here but continue the action anyways
110+
sys.exit(0) # Not sure how we got here but continue the action anyways
111111

112112
patches_that_failed_to_apply = failed_matches[0].split('\n')
113-
print(
114-
f"Error: Some patches failed to apply.\n{patches_that_failed_to_apply}\n"
115-
)
113+
print(f"Error: Some patches failed to apply.\n{patches_that_failed_to_apply}\n")
116114
sys.exit(1)
117115

118116
if len(builds_that_are_missing_metadata) == len(builds):
119117
raise RuntimeError(
120118
f"Could not find a suitable git sha or compiler version in any build\n"
121-
f"Here's the build.json:\n{raw}")
119+
f"Here's the build.json:\n{raw}"
120+
)
122121

123122
if len(builds_that_are_missing_metadata) > 0:
124123
print(
125124
"Warning: Some of the builds in builds.json are malformed and missing "
126125
"some metadata.\n"
127126
f"Here's a list: {builds_that_are_missing_metadata}\n"
128-
f"Here's the build.json in question:\n{raw}")
127+
f"Here's the build.json in question:\n{raw}"
128+
)
129129

130130
assert git_sha and clang_version
131131

generator/generate.py

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -17,34 +17,36 @@
1717

1818

1919
def parse_args(trees):
20-
parser = ArgumentParser(
21-
description='Generate yml files and perform extra checks')
20+
parser = ArgumentParser(description='Generate yml files and perform extra checks')
2221

23-
parser.add_argument('-c',
24-
'--check',
25-
action='store_true',
26-
help='Fail if generating yml files results in a diff')
22+
parser.add_argument(
23+
'-c',
24+
'--check',
25+
action='store_true',
26+
help='Fail if generating yml files results in a diff',
27+
)
2728
parser.add_argument(
2829
'trees',
2930
choices=[*trees, 'all'],
3031
default='all',
3132
help='The trees to generate yml files for (default: all)',
3233
metavar='TREES',
33-
nargs='*')
34+
nargs='*',
35+
)
3436

3537
return parser.parse_args()
3638

3739

3840
def update_llvm_tot_version():
3941
# Avoids pulling in an extra Python package dependency
4042
curl_cmd = [
41-
'curl', '-fLSs',
42-
'https://raw.githubusercontent.com/llvm/llvm-project/main/cmake/Modules/LLVMVersion.cmake'
43+
'curl',
44+
'-fLSs',
45+
'https://raw.githubusercontent.com/llvm/llvm-project/main/cmake/Modules/LLVMVersion.cmake',
4346
]
44-
cmakelists = subprocess.run(curl_cmd,
45-
capture_output=True,
46-
check=True,
47-
text=True).stdout
47+
cmakelists = subprocess.run(
48+
curl_cmd, capture_output=True, check=True, text=True
49+
).stdout
4850

4951
if not (match := re.search(r'set\(LLVM_VERSION_MAJOR (\d+)', cmakelists)):
5052
raise RuntimeError('Could not find LLVM_VERSION_MAJOR?')
@@ -64,21 +66,23 @@ def generate(config, tree):
6466

6567
def check(trees_arg):
6668
try:
67-
subprocess.run(['git', 'rev-parse', '--git-dir'],
68-
check=True,
69-
capture_output=True)
69+
subprocess.run(
70+
['git', 'rev-parse', '--git-dir'], check=True, capture_output=True
71+
)
7072
except subprocess.CalledProcessError:
7173
# Print a nicer error message versus spewing the exception
7274
print('Script is not being run inside a git repository!')
7375
sys.exit(1)
7476

7577
if subprocess.run(
7678
['git', '--no-optional-locks', 'status', '-uno', '--porcelain'],
77-
capture_output=True,
78-
check=True).stdout:
79+
capture_output=True,
80+
check=True,
81+
).stdout:
7982
print(
8083
f"\nRunning 'generate.py {trees_arg}' generated the following diff:\n",
81-
flush=True)
84+
flush=True,
85+
)
8286
subprocess.run(['git', '--no-pager', 'diff', 'HEAD'], check=True)
8387
print(
8488
"\nPlease run 'generate.py all' locally then commit and push the changes it creates!"

0 commit comments

Comments
 (0)