Skip to content

Commit 5614605

Browse files
hugovksobolevn
andauthored
[3.13] gh-139590: Stricter ruff rules for Tools/wasm (GH-139752) (#140986)
Co-authored-by: sobolevn <[email protected]>
1 parent ac0ecb0 commit 5614605

File tree

7 files changed

+48
-70
lines changed

7 files changed

+48
-70
lines changed

.github/workflows/mypy.yml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ on:
2727
- "Tools/jit/**"
2828
- "Tools/peg_generator/**"
2929
- "Tools/requirements-dev.txt"
30-
- "Tools/wasm/**"
3130
workflow_dispatch:
3231

3332
permissions:
@@ -59,7 +58,6 @@ jobs:
5958
"Tools/clinic",
6059
"Tools/jit",
6160
"Tools/peg_generator",
62-
"Tools/wasm",
6361
]
6462
steps:
6563
- uses: actions/checkout@v4

.pre-commit-config.yaml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ repos:
2222
name: Run Ruff (lint) on Tools/peg_generator/
2323
args: [--exit-non-zero-on-fix, --config=Tools/peg_generator/.ruff.toml]
2424
files: ^Tools/peg_generator/
25+
- id: ruff-check
26+
name: Run Ruff (lint) on Tools/wasm/
27+
args: [--exit-non-zero-on-fix, --config=Tools/wasm/.ruff.toml]
28+
files: ^Tools/wasm/
2529
- id: ruff-format
2630
name: Run Ruff (format) on Doc/
2731
args: [--check]

Tools/wasm/.ruff.toml

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,4 @@ select = [
2222
]
2323
ignore = [
2424
"E501", # Line too long
25-
"F541", # f-string without any placeholders
26-
"PYI024", # Use `typing.NamedTuple` instead of `collections.namedtuple`
27-
"PYI025", # Use `from collections.abc import Set as AbstractSet`
2825
]

Tools/wasm/mypy.ini

Lines changed: 0 additions & 11 deletions
This file was deleted.

Tools/wasm/wasi.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,13 @@
1616
import sysconfig
1717
import tempfile
1818

19-
2019
CHECKOUT = pathlib.Path(__file__).parent.parent.parent
2120

2221
CROSS_BUILD_DIR = CHECKOUT / "cross-build"
2322
BUILD_DIR = CROSS_BUILD_DIR / "build"
2423

2524
LOCAL_SETUP = CHECKOUT / "Modules" / "Setup.local"
26-
LOCAL_SETUP_MARKER = "# Generated by Tools/wasm/wasi.py\n".encode("utf-8")
25+
LOCAL_SETUP_MARKER = b"# Generated by Tools/wasm/wasi.py\n"
2726

2827
WASMTIME_VAR_NAME = "WASMTIME"
2928
WASMTIME_HOST_RUNNER_VAR = f"{{{WASMTIME_VAR_NAME}}}"
@@ -84,7 +83,7 @@ def wrapper(context):
8483
and getattr(context, "clean", False)
8584
and working_dir.exists()
8685
):
87-
print(f"🚮 Deleting directory (--clean)...")
86+
print("🚮 Deleting directory (--clean)...")
8887
shutil.rmtree(working_dir)
8988

