Use more modern Python features. NFC - Replace custom `remove_prefix`/`remove_suffix` helpers and manual prefix slicing (including `--build=` parsing) with `str.removeprefix()` and `str.removesuffix()`. - Replace manual attribute caching in `load_releases_info` with `@functools.cache`. - Replace the `[False]` list workaround for `has_partially_active_tools` in `main()` with `nonlocal`. - Replace `unique_items()` with `list(dict.fromkeys(...))`. - Use the walrus operator (`:=`) across `emsdk.py` for env/regex/lookup checks. - Modernize `subprocess` usage across `emsdk.py`, `scripts/get_emscripten_revision_info.py`, and `bazel/emscripten_toolchain/link_wrapper.py` (`subprocess.run`, `check_output(..., text=True)`, `capture_output=True`, `DEVNULL`). - Use `match`/`case` in `emsdk.py` for `EMSDK_OS` override, `ARCH` in `build_llvm()`, `custom_is_installed_script`, and `custom_install_script`. - Replace `try ... except Exception: pass` in `load_em_config()` with `contextlib.suppress(Exception)`.
diff --git a/bazel/emscripten_toolchain/link_wrapper.py b/bazel/emscripten_toolchain/link_wrapper.py index 2f40744..8bb9a95 100644 --- a/bazel/emscripten_toolchain/link_wrapper.py +++ b/bazel/emscripten_toolchain/link_wrapper.py
@@ -107,10 +107,10 @@ os.environ['EM_BIN_PATH'], 'bin/llvm-objcopy') # First, check to make sure the .wasm file has the header that needs to be # rewritten. - rtn = subprocess.call([ + rtn = subprocess.run([ llvm_objcopy, '--dump-section=external_debug_info=/dev/null', - wasm_base], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + wasm_base], capture_output=True).returncode if rtn == 0: # If llvm-objcopy did not return an error, the external_debug_info section # must exist, so we're good to continue.
diff --git a/emsdk.py b/emsdk.py index b9417ac..a0cc848 100644 --- a/emsdk.py +++ b/emsdk.py
@@ -6,6 +6,7 @@ import contextlib import copy +import functools import json import multiprocessing import os @@ -28,6 +29,8 @@ from urllib.parse import urljoin from urllib.request import urlopen +# This check is somewhat mute since olders python version will produce a +# syntax error before we even get here, but serves as documentation still. if sys.version_info < (3, 10): # ruff: ignore[outdated-version-block] print(f'error: emsdk requires python 3.10 or above ({sys.executable} {sys.version})', file=sys.stderr) sys.exit(1) @@ -84,22 +87,21 @@ MACOS = False LINUX = False -os_override = os.environ.get('EMSDK_OS') -if os_override: - if os_override == 'windows': - WINDOWS = True - elif os_override == 'linux': - LINUX = True - elif os_override == 'macos': - MACOS = True - else: - assert False, 'EMSDK_OS must be one of: windows, linux, macos' +if os_override := os.environ.get('EMSDK_OS'): + match os_override: + case 'windows': + WINDOWS = True + case 'linux': + LINUX = True + case 'macos': + MACOS = True + case _: + assert False, 'EMSDK_OS must be one of: windows, linux, macos' else: if os.name == 'nt' or ('windows' in os.getenv('SYSTEMROOT', '').lower()) or ('windows' in os.getenv('COMSPEC', '').lower()): WINDOWS = True - msystem = os.getenv('MSYSTEM') - if msystem: + if msystem := os.getenv('MSYSTEM'): MSYS = True # Some functions like os.path.normpath() exhibit different behavior between # different versions of Python, so we need to distinguish between the MinGW @@ -409,7 +411,7 @@ else: cmd = ['REG', 'DELETE', 'HKCU\\Environment', '/V', key, '/f'] debug_print(cmd) - subprocess.call(cmd, stdout=subprocess.PIPE) + subprocess.run(cmd, stdout=subprocess.DEVNULL) except Exception: return False return True @@ -425,7 +427,7 @@ 'specified above to system environment manually via Control Panel.') cmd = ['SETX', key, value] debug_print(cmd) - retcode = subprocess.call(cmd, stdout=subprocess.PIPE) + retcode = subprocess.run(cmd, stdout=subprocess.DEVNULL).returncode if retcode != 0: errlog(f'ERROR! Failed to set environment variable {key}={value}. You may need to set it manually.') else: @@ -505,7 +507,7 @@ def run(cmd, cwd=None, check=True): debug_print(f'run(cmd={cmd}, cwd={cwd})') - returncode = subprocess.call(cmd, cwd=cwd, env=os.environ.copy()) + returncode = subprocess.call(cmd, cwd=cwd) if returncode != 0 and check: errlog(f'{cmd} failed with error code {returncode}') return returncode @@ -598,7 +600,7 @@ # directory name, if we are stripping that away. if common_subdir: assert member.filename.startswith(common_subdir), f'unexpected filename {member.filename}' - stripped_filename = '.' + member.filename[len(common_subdir):] + stripped_filename = '.' + member.filename.removeprefix(common_subdir) final_dst_filename = os.path.join(dest_dir, stripped_filename) # Check if a directory if stripped_filename.endswith('/'): @@ -726,7 +728,7 @@ if not mirror.endswith('/'): mirror += '/' - mirror_url = mirror + url[len(emscripten_releases_builds_url):] + mirror_url = mirror + url.removeprefix(emscripten_releases_builds_url) debug_print(f'using mirror: {url} -> {mirror_url}') return mirror_url @@ -1147,14 +1149,15 @@ enable_assertions = ENABLE_LLVM_ASSERTIONS.lower() == 'on' or (ENABLE_LLVM_ASSERTIONS == 'auto' and build_type.lower() not in {'release', 'minsizerel'}) - if ARCH in {'x86', 'x86_64'}: - targets_to_build = 'WebAssembly;X86' - elif ARCH == 'arm': - targets_to_build = 'WebAssembly;ARM' - elif ARCH == 'arm64': - targets_to_build = 'WebAssembly;AArch64' - else: - targets_to_build = 'WebAssembly' + match ARCH: + case 'x86' | 'x86_64': + targets_to_build = 'WebAssembly;X86' + case 'arm': + targets_to_build = 'WebAssembly;ARM' + case 'arm64': + targets_to_build = 'WebAssembly;AArch64' + case _: + targets_to_build = 'WebAssembly' cmake_generator, args = get_generator_and_config_args(tool) assertions_arg = 'ON' if enable_assertions else 'OFF' args += [f'-DLLVM_TARGETS_TO_BUILD={targets_to_build}', @@ -1178,8 +1181,8 @@ # upstream LLVM. args += ['-DLLVM_TEMPORARILY_ALLOW_OLD_TOOLCHAIN=ON'] - if os.getenv('LLVM_CMAKE_ARGS'): - extra_args = os.environ['LLVM_CMAKE_ARGS'].split(',') + if llvm_cmake_args := os.getenv('LLVM_CMAKE_ARGS'): + extra_args = llvm_cmake_args.split(',') print(f'Passing the following extra arguments to LLVM CMake configuration: {extra_args}') args += extra_args @@ -1282,7 +1285,7 @@ print(f'Node: {npx}') cmd = [npx, '@puppeteer/browsers', 'install', f'chrome@{tool.version}'] print(cmd) - output = subprocess.check_output(cmd, env=node_env).decode('utf-8') + output = subprocess.check_output(cmd, env=node_env, text=True) chrome_path = output[output.find(' ') + 1:].strip() print(f'Chrome: {chrome_path}') @@ -1693,12 +1696,10 @@ with contextlib.suppress(Exception): lines = read_file(EM_CONFIG_PATH).splitlines() for line in lines: - try: + with contextlib.suppress(Exception): key, value = parse_key_value(line) if value: EM_CONFIG_DICT[key] = value - except Exception: - pass def find_emscripten_root(active_tools): @@ -1767,8 +1768,7 @@ def extract_newest_node_nightly_version(versions): def parse(v): # example: v7.0.0-nightly2016080175c6d9dd95 - m = re.search(r'v(\d+)\.(\d+)\.(\d+)-nightly(\d{8})', v) - if m: + if m := re.search(r'v(\d+)\.(\d+)\.(\d+)-nightly(\d{8})', v): major, minor, patch, nightly = m.groups() return [int(major), int(minor), int(patch), int(nightly)] else: @@ -2083,14 +2083,15 @@ content_exists = False if self.custom_is_installed_script: - if self.custom_is_installed_script == 'is_binaryen_installed': - return is_binaryen_installed(self) - elif self.custom_is_installed_script == 'is_firefox_installed': - return is_firefox_installed(self) - elif self.custom_is_installed_script == 'is_chrome_installed': - return is_chrome_installed(self) - else: - raise Exception(f'Unknown custom_is_installed_script: "{self.custom_is_installed_script}"') + match self.custom_is_installed_script: + case 'is_binaryen_installed': + return is_binaryen_installed(self) + case 'is_firefox_installed': + return is_firefox_installed(self) + case 'is_chrome_installed': + return is_chrome_installed(self) + case _: + raise Exception(f'Unknown custom_is_installed_script: "{self.custom_is_installed_script}"') return content_exists and (skip_version_check or self.is_installed_version()) @@ -2221,16 +2222,17 @@ exit_with_error("installation failed!") if self.custom_install_script: - if self.custom_install_script == 'emscripten_install': - success = emscripten_install(self) - elif self.custom_install_script in {'build_llvm', 'build_ninja', 'build_ccache', 'download_node_nightly', 'download_firefox', 'download_chrome'}: - # 'build_llvm' is a special one that does the download on its - # own, others do the download manually. - pass - elif self.custom_install_script == 'build_binaryen': - success = build_binaryen_tool(self) - else: - raise Exception(f'Unknown custom_install_script: "{self.custom_install_script}"') + match self.custom_install_script: + case 'emscripten_install': + success = emscripten_install(self) + case 'build_llvm' | 'build_ninja' | 'build_ccache' | 'download_node_nightly' | 'download_firefox' | 'download_chrome': + # 'build_llvm' is a special one that does the download on its + # own, others do the download manually. + pass + case 'build_binaryen': + success = build_binaryen_tool(self) + case _: + raise Exception(f'Unknown custom_install_script: "{self.custom_install_script}"') if not success: exit_with_error("installation failed!") @@ -2240,8 +2242,7 @@ # write anything.) if self.emscripten_releases_hash: emscripten_version_file_path = os.path.join(to_native_path(self.expand_vars(self.activated_path)), 'emscripten-version.txt') - version = get_emscripten_release_version(self.emscripten_releases_hash) - if version: + if version := get_emscripten_release_version(self.emscripten_releases_hash): write_file(emscripten_version_file_path, f'"{version}"\n') print(f"Done installing tool '{self}'.") @@ -2304,8 +2305,7 @@ def add_tool(tool): tool.is_sdk = False - existing = find_tool(str(tool)) - if existing: + if existing := find_tool(str(tool)): raise Exception(f'Duplicate tool {tool}! Existing:\n{vars(existing)}, New:\n{vars(tool)}') tools.append(tool) tools_map[str(tool)] = tool @@ -2318,8 +2318,7 @@ def add_sdk(sdk): sdk.is_sdk = True - existing = find_sdk(str(sdk)) - if existing: + if existing := find_sdk(str(sdk)): raise Exception(f'Duplicate sdk {sdk}! Existing:\n{vars(existing)}, New:\n{vars(sdk)}') sdks.append(sdk) sdks_map[str(sdk)] = sdk @@ -2463,24 +2462,10 @@ return read_file(sdk_path('legacy-binaryen-tags.txt')).splitlines() -def remove_prefix(s, prefix): - if s.startswith(prefix): - return s[len(prefix):] - else: - return s - - -def remove_suffix(s, suffix): - if s.endswith(suffix): - return s[:len(s) - len(suffix)] - else: - return s - - def load_file_index_list(filename): """filename should be one of: 'llvm-precompiled-tags-32bit.txt', 'llvm-precompiled-tags-64bit.txt'""" items = read_file(sdk_path(filename)).splitlines() - items = [remove_suffix(remove_suffix(remove_prefix(x, 'emscripten-llvm-e'), '.tar.gz'), '.zip').strip() for x in items] + items = [x.removeprefix('emscripten-llvm-e').removesuffix('.tar.gz').removesuffix('.zip').strip() for x in items] items = [x for x in items if 'latest' not in x and len(x) > 0] # Sort versions from oldest to newest (the default sort would be @@ -2488,17 +2473,15 @@ return sorted(items, key=version_key) +@functools.cache def load_releases_info(): """Load the json info for emscripten-releases.""" - if not hasattr(load_releases_info, 'cached_info'): - try: - text = read_file(sdk_path('emscripten-releases-tags.json')) - load_releases_info.cached_info = json.loads(text) - except Exception as e: - print('Error parsing emscripten-releases-tags.json!') - exit_with_error(e) - - return load_releases_info.cached_info + try: + text = read_file(sdk_path('emscripten-releases-tags.json')) + return json.loads(text) + except Exception as e: + print('Error parsing emscripten-releases-tags.json!') + exit_with_error(e) def get_installed_sdk_version(): @@ -2718,13 +2701,6 @@ return active_tools -# http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order -def unique_items(seq): - seen = set() - seen_add = seen.add - return [x for x in seq if x not in seen and not seen_add(x)] - - def normalized_contains(lst, elem): """Tests if a path is contained in the given list, but with separators normalized.""" elem = to_unix_path(elem) @@ -2767,7 +2743,7 @@ else: kept_emsdk_tools.append(entry) - whole_path = unique_items(new_emsdk_tools + kept_emsdk_tools + existing_nonemsdk_path) + whole_path = list(dict.fromkeys(new_emsdk_tools + kept_emsdk_tools + existing_nonemsdk_path)) if MSYS: # XXX Hack: If running native Windows Python in MSYS prompt where PATH @@ -2941,8 +2917,7 @@ version = fullname.replace('sdk-', '').replace('releases-', '').replace('-64bit', '').replace('tag-', '') sdk = 'sdk-' if not name.startswith('releases-') else '' releases_info = load_releases_info()['releases'] - release_hash = get_release_hash(version, releases_info) - if release_hash: + if release_hash := get_release_hash(version, releases_info): # Known release hash full_name = f'{sdk}releases-{release_hash}-64bit' print(f"Resolving SDK version '{version}' to '{full_name}'") @@ -3138,8 +3113,7 @@ load_sdk_manifest() # Apply any overrides to git branch names to clone from. - forked_url = extract_string_arg('--override-repository') - while forked_url: + while forked_url := extract_string_arg('--override-repository'): tool_name, url_and_refspec = forked_url.split('@') t = find_tool(tool_name) if not t: @@ -3149,13 +3123,10 @@ t.url, t.git_branch, t.remote_name = parse_github_url_and_refspec(url_and_refspec) debug_print(f'Reading git repository URL "{t.url}" and git branch "{t.git_branch}" for Tool "{tool_name}".') - forked_url = extract_string_arg('--override-repository') - # Process global args for i in range(len(args)): if args[i].startswith('--generator='): - build_generator = re.match(r'''^--generator=['"]?([^'"]+)['"]?$''', args[i]) - if build_generator: + if build_generator := re.match(r'''^--generator=['"]?([^'"]+)['"]?$''', args[i]): global CMAKE_GENERATOR CMAKE_GENERATOR = build_generator.group(1) args[i] = '' @@ -3163,10 +3134,9 @@ errlog(f"Cannot parse CMake generator string: {args[i]}. Try wrapping generator string with quotes") return 1 elif args[i].startswith('--build='): - build_type = re.match(r'^--build=(.+)$', args[i]) + build_type = args[i].removeprefix('--build=') if build_type: global CMAKE_BUILD_TYPE_OVERRIDE - build_type = build_type.group(1) build_types = ['Debug', 'MinSizeRel', 'RelWithDebInfo', 'Release'] try: build_type_index = [x.lower() for x in build_types].index(build_type.lower()) @@ -3209,9 +3179,7 @@ print(f' {ver} {installed_sdk_text(sdk_name)}') print() - # Use array to work around the lack of being able to mutate from enclosing - # function. - has_partially_active_tools = [False] + has_partially_active_tools = False if sdks: def find_sdks(needs_compilation): @@ -3250,6 +3218,7 @@ return t def print_tools(t): + nonlocal has_partially_active_tools for tool in t: if tool.is_old and not arg_old: continue @@ -3263,7 +3232,7 @@ active = ' * ' elif tool_is_active: active = '(*)' - has_partially_active_tools[0] = has_partially_active_tools[0] or True + has_partially_active_tools = True else: active = ' ' print(f' {active} {tool!s: <25}{installed}') @@ -3281,7 +3250,7 @@ print() print('Items marked with * are activated for the current user.') - if has_partially_active_tools[0]: + if has_partially_active_tools: env_cmd = 'emsdk_env.bat' if WINDOWS else 'source ./emsdk_env.sh' suffix = ', or call "emsdk activate --permanent <name_of_sdk>" to permanently activate them.' if WINDOWS else '.' print('Items marked with (*) are selected for use, ' @@ -3357,8 +3326,7 @@ # Process args for i in range(len(args)): if args[i].startswith('-j'): - multicore = re.match(r'^-j(\d+)$', args[i]) - if multicore: + if multicore := re.match(r'^-j(\d+)$', args[i]): CPU_CORES = int(multicore.group(1)) args[i] = '' else:
diff --git a/scripts/get_emscripten_revision_info.py b/scripts/get_emscripten_revision_info.py index 4f00d74..6235356 100755 --- a/scripts/get_emscripten_revision_info.py +++ b/scripts/get_emscripten_revision_info.py
@@ -24,9 +24,8 @@ # This will fail if the 'latest' revision is not within the most recent # 100 commits; but that shouldn't happen because this script is intended # to be run right after a release is added. - info = subprocess.run(['emscripten-releases/src/release-info.py', - 'emscripten-releases', latest], - stdout=subprocess.PIPE, check=True, text=True).stdout + info = subprocess.check_output(['emscripten-releases/src/release-info.py', + 'emscripten-releases', latest], text=True) for line in info.split('\n'): tokens = line.split() if len(tokens) and tokens[0] == 'emscripten':