Skip to content

Commit f6d98d6

Browse files
committed
Format python code with ruff
Same configuration as upstream Ladybird.
1 parent 7bca6fd commit f6d98d6

5 files changed

Lines changed: 63 additions & 109 deletions

File tree

.github/workflows/lint.yml

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ jobs:
66
lint:
77
runs-on: ubuntu-latest
88
steps:
9-
- uses: actions/checkout@v2
10-
- uses: actions/setup-python@v2
11-
- uses: psf/black@stable
9+
- uses: actions/checkout@v6
10+
- uses: astral-sh/ruff-action@v3
11+
- run: ruff check
12+
- run: ruff format --check
1213

main.py

Lines changed: 27 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,15 @@
2121
import sys
2222
import threading
2323
import traceback
24+
2425
from argparse import ArgumentParser
25-
from dataclasses import dataclass
2626
from collections import Counter
27+
from dataclasses import dataclass
2728
from enum import Enum
2829
from pathlib import Path
29-
from typing import Any, Callable, Optional
30+
from typing import Any
31+
from typing import Callable
32+
from typing import Optional
3033

3134
from tqdm import tqdm
3235

@@ -82,9 +85,7 @@ def run_streaming_script(
8285
) -> subprocess.CompletedProcess:
8386
def limit_memory():
8487
if platform.system() != "Darwin":
85-
resource.setrlimit(
86-
resource.RLIMIT_AS, (memory_limit * 1024 * 1024, resource.RLIM_INFINITY)
87-
)
88+
resource.setrlimit(resource.RLIMIT_AS, (memory_limit * 1024 * 1024, resource.RLIM_INFINITY))
8889