9089
working_dir.mkdir(parents=True, exist_ok=True)
@@ -372,7 +371,7 @@ def main():
372371
make_host = subcommands.add_parser(
373372
"make-host", help="Run `make` for the host/WASI"
374373
)
375-
clean = subcommands.add_parser(
374+
subcommands.add_parser(
376375
"clean", help="Delete files and directories created by this script"
377376
)
378377
for subcommand in (

Tools/wasm/wasm_assets.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
import sys
1717
import sysconfig
1818
import zipfile
19-
from typing import Dict
2019

2120
# source directory
2221
SRCDIR = pathlib.Path(__file__).parent.parent.parent.absolute()
@@ -147,7 +146,7 @@ def filterfunc(filename: str) -> bool:
147146
pzf.writepy(entry, filterfunc=filterfunc)
148147

149148

150-
def detect_extension_modules(args: argparse.Namespace) -> Dict[str, bool]:
149+
def detect_extension_modules(args: argparse.Namespace) -> dict[str, bool]:
151150
modules = {}
152151

153152
# disabled by Modules/Setup.local ?
@@ -162,7 +161,7 @@ def detect_extension_modules(args: argparse.Namespace) -> Dict[str, bool]:
162161
# disabled by configure?
163162
with open(args.sysconfig_data) as f:
164163
data = f.read()
165-
loc: Dict[str, Dict[str, str]] = {}
164+
loc: dict[str, dict[str, str]] = {}
166165
exec(data, globals(), loc)
167166

168167
for key, value in loc["build_time_vars"].items():

Tools/wasm/wasm_build.py

Lines changed: 39 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@
2323
"""
2424

2525
import argparse
26-
import enum
2726
import dataclasses
27+
import enum
2828
import logging
2929
import os
3030
import pathlib
@@ -39,18 +39,12 @@
3939
import time
4040
import warnings
4141
import webbrowser
42+
from collections.abc import Callable, Iterable
4243

4344
# for Python 3.8
4445
from typing import (
45-
cast,
4646
Any,
47-
Callable,
48-
Dict,
49-
Iterable,
50-
List,
51-
Optional,
52-
Tuple,
53-
Union,
47+
cast,
5448
)
5549

5650
logger = logging.getLogger("wasm_build")
@@ -122,7 +116,7 @@
122116

123117
def parse_emconfig(
124118
emconfig: pathlib.Path = EM_CONFIG,
125-
) -> Tuple[pathlib.Path, pathlib.Path]:
119+
) -> tuple[pathlib.Path, pathlib.Path]:
126120
"""Parse EM_CONFIG file and lookup EMSCRIPTEN_ROOT and NODE_JS.
127121
128122
The ".emscripten" config file is a Python snippet that uses "EM_CONFIG"
@@ -134,7 +128,7 @@ def parse_emconfig(
134128
with open(emconfig, encoding="utf-8") as f:
135129
code = f.read()
136130
# EM_CONFIG file is a Python snippet
137-
local: Dict[str, Any] = {}
131+
local: dict[str, Any] = {}
138132
exec(code, globals(), local)
139133
emscripten_root = pathlib.Path(local["EMSCRIPTEN_ROOT"])
140134
node_js = pathlib.Path(local["NODE_JS"])
@@ -192,16 +186,16 @@ class Platform:
192186

193187
name: str
194188
pythonexe: str
195-
config_site: Optional[pathlib.PurePath]
196-
configure_wrapper: Optional[pathlib.Path]
197-
make_wrapper: Optional[pathlib.PurePath]
198-
environ: Dict[str, Any]
189+
config_site: pathlib.PurePath | None
190+
configure_wrapper: pathlib.Path | None
191+
make_wrapper: pathlib.PurePath | None
192+
environ: dict[str, Any]
199193
check: Callable[[], None]
200194
# Used for build_emports().
201-
ports: Optional[pathlib.PurePath]
202-
cc: Optional[pathlib.PurePath]
195+
ports: pathlib.PurePath | None
196+
cc: pathlib.PurePath | None
203197

204-
def getenv(self, profile: "BuildProfile") -> Dict[str, Any]:
198+
def getenv(self, profile: "BuildProfile") -> dict[str, Any]:
205199
return self.environ.copy()
206200

207201

@@ -264,7 +258,7 @@ def _check_emscripten() -> None:
264258
# git / upstream / tot-upstream installation
265259
version = version[:-4]
266260
version_tuple = cast(
267-
Tuple[int, int, int], tuple(int(v) for v in version.split("."))
261+
tuple[int, int, int], tuple(int(v) for v in version.split("."))
268262
)
269263
if version_tuple < EMSDK_MIN_VERSION:
270264
raise ConditionError(
@@ -388,7 +382,7 @@ def get_extra_paths(self) -> Iterable[pathlib.PurePath]:
388382
return []
389383

390384
@property
391-
def emport_args(self) -> List[str]:
385+
def emport_args(self) -> list[str]:
392386
"""Host-specific port args (Emscripten)."""
393387
cls = type(self)
394388
if self is cls.wasm64_emscripten:
@@ -399,7 +393,7 @@ def emport_args(self) -> List[str]:
399393
return []
400394

401395
@property
402-
def embuilder_args(self) -> List[str]:
396+
def embuilder_args(self) -> list[str]:
403397
"""Host-specific embuilder args (Emscripten)."""
404398
cls = type(self)
405399
if self is cls.wasm64_emscripten:
@@ -422,7 +416,7 @@ def is_browser(self) -> bool:
422416
return self in {cls.browser, cls.browser_debug}
423417

424418
@property
425-
def emport_args(self) -> List[str]:
419+
def emport_args(self) -> list[str]:
426420
"""Target-specific port args."""
427421
cls = type(self)
428422
if self in {cls.browser_debug, cls.node_debug}:
@@ -448,9 +442,9 @@ class BuildProfile:
448442
name: str
449443
support_level: SupportLevel
450444
host: Host
451-
target: Union[EmscriptenTarget, None] = None
452-
dynamic_linking: Union[bool, None] = None
453-
pthreads: Union[bool, None] = None
445+
target: EmscriptenTarget | None = None
446+
dynamic_linking: bool | None = None
447+
pthreads: bool | None = None
454448
default_testopts: str = "-j2"
455449

456450
@property
@@ -474,7 +468,7 @@ def makefile(self) -> pathlib.Path:
474468
return self.builddir / "Makefile"
475469

476470
@property
477-
def configure_cmd(self) -> List[str]:
471+
def configure_cmd(self) -> list[str]:
478472
"""Generate configure command"""
479473
# use relative path, so WASI tests can find lib prefix.
480474
# pathlib.Path.relative_to() does not work here.
@@ -509,15 +503,15 @@ def configure_cmd(self) -> List[str]:
509503
return cmd
510504

511505
@property
512-
def make_cmd(self) -> List[str]:
506+
def make_cmd(self) -> list[str]:
513507
"""Generate make command"""
514508
cmd = ["make"]
515509
platform = self.host.platform
516510
if platform.make_wrapper:
517511
cmd.insert(0, os.fspath(platform.make_wrapper))
518512
return cmd
519513

520-
def getenv(self) -> Dict[str, Any]:
514+
def getenv(self) -> dict[str, Any]:
521515
"""Generate environ dict for platform"""
522516
env = os.environ.copy()
523517
if hasattr(os, "process_cpu_count"):
@@ -531,7 +525,7 @@ def getenv(self) -> Dict[str, Any]:
531525
env.pop(key, None)
532526
elif key == "PATH":
533527
# list of path items, prefix with extra paths
534-
new_path: List[pathlib.PurePath] = []
528+
new_path: list[pathlib.PurePath] = []
535529
new_path.extend(self.host.get_extra_paths())
536530
new_path.extend(value)
537531
env[key] = os.pathsep.join(os.fspath(p) for p in new_path)
@@ -549,7 +543,7 @@ def _run_cmd(
549543
self,
550544
cmd: Iterable[str],
551545
args: Iterable[str] = (),
552-
cwd: Optional[pathlib.Path] = None,
546+
cwd: pathlib.Path | None = None,
553547
) -> int:
554548
cmd = list(cmd)
555549
cmd.extend(args)
@@ -587,7 +581,7 @@ def run_pythoninfo(self, *args: str) -> int:
587581
self._check_execute()
588582
return self.run_make("pythoninfo", *args)
589583

590-
def run_test(self, target: str, testopts: Optional[str] = None) -> int:
584+
def run_test(self, target: str, testopts: str | None = None) -> int:
591585
"""Run buildbottests"""
592586
self._check_execute()
593587
if testopts is None:
@@ -823,29 +817,27 @@ def build_emports(self, force: bool = False) -> None:
823817
)
824818

825819
# Don't list broken and experimental variants in help
826-
platforms_choices = list(p.name for p in _profiles) + ["cleanall"]
827-
platforms_help = list(p.name for p in _profiles if p.support_level) + [
828-
"cleanall"
829-
]
820+
platforms_choices = [p.name for p in _profiles] + ["cleanall"]
821+
platforms_help = [p.name for p in _profiles if p.support_level] + ["cleanall"]
830822
parser.add_argument(
831823
"platform",
832824
metavar="PLATFORM",
833825
help=f"Build platform: {', '.join(platforms_help)}",
834826
choices=platforms_choices,
835827
)
836828

837-
ops = dict(
838-
build="auto build (build 'build' Python, emports, configure, compile)",
839-
configure="run ./configure",
840-
compile="run 'make all'",
841-
pythoninfo="run 'make pythoninfo'",
842-
test="run 'make buildbottest TESTOPTS=...' (supports parallel tests)",
843-
hostrunnertest="run 'make hostrunnertest TESTOPTS=...'",
844-
repl="start interactive REPL / webserver + browser session",
845-
clean="run 'make clean'",
846-
cleanall="remove all build directories",
847-
emports="build Emscripten port with embuilder (only Emscripten)",
848-
)
829+
ops = {
830+
"build": "auto build (build 'build' Python, emports, configure, compile)",
831+
"configure": "run ./configure",
832+
"compile": "run 'make all'",
833+
"pythoninfo": "run 'make pythoninfo'",
834+
"test": "run 'make buildbottest TESTOPTS=...' (supports parallel tests)",
835+
"hostrunnertest": "run 'make hostrunnertest TESTOPTS=...'",
836+
"repl": "start interactive REPL / webserver + browser session",
837+
"clean": "run 'make clean'",
838+
"cleanall": "remove all build directories",
839+
"emports": "build Emscripten port with embuilder (only Emscripten)",
840+
}
849841
ops_help = "\n".join(f"{op:16s} {help}" for op, help in ops.items())
850842
parser.add_argument(
851843
"ops",

0 commit comments

Comments
 (0)