From f5d7cb40c186b861eac6adf7826a6dfbf3c99605 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 25 Nov 2024 17:33:50 -0800 Subject: [PATCH] [pre-commit.ci] pre-commit autoupdate (#2799) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Bernát Gábor Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Bernát Gábor --- .pre-commit-config.yaml | 2 +- src/virtualenv/__main__.py | 8 ++++--- src/virtualenv/app_data/__init__.py | 8 ++++--- src/virtualenv/app_data/via_disk_folder.py | 10 ++++---- src/virtualenv/app_data/via_tempdir.py | 6 +++-- src/virtualenv/config/convert.py | 4 +++- src/virtualenv/config/ini.py | 4 +++- src/virtualenv/create/creator.py | 5 ++-- src/virtualenv/create/pyenv_cfg.py | 6 +++-- src/virtualenv/create/via_global_ref/api.py | 6 +++-- .../via_global_ref/builtin/cpython/mac_os.py | 6 +++-- src/virtualenv/create/via_global_ref/venv.py | 4 +++- src/virtualenv/discovery/builtin.py | 9 ++++---- src/virtualenv/discovery/cached_py_info.py | 5 ++-- src/virtualenv/discovery/py_info.py | 17 +++++++------- src/virtualenv/info.py | 5 ++-- src/virtualenv/report.py | 2 +- src/virtualenv/run/session.py | 12 ++++++---- src/virtualenv/seed/embed/pip_invoke.py | 4 +++- .../embed/via_app_data/pip_install/base.py | 8 ++++--- .../seed/embed/via_app_data/via_app_data.py | 8 ++++--- src/virtualenv/seed/wheels/acquire.py | 6 +++-- src/virtualenv/seed/wheels/periodic_update.py | 23 ++++++++++--------- src/virtualenv/util/lock.py | 4 +++- src/virtualenv/util/path/_sync.py | 12 ++++++---- src/virtualenv/util/zipapp.py | 4 +++- tasks/upgrade_wheels.py | 10 ++++++-- tox.ini | 2 +- 28 files changed, 124 insertions(+), 76 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a19389600..bc0373e30 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -24,7 +24,7 @@ repos: hooks: - id: pyproject-fmt - repo: https://github.com/astral-sh/ruff-pre-commit - rev: "v0.7.2" + rev: "v0.8.0" hooks: - id: ruff-format - id: ruff diff --git a/src/virtualenv/__main__.py b/src/virtualenv/__main__.py index d0979a665..195732619 100644 --- a/src/virtualenv/__main__.py +++ b/src/virtualenv/__main__.py @@ -5,6 +5,8 @@ import sys from timeit import default_timer +LOGGER = logging.getLogger(__name__) + def run(args=None, options=None, env=None): env = os.environ if env is None else env @@ -16,7 +18,7 @@ def run(args=None, options=None, env=None): args = sys.argv[1:] try: session = cli_run(args, options, env) - logging.warning(LogSession(session, start)) + LOGGER.warning(LogSession(session, start)) except ProcessCallFailedError as exception: print(f"subprocess call failed for {exception.cmd} with code {exception.code}") # noqa: T201 print(exception.out, file=sys.stdout, end="") # noqa: T201 @@ -59,11 +61,11 @@ def run_with_catch(args=None, env=None): if getattr(options, "with_traceback", False): raise if not (isinstance(exception, SystemExit) and exception.code == 0): - logging.error("%s: %s", type(exception).__name__, exception) # noqa: TRY400 + LOGGER.error("%s: %s", type(exception).__name__, exception) # noqa: TRY400 code = exception.code if isinstance(exception, SystemExit) else 1 sys.exit(code) finally: - logging.shutdown() # force flush of log messages before the trace is printed + LOGGER.shutdown() # force flush of log messages before the trace is printed if __name__ == "__main__": # pragma: no cov diff --git a/src/virtualenv/app_data/__init__.py b/src/virtualenv/app_data/__init__.py index 148c94183..d7f148023 100644 --- a/src/virtualenv/app_data/__init__.py +++ b/src/virtualenv/app_data/__init__.py @@ -12,6 +12,8 @@ from .via_disk_folder import AppDataDiskFolder from .via_tempdir import TempAppData +LOGGER = logging.getLogger(__name__) + def _default_app_data_dir(env): key = "VIRTUALENV_OVERRIDE_APP_DATA" @@ -37,13 +39,13 @@ def make_app_data(folder, **kwargs): if not os.path.isdir(folder): try: os.makedirs(folder) - logging.debug("created app data folder %s", folder) + LOGGER.debug("created app data folder %s", folder) except OSError as exception: - logging.info("could not create app data folder %s due to %r", folder, exception) + LOGGER.info("could not create app data folder %s due to %r", folder, exception) if os.access(folder, os.W_OK): return AppDataDiskFolder(folder) - logging.debug("app data folder %s has no write access", folder) + LOGGER.debug("app data folder %s has no write access", folder) return TempAppData() diff --git a/src/virtualenv/app_data/via_disk_folder.py b/src/virtualenv/app_data/via_disk_folder.py index 5228e49a8..98cf2886b 100644 --- a/src/virtualenv/app_data/via_disk_folder.py +++ b/src/virtualenv/app_data/via_disk_folder.py @@ -37,6 +37,8 @@ from .base import AppData, ContentStore +LOGGER = logging.getLogger(__name__) + class AppDataDiskFolder(AppData): """Store the application data on the disk within a folder layout.""" @@ -54,7 +56,7 @@ def __str__(self) -> str: return str(self.lock.path) def reset(self): - logging.debug("reset app data folder %s", self.lock.path) + LOGGER.debug("reset app data folder %s", self.lock.path) safe_delete(self.lock.path) def close(self): @@ -128,7 +130,7 @@ def read(self): except Exception: # noqa: BLE001, S110 pass else: - logging.debug("got %s from %s", self.msg, self.msg_args) + LOGGER.debug("got %s from %s", self.msg, self.msg_args) return data if bad_format: with suppress(OSError): # reading and writing on the same file may cause race on multiple processes @@ -137,7 +139,7 @@ def read(self): def remove(self): self.file.unlink() - logging.debug("removed %s at %s", self.msg, self.msg_args) + LOGGER.debug("removed %s at %s", self.msg, self.msg_args) @contextmanager def locked(self): @@ -148,7 +150,7 @@ def write(self, content): folder = self.file.parent folder.mkdir(parents=True, exist_ok=True) self.file.write_text(json.dumps(content, sort_keys=True, indent=2), encoding="utf-8") - logging.debug("wrote %s at %s", self.msg, self.msg_args) + LOGGER.debug("wrote %s at %s", self.msg, self.msg_args) class PyInfoStoreDisk(JSONStoreDisk): diff --git a/src/virtualenv/app_data/via_tempdir.py b/src/virtualenv/app_data/via_tempdir.py index 0a30dfe1c..884a570ce 100644 --- a/src/virtualenv/app_data/via_tempdir.py +++ b/src/virtualenv/app_data/via_tempdir.py @@ -7,6 +7,8 @@ from .via_disk_folder import AppDataDiskFolder +LOGGER = logging.getLogger(__name__) + class TempAppData(AppDataDiskFolder): transient = True @@ -14,13 +16,13 @@ class TempAppData(AppDataDiskFolder): def __init__(self) -> None: super().__init__(folder=mkdtemp()) - logging.debug("created temporary app data folder %s", self.lock.path) + LOGGER.debug("created temporary app data folder %s", self.lock.path) def reset(self): """This is a temporary folder, is already empty to start with.""" def close(self): - logging.debug("remove temporary app data folder %s", self.lock.path) + LOGGER.debug("remove temporary app data folder %s", self.lock.path) safe_delete(self.lock.path) def embed_update_log(self, distribution, for_py_version): diff --git a/src/virtualenv/config/convert.py b/src/virtualenv/config/convert.py index ecd9d2b5b..ef7581dbd 100644 --- a/src/virtualenv/config/convert.py +++ b/src/virtualenv/config/convert.py @@ -4,6 +4,8 @@ import os from typing import ClassVar +LOGGER = logging.getLogger(__name__) + class TypeData: def __init__(self, default_type, as_type) -> None: @@ -81,7 +83,7 @@ def convert(value, as_type, source): try: return as_type.convert(value) except Exception as exception: - logging.warning("%s failed to convert %r as %r because %r", source, value, as_type, exception) + LOGGER.warning("%s failed to convert %r as %r because %r", source, value, as_type, exception) raise diff --git a/src/virtualenv/config/ini.py b/src/virtualenv/config/ini.py index cd6ecf504..ed0a1b930 100644 --- a/src/virtualenv/config/ini.py +++ b/src/virtualenv/config/ini.py @@ -10,6 +10,8 @@ from .convert import convert +LOGGER = logging.getLogger(__name__) + class IniConfig: VIRTUALENV_CONFIG_FILE_ENV_VAR: ClassVar[str] = "VIRTUALENV_CONFIG_FILE" @@ -44,7 +46,7 @@ def __init__(self, env=None) -> None: except Exception as exc: # noqa: BLE001 exception = exc if exception is not None: - logging.error("failed to read config file %s because %r", config_file, exception) + LOGGER.error("failed to read config file %s because %r", config_file, exception) def _load(self): with self.config_file.open("rt", encoding="utf-8") as file_handler: diff --git a/src/virtualenv/create/creator.py b/src/virtualenv/create/creator.py index 4d5dabaf8..f4a83d981 100644 --- a/src/virtualenv/create/creator.py +++ b/src/virtualenv/create/creator.py @@ -20,6 +20,7 @@ HERE = Path(os.path.abspath(__file__)).parent DEBUG_SCRIPT = HERE / "debug.py" +LOGGER = logging.getLogger(__name__) class CreatorMeta: @@ -154,7 +155,7 @@ def non_write_able(dest, value): def run(self): if self.dest.exists() and self.clear: - logging.debug("delete %s", self.dest) + LOGGER.debug("delete %s", self.dest) safe_delete(self.dest) self.create() self.add_cachedir_tag() @@ -219,7 +220,7 @@ def get_env_debug_info(env_exe, debug_script, app_data, env): with app_data.ensure_extracted(debug_script) as debug_script_extracted: cmd = [str(env_exe), str(debug_script_extracted)] - logging.debug("debug via %r", LogCmd(cmd)) + LOGGER.debug("debug via %r", LogCmd(cmd)) code, out, err = run_cmd(cmd) try: diff --git a/src/virtualenv/create/pyenv_cfg.py b/src/virtualenv/create/pyenv_cfg.py index 04883dea2..1d1beacff 100644 --- a/src/virtualenv/create/pyenv_cfg.py +++ b/src/virtualenv/create/pyenv_cfg.py @@ -4,6 +4,8 @@ import os from collections import OrderedDict +LOGGER = logging.getLogger(__name__) + class PyEnvCfg: def __init__(self, content, path) -> None: @@ -30,12 +32,12 @@ def _read_values(path): return content def write(self): - logging.debug("write %s", self.path) + LOGGER.debug("write %s", self.path) text = "" for key, value in self.content.items(): normalized_value = os.path.realpath(value) if value and os.path.exists(value) else value line = f"{key} = {normalized_value}" - logging.debug("\t%s", line) + LOGGER.debug("\t%s", line) text += line text += "\n" self.path.write_text(text, encoding="utf-8") diff --git a/src/virtualenv/create/via_global_ref/api.py b/src/virtualenv/create/via_global_ref/api.py index d29067c8b..2bf43fa74 100644 --- a/src/virtualenv/create/via_global_ref/api.py +++ b/src/virtualenv/create/via_global_ref/api.py @@ -8,6 +8,8 @@ from virtualenv.create.creator import Creator, CreatorMeta from virtualenv.info import fs_supports_symlink +LOGGER = logging.getLogger(__name__) + class ViaGlobalRefMeta(CreatorMeta): def __init__(self) -> None: @@ -88,10 +90,10 @@ def install_patch(self): text = self.env_patch_text() if text: pth = self.purelib / "_virtualenv.pth" - logging.debug("create virtualenv import hook file %s", pth) + LOGGER.debug("create virtualenv import hook file %s", pth) pth.write_text("import _virtualenv", encoding="utf-8") dest_path = self.purelib / "_virtualenv.py" - logging.debug("create %s", dest_path) + LOGGER.debug("create %s", dest_path) dest_path.write_text(text, encoding="utf-8") def env_patch_text(self): diff --git a/src/virtualenv/create/via_global_ref/builtin/cpython/mac_os.py b/src/virtualenv/create/via_global_ref/builtin/cpython/mac_os.py index d0ffa8f00..0ddbf9a33 100644 --- a/src/virtualenv/create/via_global_ref/builtin/cpython/mac_os.py +++ b/src/virtualenv/create/via_global_ref/builtin/cpython/mac_os.py @@ -20,6 +20,8 @@ from .common import CPython, CPythonPosix, is_mac_os_framework, is_macos_brew from .cpython3 import CPython3 +LOGGER = logging.getLogger(__name__) + class CPythonmacOsFramework(CPython, ABC): @classmethod @@ -115,10 +117,10 @@ def fix_mach_o(exe, current, new, max_size): unneeded bits of information, however Mac OS X 10.5 and earlier cannot read this new Link Edit table format. """ try: - logging.debug("change Mach-O for %s from %s to %s", exe, current, new) + LOGGER.debug("change Mach-O for %s from %s to %s", exe, current, new) _builtin_change_mach_o(max_size)(exe, current, new) except Exception as e: # noqa: BLE001 - logging.warning("Could not call _builtin_change_mac_o: %s. Trying to call install_name_tool instead.", e) + LOGGER.warning("Could not call _builtin_change_mac_o: %s. Trying to call install_name_tool instead.", e) try: cmd = ["install_name_tool", "-change", current, new, exe] subprocess.check_call(cmd) diff --git a/src/virtualenv/create/via_global_ref/venv.py b/src/virtualenv/create/via_global_ref/venv.py index e1c9f64d0..7d6f32e39 100644 --- a/src/virtualenv/create/via_global_ref/venv.py +++ b/src/virtualenv/create/via_global_ref/venv.py @@ -13,6 +13,8 @@ from .builtin.cpython.mac_os import CPython3macOsBrew from .builtin.pypy.pypy3 import Pypy3Windows +LOGGER = logging.getLogger(__name__) + class Venv(ViaGlobalRefApi): def __init__(self, options, interpreter) -> None: @@ -70,7 +72,7 @@ def create_inline(self): def create_via_sub_process(self): cmd = self.get_host_create_cmd() - logging.info("using host built-in venv to create via %s", " ".join(cmd)) + LOGGER.info("using host built-in venv to create via %s", " ".join(cmd)) code, out, err = run_cmd(cmd) if code != 0: raise ProcessCallFailedError(code, out, err, cmd) diff --git a/src/virtualenv/discovery/builtin.py b/src/virtualenv/discovery/builtin.py index d2f1cf433..00c595b46 100644 --- a/src/virtualenv/discovery/builtin.py +++ b/src/virtualenv/discovery/builtin.py @@ -18,6 +18,7 @@ from collections.abc import Generator, Iterable, Mapping, Sequence from virtualenv.app_data.base import AppData +LOGGER = logging.getLogger(__name__) class Builtin(Discover): @@ -70,16 +71,16 @@ def get_interpreter( key, try_first_with: Iterable[str], app_data: AppData | None = None, env: Mapping[str, str] | None = None ) -> PythonInfo | None: spec = PythonSpec.from_string_spec(key) - logging.info("find interpreter for spec %r", spec) + LOGGER.info("find interpreter for spec %r", spec) proposed_paths = set() env = os.environ if env is None else env for interpreter, impl_must_match in propose_interpreters(spec, try_first_with, app_data, env): key = interpreter.system_executable, impl_must_match if key in proposed_paths: continue - logging.info("proposed %s", interpreter) + LOGGER.info("proposed %s", interpreter) if interpreter.satisfies(spec, impl_must_match): - logging.debug("accepted %s", interpreter) + LOGGER.debug("accepted %s", interpreter) return interpreter proposed_paths.add(key) return None @@ -146,7 +147,7 @@ def propose_interpreters( # noqa: C901, PLR0912, PLR0915 # finally just find on path, the path order matters (as the candidates are less easy to control by end user) find_candidates = path_exe_finder(spec) for pos, path in enumerate(get_paths(env)): - logging.debug(LazyPathDump(pos, path, env)) + LOGGER.debug(LazyPathDump(pos, path, env)) for exe, impl_must_match in find_candidates(path): exe_raw = str(exe) exe_id = fs_path_id(exe_raw) diff --git a/src/virtualenv/discovery/cached_py_info.py b/src/virtualenv/discovery/cached_py_info.py index 8f4c7291b..846856d0e 100644 --- a/src/virtualenv/discovery/cached_py_info.py +++ b/src/virtualenv/discovery/cached_py_info.py @@ -23,6 +23,7 @@ _CACHE = OrderedDict() _CACHE[Path(sys.executable)] = PythonInfo() +LOGGER = logging.getLogger(__name__) def from_exe(cls, app_data, exe, env=None, raise_on_error=True, ignore_cache=False): # noqa: FBT002, PLR0913 @@ -31,7 +32,7 @@ def from_exe(cls, app_data, exe, env=None, raise_on_error=True, ignore_cache=Fal if isinstance(result, Exception): if raise_on_error: raise result - logging.info("%s", result) + LOGGER.info("%s", result) result = None return result @@ -109,7 +110,7 @@ def _run_subprocess(cls, exe, app_data, env): # prevent sys.prefix from leaking into the child process - see https://bugs.python.org/issue22490 env = env.copy() env.pop("__PYVENV_LAUNCHER__", None) - logging.debug("get interpreter info via cmd: %s", LogCmd(cmd)) + LOGGER.debug("get interpreter info via cmd: %s", LogCmd(cmd)) try: process = Popen( cmd, diff --git a/src/virtualenv/discovery/py_info.py b/src/virtualenv/discovery/py_info.py index 882daa331..4895e2408 100644 --- a/src/virtualenv/discovery/py_info.py +++ b/src/virtualenv/discovery/py_info.py @@ -18,6 +18,7 @@ from string import digits VersionInfo = namedtuple("VersionInfo", ["major", "minor", "micro", "releaselevel", "serial"]) # noqa: PYI024 +LOGGER = logging.getLogger(__name__) def _get_path_extensions(): @@ -386,7 +387,7 @@ def from_exe( # noqa: PLR0913 except Exception as exception: if raise_on_error: raise - logging.info("ignore %s due cannot resolve system due to %r", proposed.original_executable, exception) + LOGGER.info("ignore %s due cannot resolve system due to %r", proposed.original_executable, exception) proposed = None return proposed @@ -412,12 +413,12 @@ def _resolve_to_system(cls, app_data, target): if prefix in prefixes: if len(prefixes) == 1: # if we're linking back to ourselves accept ourselves with a WARNING - logging.info("%r links back to itself via prefixes", target) + LOGGER.info("%r links back to itself via prefixes", target) target.system_executable = target.executable break for at, (p, t) in enumerate(prefixes.items(), start=1): - logging.error("%d: prefix=%s, info=%r", at, p, t) - logging.error("%d: prefix=%s, info=%r", len(prefixes) + 1, prefix, target) + LOGGER.error("%d: prefix=%s, info=%r", at, p, t) + LOGGER.error("%d: prefix=%s, info=%r", len(prefixes) + 1, prefix, target) msg = "prefixes are causing a circle {}".format("|".join(prefixes.keys())) raise RuntimeError(msg) prefixes[prefix] = target @@ -432,9 +433,9 @@ def _resolve_to_system(cls, app_data, target): def discover_exe(self, app_data, prefix, exact=True, env=None): # noqa: FBT002 key = prefix, exact if key in self._cache_exe_discovery and prefix: - logging.debug("discover exe from cache %s - exact %s: %r", prefix, exact, self._cache_exe_discovery[key]) + LOGGER.debug("discover exe from cache %s - exact %s: %r", prefix, exact, self._cache_exe_discovery[key]) return self._cache_exe_discovery[key] - logging.debug("discover exe for %s in %s", self, prefix) + LOGGER.debug("discover exe for %s in %s", self, prefix) # we don't know explicitly here, do some guess work - our executable name should tell possible_names = self._find_possible_exe_names() possible_folders = self._find_possible_folders(prefix) @@ -450,7 +451,7 @@ def discover_exe(self, app_data, prefix, exact=True, env=None): # noqa: FBT002 info = self._select_most_likely(discovered, self) folders = os.pathsep.join(possible_folders) self._cache_exe_discovery[key] = info - logging.debug("no exact match found, chosen most similar of %s within base folders %s", info, folders) + LOGGER.debug("no exact match found, chosen most similar of %s within base folders %s", info, folders) return info msg = "failed to detect {} in {}".format("|".join(possible_names), os.pathsep.join(possible_folders)) raise RuntimeError(msg) @@ -469,7 +470,7 @@ def _check_exe(self, app_data, folder, name, exact, discovered, env): # noqa: P if item == "version_info": found, searched = ".".join(str(i) for i in found), ".".join(str(i) for i in searched) executable = info.executable - logging.debug("refused interpreter %s because %s differs %s != %s", executable, item, found, searched) + LOGGER.debug("refused interpreter %s because %s differs %s != %s", executable, item, found, searched) if exact is False: discovered.append(info) break diff --git a/src/virtualenv/info.py b/src/virtualenv/info.py index 8b217d0c3..6f8c2bdf3 100644 --- a/src/virtualenv/info.py +++ b/src/virtualenv/info.py @@ -14,6 +14,7 @@ ROOT = os.path.realpath(os.path.join(os.path.abspath(__file__), os.path.pardir, os.path.pardir)) IS_ZIPAPP = os.path.isfile(ROOT) _CAN_SYMLINK = _FS_CASE_SENSITIVE = _CFG_DIR = _DATA_DIR = None +LOGGER = logging.getLogger(__name__) def fs_is_case_sensitive(): @@ -22,7 +23,7 @@ def fs_is_case_sensitive(): if _FS_CASE_SENSITIVE is None: with tempfile.NamedTemporaryFile(prefix="TmP") as tmp_file: _FS_CASE_SENSITIVE = not os.path.exists(tmp_file.name.lower()) - logging.debug("filesystem is %scase-sensitive", "" if _FS_CASE_SENSITIVE else "not ") + LOGGER.debug("filesystem is %scase-sensitive", "" if _FS_CASE_SENSITIVE else "not ") return _FS_CASE_SENSITIVE @@ -41,7 +42,7 @@ def fs_supports_symlink(): can = True except (OSError, NotImplementedError): pass - logging.debug("symlink on filesystem does%s work", "" if can else " not") + LOGGER.debug("symlink on filesystem does%s work", "" if can else " not") else: can = True _CAN_SYMLINK = can diff --git a/src/virtualenv/report.py b/src/virtualenv/report.py index 9ad52a12a..c9682a8f6 100644 --- a/src/virtualenv/report.py +++ b/src/virtualenv/report.py @@ -33,7 +33,7 @@ def setup_report(verbosity, show_pid=False): # noqa: FBT002 stream_handler.setFormatter(formatter) LOGGER.addHandler(stream_handler) level_name = logging.getLevelName(level) - logging.debug("setup logging to %s", level_name) + LOGGER.debug("setup logging to %s", level_name) logging.getLogger("distlib").setLevel(logging.ERROR) return verbosity diff --git a/src/virtualenv/run/session.py b/src/virtualenv/run/session.py index 9ffd89082..def795328 100644 --- a/src/virtualenv/run/session.py +++ b/src/virtualenv/run/session.py @@ -3,6 +3,8 @@ import json import logging +LOGGER = logging.getLogger(__name__) + class Session: """Represents a virtual environment creation session.""" @@ -47,20 +49,20 @@ def run(self): self.creator.pyenv_cfg.write() def _create(self): - logging.info("create virtual environment via %s", self.creator) + LOGGER.info("create virtual environment via %s", self.creator) self.creator.run() - logging.debug(_DEBUG_MARKER) - logging.debug("%s", _Debug(self.creator)) + LOGGER.debug(_DEBUG_MARKER) + LOGGER.debug("%s", _Debug(self.creator)) def _seed(self): if self.seeder is not None and self.seeder.enabled: - logging.info("add seed packages via %s", self.seeder) + LOGGER.info("add seed packages via %s", self.seeder) self.seeder.run(self.creator) def _activate(self): if self.activators: active = ", ".join(type(i).__name__.replace("Activator", "") for i in self.activators) - logging.info("add activators for %s", active) + LOGGER.info("add activators for %s", active) for activator in self.activators: activator.generate(self.creator) diff --git a/src/virtualenv/seed/embed/pip_invoke.py b/src/virtualenv/seed/embed/pip_invoke.py index 815753c46..b733c5148 100644 --- a/src/virtualenv/seed/embed/pip_invoke.py +++ b/src/virtualenv/seed/embed/pip_invoke.py @@ -8,6 +8,8 @@ from virtualenv.seed.embed.base_embed import BaseEmbed from virtualenv.seed.wheels import Version, get_wheel, pip_wheel_env_run +LOGGER = logging.getLogger(__name__) + class PipInvoke(BaseEmbed): def __init__(self, options) -> None: @@ -23,7 +25,7 @@ def run(self, creator): @staticmethod def _execute(cmd, env): - logging.debug("pip seed by running: %s", LogCmd(cmd, env)) + LOGGER.debug("pip seed by running: %s", LogCmd(cmd, env)) process = Popen(cmd, env=env) process.communicate() if process.returncode != 0: diff --git a/src/virtualenv/seed/embed/via_app_data/pip_install/base.py b/src/virtualenv/seed/embed/via_app_data/pip_install/base.py index 0ca829713..6cddef839 100644 --- a/src/virtualenv/seed/embed/via_app_data/pip_install/base.py +++ b/src/virtualenv/seed/embed/via_app_data/pip_install/base.py @@ -14,6 +14,8 @@ from virtualenv.util.path import safe_delete +LOGGER = logging.getLogger(__name__) + class PipInstall(ABC): def __init__(self, wheel, creator, image_folder) -> None: @@ -40,11 +42,11 @@ def install(self, version_info): script_dir = self._creator.script_dir for name, module in self._console_scripts.items(): consoles.update(self._create_console_entry_point(name, module, script_dir, version_info)) - logging.debug("generated console scripts %s", " ".join(i.name for i in consoles)) + LOGGER.debug("generated console scripts %s", " ".join(i.name for i in consoles)) def build_image(self): # 1. first extract the wheel - logging.debug("build install image for %s to %s", self._wheel.name, self._image_dir) + LOGGER.debug("build install image for %s to %s", self._wheel.name, self._image_dir) with zipfile.ZipFile(str(self._wheel)) as zip_ref: self._shorten_path_if_needed(zip_ref) zip_ref.extractall(str(self._image_dir)) @@ -151,7 +153,7 @@ def _uninstall_previous_version(self): @staticmethod def _uninstall_dist(dist): dist_base = dist.parent - logging.debug("uninstall existing distribution %s from %s", dist.stem, dist_base) + LOGGER.debug("uninstall existing distribution %s from %s", dist.stem, dist_base) top_txt = dist / "top_level.txt" # add top level packages at folder level paths = ( diff --git a/src/virtualenv/seed/embed/via_app_data/via_app_data.py b/src/virtualenv/seed/embed/via_app_data/via_app_data.py index 7e58bfc6e..a2e9630c6 100644 --- a/src/virtualenv/seed/embed/via_app_data/via_app_data.py +++ b/src/virtualenv/seed/embed/via_app_data/via_app_data.py @@ -17,6 +17,8 @@ from .pip_install.copy import CopyPipInstall from .pip_install.symlink import SymlinkPipInstall +LOGGER = logging.getLogger(__name__) + class FromAppData(BaseEmbed): def __init__(self, options) -> None: @@ -46,7 +48,7 @@ def run(self, creator): def _install(name, wheel): try: - logging.debug("install %s from wheel %s via %s", name, wheel, installer_class.__name__) + LOGGER.debug("install %s from wheel %s via %s", name, wheel, installer_class.__name__) key = Path(installer_class.__name__) / wheel.path.stem wheel_img = self.app_data.wheel_image(creator.interpreter.version_release_str, key) installer = installer_class(wheel.path, creator, wheel_img) @@ -94,7 +96,7 @@ def _get(distribution, version): if result is not None: break except Exception as exception: - logging.exception("fail") + LOGGER.exception("fail") failure = exception if failure: if isinstance(failure, CalledProcessError): @@ -108,7 +110,7 @@ def _get(distribution, version): msg += output else: msg = repr(failure) - logging.error(msg) + LOGGER.error(msg) with lock: fail[distribution] = version else: diff --git a/src/virtualenv/seed/wheels/acquire.py b/src/virtualenv/seed/wheels/acquire.py index 8b3ddd8eb..5ca610fcd 100644 --- a/src/virtualenv/seed/wheels/acquire.py +++ b/src/virtualenv/seed/wheels/acquire.py @@ -12,6 +12,8 @@ from .periodic_update import add_wheel_to_update_log from .util import Version, Wheel, discover_wheels +LOGGER = logging.getLogger(__name__) + def get_wheel( # noqa: PLR0913 distribution, @@ -50,7 +52,7 @@ def get_wheel( # noqa: PLR0913 def download_wheel(distribution, version_spec, for_py_version, search_dirs, app_data, to_folder, env): # noqa: PLR0913 to_download = f"{distribution}{version_spec or ''}" - logging.debug("download wheel %s %s to %s", to_download, for_py_version, to_folder) + LOGGER.debug("download wheel %s %s to %s", to_download, for_py_version, to_folder) cmd = [ sys.executable, "-m", @@ -75,7 +77,7 @@ def download_wheel(distribution, version_spec, for_py_version, search_dirs, app_ kwargs = {"output": out, "stderr": err} raise CalledProcessError(process.returncode, cmd, **kwargs) result = _find_downloaded_wheel(distribution, version_spec, for_py_version, to_folder, out) - logging.debug("downloaded wheel %s", result.name) + LOGGER.debug("downloaded wheel %s", result.name) return result diff --git a/src/virtualenv/seed/wheels/periodic_update.py b/src/virtualenv/seed/wheels/periodic_update.py index 32ffad680..ac627b3bd 100644 --- a/src/virtualenv/seed/wheels/periodic_update.py +++ b/src/virtualenv/seed/wheels/periodic_update.py @@ -22,6 +22,7 @@ from virtualenv.seed.wheels.util import Wheel from virtualenv.util.subprocess import CREATE_NO_WINDOW +LOGGER = logging.getLogger(__name__) GRACE_PERIOD_CI = timedelta(hours=1) # prevent version switch in the middle of a CI run GRACE_PERIOD_MINOR = timedelta(days=28) UPDATE_PERIOD = timedelta(days=14) @@ -45,7 +46,7 @@ def periodic_update( # noqa: PLR0913 def _update_wheel(ver): updated_wheel = Wheel(app_data.house / ver.filename) - logging.debug("using %supdated wheel %s", "periodically " if updated_wheel else "", updated_wheel) + LOGGER.debug("using %supdated wheel %s", "periodically " if updated_wheel else "", updated_wheel) return updated_wheel u_log = UpdateLog.from_app_data(app_data, distribution, for_py_version) @@ -79,10 +80,10 @@ def handle_auto_update(distribution, for_py_version, wheel, search_dirs, app_dat def add_wheel_to_update_log(wheel, for_py_version, app_data): embed_update_log = app_data.embed_update_log(wheel.distribution, for_py_version) - logging.debug("adding %s information to %s", wheel.name, embed_update_log.file) + LOGGER.debug("adding %s information to %s", wheel.name, embed_update_log.file) u_log = UpdateLog.from_dict(embed_update_log.read()) if any(version.filename == wheel.name for version in u_log.versions): - logging.warning("%s already present in %s", wheel.name, embed_update_log.file) + LOGGER.warning("%s already present in %s", wheel.name, embed_update_log.file) return # we don't need a release date for sources other than "periodic" version = NewVersion(wheel.name, datetime.now(tz=timezone.utc), None, "download") @@ -220,7 +221,7 @@ def trigger_update(distribution, for_py_version, wheel, search_dirs, app_data, e if not debug and sys.platform == "win32": kwargs["creationflags"] = CREATE_NO_WINDOW process = Popen(cmd, **kwargs) - logging.info( + LOGGER.info( "triggered periodic upgrade of %s%s (for python %s) via background process having PID %d", distribution, "" if wheel is None else f"=={wheel.version}", @@ -239,7 +240,7 @@ def do_update(distribution, for_py_version, embed_filename, app_data, search_dir try: versions = _run_do_update(app_data, distribution, embed_filename, for_py_version, periodic, search_dirs) finally: - logging.debug("done %s %s with %s", distribution, for_py_version, versions) + LOGGER.debug("done %s %s with %s", distribution, for_py_version, versions) return versions @@ -297,7 +298,7 @@ def _run_do_update( # noqa: C901, PLR0913 break release_date = release_date_for_wheel_path(dest.path) last = NewVersion(filename=dest.path.name, release_date=release_date, found_date=download_time, source=source) - logging.info("detected %s in %s", last, datetime.now(tz=timezone.utc) - download_time) + LOGGER.info("detected %s in %s", last, datetime.now(tz=timezone.utc) - download_time) versions.append(last) filenames.add(last.filename) last_wheel = last.wheel @@ -325,7 +326,7 @@ def release_date_for_wheel_path(dest): upload_time = content["releases"][wheel.version][0]["upload_time"] return datetime.strptime(upload_time, "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc) except Exception as exception: # noqa: BLE001 - logging.error("could not load release date %s because %r", content, exception) # noqa: TRY400 + LOGGER.error("could not load release date %s because %r", content, exception) # noqa: TRY400 return None @@ -353,9 +354,9 @@ def _pypi_get_distribution_info(distribution): content = json.load(file_handler) break except URLError as exception: - logging.error("failed to access %s because %r", url, exception) # noqa: TRY400 + LOGGER.error("failed to access %s because %r", url, exception) # noqa: TRY400 except Exception as exception: # noqa: BLE001 - logging.error("failed to access %s because %r", url, exception) # noqa: TRY400 + LOGGER.error("failed to access %s because %r", url, exception) # noqa: TRY400 return content @@ -386,7 +387,7 @@ def _run_manual_upgrade(app_data, distribution, for_py_version, env): do_periodic_update=False, env=env, ) - logging.warning( + LOGGER.warning( "upgrade %s for python %s with current %s", distribution, for_py_version, @@ -410,7 +411,7 @@ def _run_manual_upgrade(app_data, distribution, for_py_version, env): args.append("\n".join(f"\t{v}" for v in versions)) ver_update = "new entries found:\n%s" if versions else "no new versions found" msg = f"upgraded %s for python %s in %s {ver_update}" - logging.warning(msg, *args) + LOGGER.warning(msg, *args) __all__ = [ diff --git a/src/virtualenv/util/lock.py b/src/virtualenv/util/lock.py index b4dc66a38..b8c9cf833 100644 --- a/src/virtualenv/util/lock.py +++ b/src/virtualenv/util/lock.py @@ -11,6 +11,8 @@ from filelock import FileLock, Timeout +LOGGER = logging.getLogger(__name__) + class _CountedFileLock(FileLock): def __init__(self, lock_file) -> None: @@ -116,7 +118,7 @@ def _lock_file(self, lock, no_block=False): # noqa: FBT002 except Timeout: if no_block: raise - logging.debug("lock file %s present, will block until released", lock.lock_file) + LOGGER.debug("lock file %s present, will block until released", lock.lock_file) lock.release() # release the acquire try from above lock.acquire() diff --git a/src/virtualenv/util/path/_sync.py b/src/virtualenv/util/path/_sync.py index 78684f015..02a6f6e9e 100644 --- a/src/virtualenv/util/path/_sync.py +++ b/src/virtualenv/util/path/_sync.py @@ -6,10 +6,12 @@ import sys from stat import S_IWUSR +LOGGER = logging.getLogger(__name__) + def ensure_dir(path): if not path.exists(): - logging.debug("create folder %s", str(path)) + LOGGER.debug("create folder %s", str(path)) os.makedirs(str(path)) @@ -20,16 +22,16 @@ def ensure_safe_to_do(src, dest): if not dest.exists(): return if dest.is_dir() and not dest.is_symlink(): - logging.debug("remove directory %s", dest) + LOGGER.debug("remove directory %s", dest) safe_delete(dest) else: - logging.debug("remove file %s", dest) + LOGGER.debug("remove file %s", dest) dest.unlink() def symlink(src, dest): ensure_safe_to_do(src, dest) - logging.debug("symlink %s", _Debug(src, dest)) + LOGGER.debug("symlink %s", _Debug(src, dest)) dest.symlink_to(src, target_is_directory=src.is_dir()) @@ -37,7 +39,7 @@ def copy(src, dest): ensure_safe_to_do(src, dest) is_dir = src.is_dir() method = copytree if is_dir else shutil.copy - logging.debug("copy %s", _Debug(src, dest)) + LOGGER.debug("copy %s", _Debug(src, dest)) method(str(src), str(dest)) diff --git a/src/virtualenv/util/zipapp.py b/src/virtualenv/util/zipapp.py index 80776d010..764c5c277 100644 --- a/src/virtualenv/util/zipapp.py +++ b/src/virtualenv/util/zipapp.py @@ -6,6 +6,8 @@ from virtualenv.info import IS_WIN, ROOT +LOGGER = logging.getLogger(__name__) + def read(full_path): sub_file = _get_path_within_zip(full_path) @@ -14,7 +16,7 @@ def read(full_path): def extract(full_path, dest): - logging.debug("extract %s to %s", full_path, dest) + LOGGER.debug("extract %s to %s", full_path, dest) sub_file = _get_path_within_zip(full_path) with zipfile.ZipFile(ROOT, "r") as zip_file: info = zip_file.getinfo(sub_file) diff --git a/tasks/upgrade_wheels.py b/tasks/upgrade_wheels.py index 8b4a1b508..70269d084 100644 --- a/tasks/upgrade_wheels.py +++ b/tasks/upgrade_wheels.py @@ -119,8 +119,14 @@ def get_embed_wheel(distribution, for_py_version): ) dest_target = DEST / "__init__.py" dest_target.write_text(msg, encoding="utf-8") - subprocess.run([sys.executable, "-m", "ruff", "format", str(dest_target), "--preview"]) - subprocess.run([sys.executable, "-m", "ruff", "check", str(dest_target), "--fix", "--unsafe-fixes"]) + subprocess.run( + [sys.executable, "-m", "ruff", "check", str(dest_target), "--fix", "--unsafe-fixes"], + check=False, + ) + subprocess.run( + [sys.executable, "-m", "ruff", "format", str(dest_target), "--preview"], + check=False, + ) raise SystemExit(outcome) diff --git a/tox.ini b/tox.ini index 591ecd9f1..e7e944189 100644 --- a/tox.ini +++ b/tox.ini @@ -76,7 +76,7 @@ pass_env = UPGRADE_ADVISORY change_dir = {toxinidir}/tasks commands = - python upgrade_wheels.py + - python upgrade_wheels.py uv_seed = true [testenv:release]