Skip to content

Commit 5848d80

Browse files
miss-islingtonsobolevnhugovk
authored
[3.14] pythongh-139590: Stricter ruff rules for Tools/wasm (pythonGH-139752) (python#139811)
Co-authored-by: sobolevn <[email protected]> Co-authored-by: Hugo van Kemenade <[email protected]>
1 parent 7a13953 commit 5848d80

File tree

8 files changed

+53
-77
lines changed

8 files changed

+53
-77
lines changed

.github/workflows/mypy.yml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ on:
2929
- "Tools/jit/**"
3030
- "Tools/peg_generator/**"
3131
- "Tools/requirements-dev.txt"
32-
- "Tools/wasm/**"
3332
workflow_dispatch:
3433

3534
permissions:
@@ -61,7 +60,6 @@ jobs:
6160
"Tools/clinic",
6261
"Tools/jit",
6362
"Tools/peg_generator",
64-
"Tools/wasm",
6563
]
6664
steps:
6765
- uses: actions/checkout@v4

.pre-commit-config.yaml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ repos:
2626
name: Run Ruff (lint) on Tools/peg_generator/
2727
args: [--exit-non-zero-on-fix, --config=Tools/peg_generator/.ruff.toml]
2828
files: ^Tools/peg_generator/
29+
- id: ruff-check
30+
name: Run Ruff (lint) on Tools/wasm/
31+
args: [--exit-non-zero-on-fix, --config=Tools/wasm/.ruff.toml]
32+
files: ^Tools/wasm/
2933
- id: ruff-format
3034
name: Run Ruff (format) on Doc/
3135
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/emscripten/__main__.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,16 @@
33
import argparse
44
import contextlib
55
import functools
6+
import hashlib
67
import os
78
import shutil
89
import subprocess
910
import sys
1011
import sysconfig
11-
import hashlib
1212
import tempfile
13-
from urllib.request import urlopen
1413
from pathlib import Path
1514
from textwrap import dedent
15+
from urllib.request import urlopen
1616

1717
try:
1818
from os import process_cpu_count as cpu_count
@@ -33,9 +33,7 @@
3333
PREFIX_DIR = CROSS_BUILD_DIR / HOST_TRIPLE / "prefix"
3434

3535
LOCAL_SETUP = CHECKOUT / "Modules" / "Setup.local"
36-
LOCAL_SETUP_MARKER = "# Generated by Tools/wasm/emscripten.py\n".encode(
37-
"utf-8"
38-
)
36+
LOCAL_SETUP_MARKER = b"# Generated by Tools/wasm/emscripten.py\n"
3937

4038

4139
def updated_env(updates={}):
@@ -432,6 +430,7 @@ def main():
432430
make_build,
433431
configure_host,
434432
make_host,
433+
clean,
435434
):
436435
subcommand.add_argument(
437436
"--quiet",

Tools/wasm/emscripten/wasm_assets.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
import sys
1616
import sysconfig
1717
import zipfile
18-
from typing import Dict
1918

2019
# source directory
2120
SRCDIR = pathlib.Path(__file__).parents[3].absolute()
@@ -134,7 +133,7 @@ def filterfunc(filename: str) -> bool:
134133
pzf.writepy(entry, filterfunc=filterfunc)
135134

136135

137-
def detect_extension_modules(args: argparse.Namespace) -> Dict[str, bool]:
136+
def detect_extension_modules(args: argparse.Namespace) -> dict[str, bool]:
138137
modules = {}
139138

140139
# disabled by Modules/Setup.local ?
@@ -149,7 +148,7 @@ def detect_extension_modules(args: argparse.Namespace) -> Dict[str, bool]:
149148
# disabled by configure?
150149
with open(args.sysconfig_data) as f:
151150
data = f.read()
152-
loc: Dict[str, Dict[str, str]] = {}
151+
loc: dict[str, dict[str, str]] = {}
153152
exec(data, globals(), loc)
154153

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

Tools/wasm/mypy.ini

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

Tools/wasm/wasi/__main__.py

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

19-
2019
CHECKOUT = pathlib.Path(__file__).parent.parent.parent.parent
2120
assert (CHECKOUT / "configure").is_file(), (
2221
"Please update the location of the file"
@@ -28,9 +27,9 @@
2827

2928
LOCAL_SETUP = CHECKOUT / "Modules" / "Setup.local"
3029
LOCAL_SETUP_MARKER = (
31-
"# Generated by Tools/wasm/wasi .\n"
32-
"# Required to statically build extension modules."
33-
).encode("utf-8")
30+
b"# Generated by Tools/wasm/wasi .\n"
31+
b"# Required to statically build extension modules."
32+
)
3433

3534
WASI_SDK_VERSION = 24
3635

@@ -154,8 +153,7 @@ def build_python_is_pydebug():
154153
test = "import sys, test.support; sys.exit(test.support.Py_DEBUG)"
155154
result = subprocess.run(
156155
[build_python_path(), "-c", test],
157-
stdout=subprocess.PIPE,
158-
stderr=subprocess.PIPE,
156+
capture_output=True,
159157
)
160158
return bool(result.returncode)
161159

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)