8990
command = [
9091
str(libjs_test262_runner),
@@ -127,11 +128,7 @@ def add_result(
127128
exit_code: int = 0,
128129
strict_mode: bool = False,
129130
) -> None:
130-
iteration_results.append(
131-
TestRun(
132-
test_file_paths[current_test], result, output, exit_code, strict_mode
133-
)
134-
)
131+
iteration_results.append(TestRun(test_file_paths[current_test], result, output, exit_code, strict_mode))
135132

136133
new_results = []
137134
while current_test < len(test_file_paths):
@@ -153,9 +150,7 @@ def add_result(
153150
process_failed = True
154151
process_result = e
155152

156-
test_results = [
157-
part.strip() for part in process_result.stdout.strip().split("\0")
158-
]
153+
test_results = [part.strip() for part in process_result.stdout.strip().split("\0")]
159154
have_stopping_result = False
160155

161156
while test_results:
@@ -167,7 +162,7 @@ def add_result(
167162
try:
168163
test_result = json.loads(test_result_string, strict=False)
169164
except json.decoder.JSONDecodeError:
170-
raise Exception(f"Could not parse JSON from '{test_result_string}'")
165+
raise Exception(f"Could not parse JSON from '{test_result_string}'") from None
171166

172167
file_name = Path(test_result["test"])
173168

@@ -229,10 +224,7 @@ def add_result(
229224
)
230225
current_test += 1
231226
elif forward_stderr is not None and process_result.stderr.strip() != "":
232-
forward_stderr(
233-
"Process did not fail but still there is stderr output:\n"
234-
+ process_result.stderr
235-
)
227+
forward_stderr("Process did not fail but still there is stderr output:\n" + process_result.stderr)
236228

237229
if on_progress_change is not None:
238230
on_progress_change(
@@ -281,13 +273,9 @@ def __init__(
281273
self.forward_stderr_function: Callable[[str], None] | None
282274
if forward_stderr:
283275
if self.silent:
284-
self.forward_stderr_function = lambda message: print(
285-
message, file=sys.stderr
286-
)
276+
self.forward_stderr_function = lambda message: print(message, file=sys.stderr)
287277
else:
288-
self.forward_stderr_function = lambda message: tqdm.write(
289-
message, file=sys.stderr
290-
)
278+
self.forward_stderr_function = lambda message: tqdm.write(message, file=sys.stderr)
291279
else:
292280
self.forward_stderr_function = None
293281

@@ -301,9 +289,7 @@ def find_tests(self, pattern: str, ignore: str) -> None:
301289
if Path(pattern).resolve().is_file():
302290
self.files = [Path(pattern).resolve()]
303291
else:
304-
ignored_files = set(
305-
glob.iglob(str(self.test262_root / ignore), recursive=True)
306-
)
292+
ignored_files = set(glob.iglob(str(self.test262_root / ignore), recursive=True))
307293
for path in glob.iglob(str(self.test262_root / pattern), recursive=True):
308294
found_path = Path(path)
309295
if (
@@ -340,7 +326,7 @@ def build_directory_result_map(self) -> None:
340326
directory = file.relative_to(self.test262_root).parent
341327
counter = self.directory_result_map
342328
for segment in directory.parts:
343-
if not segment in counter:
329+
if segment not in counter:
344330
counter[segment] = {"count": 1, "results": {}, "children": {}}
345331
for result in TestResult:
346332
counter[segment]["results"][result] = 0
@@ -375,9 +361,7 @@ def print_tree(tree, path, level):
375361
passed = tree["results"][TestResult.PASSED]
376362
percentage = (passed / count) * 100
377363
pad = " " * (80 - len(path))
378-
self.print_output(
379-
f"{path}{pad}{passed:>5}/{count:<5} ({percentage:6.2f}%) {results} "
380-
)
364+
self.print_output(f"{path}{pad}{passed:>5}/{count:<5} ({percentage:6.2f}%) {results} ")
381365
if passed > 0:
382366
for k, v in tree["children"].items():
383367
print_tree(v, path + "/" + k, level + 1)
@@ -400,13 +384,11 @@ def process_list(self, files: list[Path]) -> list[TestRun]:
400384
on_progress_change=self.update_function,
401385
forward_stderr=self.forward_stderr_function,
402386
)
403-
except Exception as e:
387+
except Exception:
404388
return [
405389
TestRun(
406390
file,
407-
result=(
408-
TestResult.RUNNER_EXCEPTION if i == 0 else TestResult.SKIPPED
409-
),
391+
result=(TestResult.RUNNER_EXCEPTION if i == 0 else TestResult.SKIPPED),
410392
output=traceback.format_exc() if i == 0 else "",
411393
exit_code=None,
412394
strict_mode=None,
@@ -432,11 +414,10 @@ def run(self) -> None:
432414
work_lists[index % amount_of_work_lists].append(test_path)
433415

434416
if not self.silent:
435-
progressbar = tqdm(
436-
total=self.total_count, mininterval=1, unit="tests", smoothing=0.1
437-
)
417+
progressbar = tqdm(total=self.total_count, mininterval=1, unit="tests", smoothing=0.1)
418+
total_stats = Counter()
438419

439-
def update_progress(value, new_results, total_stats=Counter()):
420+
def update_progress(value, new_results):
440421
progress_mutex.acquire()
441422
total_stats.update(new_results)
442423
try:
@@ -455,18 +436,13 @@ def write_output(message: Any):
455436
start = datetime.datetime.now()
456437

457438
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
458-
futures = [
459-
executor.submit(self.process_list, file_list)
460-
for file_list in work_lists
461-
]
439+
futures = [executor.submit(self.process_list, file_list) for file_list in work_lists]
462440

463441
for future in concurrent.futures.as_completed(futures):
464442
test_runs = future.result()
465443
for test_run in test_runs:
466444
self.count_result(test_run)
467-
if self.verbose or (
468-
self.fail_only and test_run.result not in NON_FAIL_RESULTS
469-
):
445+
if self.verbose or (self.fail_only and test_run.result not in NON_FAIL_RESULTS):
470446
self.print_output(
471447
f"{EMOJIS[test_run.result]} {test_run.file}"
472448
f"{' (strict mode)' if test_run.strict_mode else ''}"
@@ -480,9 +456,7 @@ def write_output(message: Any):
480456
signalnum = test_run.exit_code * -1
481457
if not test_run.output:
482458
self.print_output("")
483-
self.print_output(
484-
f"{signal.strsignal(signalnum)}: {signalnum}"
485-
)
459+
self.print_output(f"{signal.strsignal(signalnum)}: {signalnum}")
486460
self.print_output("")
487461

488462
if not self.silent:
@@ -498,9 +472,7 @@ def default_test262_runner_path() -> Path | None:
498472
ladybird_source_dir = os.environ.get("LADYBIRD_SOURCE_DIR")
499473

500474
if ladybird_source_dir:
501-
default_test262_runner = (
502-
Path(ladybird_source_dir) / "Build" / "release" / "bin" / "test262-runner"
503-
)
475+
default_test262_runner = Path(ladybird_source_dir) / "Build" / "release" / "bin" / "test262-runner"
504476

505477
if default_test262_runner.exists():
506478
return default_test262_runner
@@ -555,9 +527,7 @@ def main() -> None:
555527
type=int,
556528
help="memory limit for each test run in megabytes (defaults to 512)",
557529
)
558-
parser.add_argument(
559-
"--json", action="store_true", help="print the test results as JSON"
560-
)
530+
parser.add_argument("--json", action="store_true", help="print the test results as JSON")
561531
parser.add_argument(
562532
"--per-file",
563533
default=None,
@@ -572,13 +542,9 @@ def main() -> None:
572542
action="store_true",
573543
help="don't print any progress information",
574544
)
575-
logging_group.add_argument(
576-
"-v", "--verbose", action="store_true", help="print output of test runs"
577-
)
545+
logging_group.add_argument("-v", "--verbose", action="store_true", help="print output of test runs")
578546

579-
parser.add_argument(
580-
"-f", "--fail-only", action="store_true", help="only show failed tests"
581-
)
547+
parser.add_argument("-f", "--fail-only", action="store_true", help="only show failed tests")
582548
parser.add_argument(
583549
"--parse-only",
584550
action="store_true",

per_file_result_diff.py

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,25 @@
11
#!/usr/bin/env python3
2+
23
# Copyright (c) 2021, Matthew Olsson <mattco@serenityos.org>
34
#
45
# SPDX-License-Identifier: MIT
56

67
import json
8+
79
from argparse import ArgumentParser
810
from pathlib import Path
9-
from main import TestResult, EMOJIS
11+
12+
from main import EMOJIS
13+
from main import TestResult
1014

1115

1216
class ResultParser:
13-
def __init__(
14-
self, old_path: Path, new_path: Path, regressions: bool, intersection_only: bool
15-
) -> None:
17+
def __init__(self, old_path: Path, new_path: Path, regressions: bool, intersection_only: bool) -> None:
1618
old_results = json.loads(old_path.read_text())
1719
new_results = json.loads(new_path.read_text())
1820

19-
self.duration_delta = float(new_results["duration"]) - float(
20-
old_results["duration"]
21-
)
22-
self.old_results: dict[str, str] = {
23-
k: v for k, v in sorted(old_results["results"].items())
24-
}
21+
self.duration_delta = float(new_results["duration"]) - float(old_results["duration"])
22+
self.old_results: dict[str, str] = {k: v for k, v in sorted(old_results["results"].items())}
2523
self.new_results: dict[str, str] = new_results["results"]
2624
self.regressions = regressions
2725
self.intersection_only = intersection_only
@@ -147,18 +145,14 @@ def print_full_results(self) -> None:
147145
for path, result in self.diff_tests.items():
148146
old_emoji = EMOJIS[result["old_result"]]
149147
new_emoji = EMOJIS[result["new_result"]]
150-
print(
151-
f" {path:{self.longest_path_length}s} {old_emoji} -> {new_emoji}"
152-
)
148+
print(f" {path:{self.longest_path_length}s} {old_emoji} -> {new_emoji}")
153149

154150
def print_regressions(self) -> None:
155151
for path, result in self.diff_tests.items():
156152
if result["old_result"] == "PASSED":
157153
old_emoji = EMOJIS[TestResult.PASSED]
158154
new_emoji = EMOJIS[result["new_result"]]
159-
print(
160-
f" {path:{self.longest_path_length}s} {old_emoji} -> {new_emoji}"
161-
)
155+
print(f" {path:{self.longest_path_length}s} {old_emoji} -> {new_emoji}")
162156

163157
def print_results(self) -> None:
164158
if self.regressions:
@@ -169,12 +163,8 @@ def print_results(self) -> None:
169163

170164
def main() -> None:
171165
parser = ArgumentParser(description="Compare per-file test262 results")
172-
parser.add_argument(
173-
"-o", "--old", required=True, metavar="PATH", help="the path to the old results"
174-
)
175-
parser.add_argument(
176-
"-n", "--new", required=True, metavar="PATH", help="the path to the new results"
177-
)
166+
parser.add_argument("-o", "--old", required=True, metavar="PATH", help="the path to the old results")
167+
parser.add_argument("-n", "--new", required=True, metavar="PATH", help="the path to the new results")
178168
parser.add_argument(
179169
"-r",
180170
"--regressions",
@@ -189,9 +179,7 @@ def main() -> None:
189179
)
190180
args = parser.parse_args()
191181

192-
ResultParser(
193-
Path(args.old), Path(args.new), args.regressions, args.intersection_only
194-
).print_results()
182+
ResultParser(Path(args.old), Path(args.new), args.regressions, args.intersection_only).print_results()
195183

196184

197185
if __name__ == "__main__":

pyproject.toml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
[tool.ruff]
2+
line-length = 120
3+
4+
[tool.ruff.lint]
5+
# https://docs.astral.sh/ruff/rules/
6+
extend-select = [
7+
"B", # flake8-bugbear
8+
"I", # isort
9+
]
10+
11+
[tool.ruff.lint.isort]
12+
force-single-line = true
13+
lines-between-types = 1

run_all_and_update_results.py

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,13 @@
1010
import subprocess
1111
import sys
1212
import time
13+
1314
from argparse import ArgumentParser
1415
from pathlib import Path
1516

1617

1718
def run_command(command: str, **kwargs) -> str:
18-
process = subprocess.run(
19-
shlex.split(command), stdout=subprocess.PIPE, text=True, **kwargs
20-
)
19+
process = subprocess.run(shlex.split(command), stdout=subprocess.PIPE, text=True, **kwargs)
2120
return process.stdout.strip()
2221

2322

@@ -53,10 +52,7 @@ def main() -> None:
5352
# the result would be incomplete anyway.
5453

5554
parser = ArgumentParser(
56-
description=(
57-
"Run the test262 and test262-parser-tests with "
58-
"LibJS and update the results JSON file"
59-
)
55+
description=("Run the test262 and test262-parser-tests with LibJS and update the results JSON file")
6056
)
6157
parser.add_argument(
6258
"--serenity",
@@ -113,21 +109,15 @@ def main() -> None:
113109

114110
serenity_test_js = find_lagom_executable(libjs_test262, serenity, "test-js")
115111

116-
libjs_test262_runner = find_lagom_executable(
117-
libjs_test262, serenity, "test262-runner"
118-
)
112+
libjs_test262_runner = find_lagom_executable(libjs_test262, serenity, "test262-runner")
119113
libjs_test262_main_py = libjs_test262 / "main.py"
120114

121115
version_serenity = get_git_revision(serenity)
122116
version_libjs_test262 = get_git_revision(libjs_test262)
123117
version_test262 = get_git_revision(test262)
124118
version_test262_parser_tests = get_git_revision(test262_parser_tests)
125119

126-
result_for_current_revision = (
127-
result
128-
for result in results
129-
if result["versions"]["serenity"] == version_serenity
130-
)
120+
result_for_current_revision = (result for result in results if result["versions"]["serenity"] == version_serenity)
131121
if next(result_for_current_revision, None):
132122
print(
133123
f"Result for revision {version_serenity[:7]} already exists, "
@@ -152,11 +142,7 @@ def main() -> None:
152142
f"--libjs-test262-runner {libjs_test262_runner} "
153143
f"--test262 {test262} "
154144
"--silent --summary --json "
155-
+ (
156-
""
157-
if args.per_file_output is None
158-
else f"--per-file {args.per_file_output} "
159-
)
145+
+ ("" if args.per_file_output is None else f"--per-file {args.per_file_output} ")
160146
)
161147
)
162148
libjs_test262_results = libjs_test262_output["results"]["test"]["results"]

0 commit comments

Comments
 (0)