diff --git a/.gitattributes b/.gitattributes index ab6c3709608a099736aa6dcb01a7215217b466fa..c788f7a97c46c5ed43bb39ebd0e7e79ea3e7d811 100644 --- a/.gitattributes +++ b/.gitattributes @@ -151,3 +151,16 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/charset_normalizer/md.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/contourpy/_contourpy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/cv2/cv2.abi3.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/deprecate/__pycache__/deprecation.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/__pycache__/agl.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/cffLib/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/cu2qu/cu2qu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/designspaceLib/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/feaLib/__pycache__/ast.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/feaLib/__pycache__/parser.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/feaLib/lexer.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/misc/bezierTools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/otlLib/__pycache__/builder.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/pens/momentsPen.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/qu2cu/qu2cu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/fontTools/subset/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/lib/python3.12/site-packages/deprecate/__pycache__/_types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/deprecate/__pycache__/_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3f6cc41ff705f05202d0bd4f8cd4ddef3f520db Binary files /dev/null and b/.venv/lib/python3.12/site-packages/deprecate/__pycache__/_types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/deprecate/__pycache__/audit.cpython-312.pyc b/.venv/lib/python3.12/site-packages/deprecate/__pycache__/audit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c5d283f0b0f9523d7e700b582dd5b17c94a46af Binary files /dev/null and b/.venv/lib/python3.12/site-packages/deprecate/__pycache__/audit.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/deprecate/__pycache__/deprecation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/deprecate/__pycache__/deprecation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7186c8ba149e12f494b21f46f4bb134cc1bf9705 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/deprecate/__pycache__/deprecation.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d02b9b23d8f486a52d5ac16476672a23d5352cef60b5bf8e0c3638201814b39f +size 100575 diff --git a/.venv/lib/python3.12/site-packages/deprecate/__pycache__/proxy.cpython-312.pyc b/.venv/lib/python3.12/site-packages/deprecate/__pycache__/proxy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0da79147a7f734cd0ad0bdd0515c326e80a1468f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/deprecate/__pycache__/proxy.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/deprecate/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/deprecate/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..037a9cffffe13eb4a8059bdfe073ee4bb66c7224 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/deprecate/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/deprecate/_cli.py b/.venv/lib/python3.12/site-packages/deprecate/_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..eaeec8de794f5333de0bcf0124fd64fe81387a1a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/deprecate/_cli.py @@ -0,0 +1,756 @@ +"""CLI entry point for pyDeprecate validation. + +Provides two entry points for scanning Python code for misconfigured ``@deprecated`` wrappers: + +- ``pydeprecate `` — console script installed via ``pip install 'pyDeprecate[cli]'`` +- ``python -m deprecate `` — module invocation of the same CLI + +Subcommands: + check — Validate wrapper configuration and flag misconfigured, chain-forming, or positional-only-arg wrappers. + expiry — Check for deprecated wrappers that have passed their scheduled ``remove_in`` deadline. + chains — Detect deprecated wrappers whose ``target`` is itself a deprecated callable. + all — Run all three checks in a single scan pass. + status — Render a markdown deprecation table to stdout (and optionally save it to a file). + +""" + +import contextlib +import functools +import importlib.util +import sys +from collections.abc import Callable +from pathlib import Path +from typing import Any, Optional + +from deprecate._pkg import ( + _auto_detect_version, + _find_child_packages, + _is_package_dir, + _managed_sys_path, + _resolve_module_name, + _safe_module_name, +) +from deprecate.audit import ( + DeprecationWrapperInfo, + TableStyle, + _check_expiry_for_callables, + find_deprecation_wrappers, + generate_deprecation_table, + validate_deprecation_chains, + validate_deprecation_expiry, +) + + +def _is_package_available(name: str) -> bool: + """Return True if *name* is importable without actually importing it.""" + return importlib.util.find_spec(name) is not None + + +def _print(msg: str, *, stderr: bool = False) -> None: + """Print a message, using Rich console when available. + + Routes output through :class:`~rich.console.Console` when the ``rich`` + package is installed, falling back to built-in :func:`print` otherwise. + + Args: + msg: The message to print. + stderr: If ``True``, send the message to *stderr* instead of *stdout*. + + """ + if _Reporter._HAS_RICH: + _Reporter._console(stderr).print(msg, markup=False, highlight=False) + else: + std_ = sys.stderr if stderr else sys.stdout + print(msg, file=std_) + + +def _scan_directory(path: str, include_members: bool = True) -> list[DeprecationWrapperInfo]: + """Scan a plain directory of top-level Python files. + + Nested Python files in subdirectories are skipped unless they are part of an importable package layout. Plain + directories do not generally support dotted imports for nested modules, so this function only scans top-level + modules and warns when deeper files are present. + + """ + abs_path: Path = Path(path).resolve() + results: list[DeprecationWrapperInfo] = [] + + original_argv = sys.argv[:] + sys.argv = sys.argv[:1] # hide CLI args from any module-level code (e.g. setup.py) + try: + for entry in sorted(abs_path.iterdir(), key=lambda ent: ent.name): + if not (entry.is_file() and entry.suffix == ".py" and not entry.name.startswith("__")): + continue + module_name: str = entry.stem + try: + results.extend(find_deprecation_wrappers(module_name, recursive=False, include_members=include_members)) + except SystemExit: + _print(f"Skipping {module_name}: module-level code exited (not a library module)", stderr=True) + except Exception as e: + _print(f"Could not scan {module_name}: {e}", stderr=True) + finally: + sys.argv = original_argv + + nested_python_files_found: bool = any( + not fpy.name.startswith("__") for fpy in abs_path.rglob("*.py") if fpy.parent != abs_path + ) + + if nested_python_files_found: + _print( + "Skipping nested Python files in plain directory scan. Use an importable package layout with '__init__.py'" + " files, or scan an importable module/package path instead.", + stderr=True, + ) + return results + + +def _scan_path(path: str, recursive: bool = True, include_members: bool = True) -> list[DeprecationWrapperInfo]: + """Scan a directory or importable module/package name for deprecated wrappers. + + File paths are not accepted because ``find_deprecation_wrappers()`` expects an importable module or package name, + not a filesystem path. + + """ + pth: Path = Path(path) + if pth.is_dir(): + if _is_package_dir(pth): + # package dir: resolve importable name from directory stem + return find_deprecation_wrappers( + Path(path).resolve().name, recursive=recursive, include_members=include_members + ) + # Flat src-layout or project root: find package in direct children or src/ subdir. + child_pkgs = _find_child_packages(pth) + if len(child_pkgs) == 1: + return _scan_path(str(child_pkgs[0]), recursive=recursive, include_members=include_members) + return _scan_directory(path, include_members=include_members) + if pth.is_file(): + raise ValueError( + f"File paths are not supported: {path!r}. Pass an importable module/package name or a directory instead." + ) + return find_deprecation_wrappers(path, recursive=recursive, include_members=include_members) + + +# --------------------------------------------------------------------------- +# Reporter — all rich/plain dispatch in one namespace +# --------------------------------------------------------------------------- + + +class _Reporter: + _HAS_RICH: bool = _is_package_available("rich") + _out: Any = None + _err: Any = None + _rich_box: Any = None + _RichTable: Any = None + + try: + from rich import box as _rich_box_import + from rich.console import Console as _RichConsole + from rich.table import Table as _RichTable_import + + _rich_box = _rich_box_import + _RichTable = _RichTable_import + _out = _RichConsole() + _err = _RichConsole(stderr=True) + except ImportError: # pragma: no cover + pass + + @staticmethod + def _console(stderr: bool = False) -> Any: # noqa: ANN401 + """Return the Rich Console for stdout (default) or stderr.""" + return _Reporter._err if stderr else _Reporter._out + + @staticmethod + def _make_table(title: str, col: str, *, title_style: str, col_style: str) -> Any: # noqa: ANN401 + """Build a three-column Module/Function/ Rich table.""" + table = _Reporter._RichTable(title=title, box=_Reporter._rich_box.ROUNDED, title_style=title_style) + table.add_column("Module", style="cyan") + table.add_column("Function", style="magenta") + table.add_column(col, style=col_style) + return table + + @staticmethod + def _render_table( + title: str, + col: str, + *, + title_style: str, + col_style: str, + rows: list[tuple[str, ...]], + plain_prefix: str, + ) -> None: + """Render a three-column Module/Function/Detail table (rich or plain fallback).""" + if _Reporter._HAS_RICH: + table = _Reporter._make_table(title, col, title_style=title_style, col_style=col_style) + for row in rows: + table.add_row(*row) + _Reporter._console().print(table) + else: + _print(f"\n{plain_prefix}") + for mod, fn, detail in rows: + _print(f"\t- {mod}.{fn}: {detail}") + + @staticmethod + def invalid_args(items: list[DeprecationWrapperInfo]) -> None: + """Report wrappers with invalid ``args_mapping`` keys.""" + _Reporter._render_table( + "Invalid Argument Mappings", + "Invalid Args", + title_style="bold red", + col_style="red", + rows=[(r.module, r.function, ", ".join(r.invalid_args)) for r in items], + plain_prefix="[ERROR] Found functions with invalid argument mappings:", + ) + + @staticmethod + def identity_args_mappings(items: list[DeprecationWrapperInfo]) -> None: + """Report wrappers whose ``args_mapping`` maps an argument to itself.""" + _Reporter._render_table( + "Identity Argument Mappings (arg -> arg)", + "Identity Args", + title_style="bold yellow", + col_style="yellow", + rows=[(r.module, r.function, ", ".join(r.identity_args_mapping)) for r in items], + plain_prefix="[WARNING] Found functions with identity argument mappings (arg -> arg):", + ) + + @staticmethod + def no_effect(items: list[DeprecationWrapperInfo]) -> None: + """Report wrappers that have no observable effect on callers.""" + + def _reasons(r: DeprecationWrapperInfo) -> str: + """Format the no-effect reasons for a single wrapper as a comma-separated string.""" + parts = [] + if r.empty_args_mapping: + parts.append("Empty mapping") + if r.self_reference: + parts.append("Self reference") + if r.all_identity: + parts.append("All identity mappings") + return ", ".join(parts) + + _Reporter._render_table( + "No-Effect Wrappers (zero impact)", + "Reason", + title_style="bold yellow", + col_style="yellow", + rows=[(r.module, r.function, _reasons(r)) for r in items], + plain_prefix="[WARNING] Found deprecated wrappers with NO EFFECT (zero impact):", + ) + + @staticmethod + def chains(items: list[DeprecationWrapperInfo], *, error: bool = False) -> None: + """Report deprecated-to-deprecated forwarding chains; ``error=True`` renders in red.""" + style = "bold red" if error else "bold yellow" + col_style = "red" if error else "yellow" + prefix = "[ERROR]" if error else "[WARNING]" + _Reporter._render_table( + "Deprecation Chains", + "Chain Type", + title_style=style, + col_style=col_style, + rows=[(r.module, r.function, r.chain_type.value if r.chain_type is not None else "") for r in items], + plain_prefix=f"{prefix} Found deprecated wrappers forming deprecation chains:", + ) + + @staticmethod + def expiry(expired: list[str]) -> None: + """Report deprecated wrappers that have passed their ``remove_in`` deadline.""" + if _Reporter._HAS_RICH: + table = _Reporter._RichTable( + title="Expired Deprecated Wrappers", box=_Reporter._rich_box.ROUNDED, title_style="bold red" + ) + table.add_column("Message", style="red") + for msg in expired: + table.add_row(msg) + _Reporter._console().print(table) + else: + _print("\n[ERROR] Found expired deprecated wrappers:") + for msg in expired: + _print(f"\t- {msg}") + + @staticmethod + def positional_only_args(items: list[DeprecationWrapperInfo]) -> None: + """Report wrappers whose ``args_mapping`` remaps a kwarg to a POSITIONAL_ONLY constructor parameter.""" + _Reporter._render_table( + "Positional-Only Constructor Args in args_mapping", + "Positional-Only Args", + title_style="bold yellow", + col_style="yellow", + rows=[(r.module, r.function, ", ".join(r.args_mapping_positional_only)) for r in items], + plain_prefix=( + "[WARNING] Found args_mapping entries targeting POSITIONAL_ONLY constructor parameters" + " (proxy falls back to setattr for these entries):" + ), + ) + + @staticmethod + def issues(results: list[DeprecationWrapperInfo], *, error_on_chains: bool = False) -> bool: + """Print categorised diagnostics and return whether any issues were found.""" + invalid_args = [r for r in results if r.invalid_args] + identity_args_mappings = [r for r in results if r.identity_args_mapping] + no_effect = [r for r in results if r.no_effect] + chains = [r for r in results if r.chain_type is not None] + positional_only = [r for r in results if r.args_mapping_positional_only] + + if not (invalid_args or identity_args_mappings or no_effect or chains or positional_only): + return False + + if invalid_args: + _Reporter.invalid_args(invalid_args) + if identity_args_mappings: + _Reporter.identity_args_mappings(identity_args_mappings) + if no_effect: + _Reporter.no_effect(no_effect) + if chains: + _Reporter.chains(chains, error=error_on_chains) + if positional_only: + _Reporter.positional_only_args(positional_only) + + return True + + +def _do_expiry(path: str, version: Optional[str], recursive: bool) -> Optional[list[str]]: + """Run the expiry scan and return expired wrapper messages, or None when packaging is unavailable. + + Caller is responsible for setting up ``sys.path`` via :func:`_managed_sys_path` before calling. + + Args: + path: Package directory path or importable module name string. + version: Current package version for comparison, or None to auto-detect. + recursive: Scan submodules recursively. + + Returns: + List of expired wrapper message strings (may be empty), or None when the + ``packaging`` library is unavailable (advisory — warning already printed to stderr). + + """ + module_name = _resolve_module_name(path) + try: + return validate_deprecation_expiry(module_name, version, recursive=recursive) + except ImportError as exc: + if _is_missing_packaging_import_error(exc): + _print( + "The 'expiry' subcommand requires the 'packaging' library.\n" + "Install it with: `pip install 'pyDeprecate[audit]'`", + stderr=True, + ) + return None + if getattr(exc, "name", None) is not None: + # Python's import system sets ``exc.name`` when a module-level ``import`` statement + # fails — this is a broken import inside the user's package, not a version-detection + # failure. Propagate so the caller gets the real error instead of the misleading + # "Could not determine version" message. + raise + _print( + "Could not determine the current package version automatically.\n" + "Pass --version explicitly, or ensure the package is installed and importable.\n\n" + f"Original error: {exc}", + stderr=True, + ) + return None + # other exceptions propagate to cli()'s top-level handler around fire.Fire + + +def _is_missing_packaging_import_error(error: ImportError) -> bool: + """Return True when an ImportError was caused by a missing packaging dependency. + + Args: + error: The ImportError raised while trying to inspect expiry information. + + Returns: + True if the error indicates that the ``packaging`` library is unavailable. + + """ + for exc in (error, getattr(error, "__cause__", None)): + if exc is None: + continue + name = getattr(exc, "name", None) + if isinstance(name, str) and (name == "packaging" or name.startswith("packaging.")): + return True + return "No module named 'packaging'" in str(error) + + +# --------------------------------------------------------------------------- +# Subcommand functions +# --------------------------------------------------------------------------- + + +def _print_scan_header(path: str, version: Optional[str] = None, *, user_provided: bool = False) -> None: + """Print a consistent scan header: scanning location, package name, and version.""" + module = _safe_module_name(path) + _print(f"Scanning: {path}") + if version is not None: + source = "user-provided" if user_provided else "auto-detected" + _print(f"Package: {module} Version: {version} ({source})") + else: + _print(f"Package: {module}") + + +def cmd_check( + path: str = ".", + recursive: bool = True, + exit_zero: bool = False, + *, + _wrappers: Optional[list[DeprecationWrapperInfo]] = None, +) -> int: + """Scan Python code for misconfigured ``@deprecated`` wrappers and deprecation chains. + + Reports invalid argument mappings (exit 1), identity mappings, no-effect wrappers, + deprecation chains, and ``args_mapping`` entries targeting POSITIONAL_ONLY constructor + parameters (all advisory warnings only, exit 0). Use the ``chains`` subcommand for a + dedicated hard-error chain check. + + Args: + path: Path to the module, package directory, or importable module name to scan. + recursive: Scan submodules recursively (default True). Pass ``--norecursive`` to scan top-level only. + exit_zero: Always exit 0 even if hard errors (invalid argument mappings) are found. + Useful for advisory CI steps that should report but never block. + _wrappers: Pre-scanned wrapper list. When provided, skips the scan step. Underscore + prefix hides this parameter from the Fire CLI (internal use by ``cmd_all`` only). + + Returns: + 0 on success or advisory-only issues; 1 when hard errors are found and ``exit_zero`` is False. + + """ + if _wrappers is None: + _print_scan_header(path) + with _managed_sys_path(path): + _wrappers = _scan_path(path, recursive=recursive) + + if not _wrappers: + _print("No deprecated callables found.") + return 0 + + if _Reporter.issues(_wrappers, error_on_chains=False): + _print("\nIssues were found in deprecated wrappers.") + else: + _print("\nAll deprecated wrappers look correct!") + + has_invalid = any(r.invalid_args for r in _wrappers) + return 1 if not exit_zero and has_invalid else 0 + + +def cmd_expiry( + path: str = ".", + version: Optional[str] = None, + recursive: bool = True, + exit_zero: bool = False, + *, + _wrappers: Optional[list[DeprecationWrapperInfo]] = None, +) -> int: + """Check for deprecated wrappers that have passed their scheduled removal version. + + Requires the ``packaging`` library: ``pip install 'pyDeprecate[audit]'``. + A missing ``packaging`` library is treated as advisory (returns 0 with a warning). + + Args: + path: Path to the module, package directory, or importable module name to scan. + version: Current package version for comparison (e.g. ``"2.0.0"``). Auto-detected + from installed package metadata if not provided. + recursive: Scan submodules recursively (default True). Pass ``--norecursive`` to scan top-level only. + exit_zero: Always exit 0 even if expired wrappers are found. + Useful for advisory CI steps that should report but never block. + _wrappers: Pre-scanned wrapper list. When provided, skips the scan step and derives + expired wrappers via ``_check_expiry_for_callables``. Requires *version* to be + non-``None`` when set. Underscore prefix hides this parameter from the Fire CLI + (internal use by ``cmd_all`` only). + + Returns: + 0 on success or when the ``packaging`` library is unavailable; 1 when expired + wrappers are found and ``exit_zero`` is False. + + """ + # Fire auto-converts numeric-looking strings (e.g. "1.0" → float); normalise to str. + if version is not None: + version = str(version) + if _wrappers is None: + # Standalone path: full scan + version auto-detect inside _do_expiry. + resolved_version = version if version is not None else _auto_detect_version(_safe_module_name(path), path=path) + if resolved_version is None and version is None: + _print( + "Could not resolve the current package version automatically and no --version was given; " + "the expiry check runs without a resolved version and its result may be unreliable. " + "Pass --version explicitly for a definitive check.", + stderr=True, + ) + _print_scan_header(path, resolved_version, user_provided=version is not None) + with _managed_sys_path(path): + raw = _do_expiry(path, resolved_version, recursive) + if raw is None: # packaging unavailable — warning already printed to stderr + return 0 + expired = raw + else: + # Pre-scanned path: derive expired list from wrappers directly. + if version is None: + _print("Cannot check expiry: version not resolved. Pass --version explicitly.", stderr=True) + return 0 + try: + expired = _check_expiry_for_callables(_wrappers, version) + except ImportError: + _print( + "The 'expiry' subcommand requires the 'packaging' library.\n" + "Install it with: `pip install 'pyDeprecate[audit]'`", + stderr=True, + ) + return 0 + if not expired: + _print("No expired deprecated wrappers found.") + return 0 + _Reporter.expiry(expired) + _print(f"\n{len(expired)} expired wrapper(s) found.") + return 0 if exit_zero else 1 + + +def cmd_chains( + path: str = ".", + recursive: bool = True, + exit_zero: bool = False, + *, + _wrappers: Optional[list[DeprecationWrapperInfo]] = None, +) -> int: + """Detect deprecated wrappers whose ``target`` is itself a deprecated callable (chains). + + Two chain kinds are detected: ``target`` (forwarding chain to another deprecated + callable) and ``stacked`` (composed argument mappings that should be collapsed). + + Args: + path: Path to the module, package directory, or importable module name to scan. + recursive: Scan submodules recursively (default True). Pass ``--norecursive`` to scan top-level only. + exit_zero: Always exit 0 even if chains are found. + Useful for advisory CI steps that should report but never block. + _wrappers: Pre-scanned wrapper list. When provided, skips the scan step and filters + for ``chain_type is not None`` internally. Underscore prefix hides this parameter + from the Fire CLI (internal use by ``cmd_all`` only). + + Returns: + 0 when no chains are found or ``exit_zero`` is True; 1 when chains are found. + + """ + if _wrappers is None: + _print_scan_header(path) + with _managed_sys_path(path): + _wrappers = validate_deprecation_chains(_resolve_module_name(path), recursive=recursive) + chains = [r for r in _wrappers if r.chain_type is not None] + if not chains: + _print("No deprecation chains found.") + return 0 + _Reporter.chains(chains, error=True) + _print(f"\n{len(chains)} deprecation chain(s) found.") + return 0 if exit_zero else 1 + + +def cmd_all( + path: str = ".", + version: Optional[str] = None, + recursive: bool = True, + exit_zero: bool = False, +) -> int: + """Run all three checks then append a deprecation table. + + Performs a single scan pass and distributes the wrappers to ``cmd_check``, + ``cmd_expiry``, and ``cmd_chains`` so the filesystem is only traversed once. + After all three checks complete, ``cmd_status`` is always called to append a + compact markdown deprecation table to the output. + Version is auto-detected from installed package metadata when not provided. + A missing ``packaging`` library skips the expiry check with a warning and does not + count as a hard error. + + Args: + path: Path to the module, package directory, or importable module name to scan. + version: Current package version for expiry comparison (e.g. ``"2.0.0"``). + Auto-detected from installed package metadata if not provided. + recursive: Scan submodules recursively (default True). Pass ``--norecursive`` to scan top-level only. + exit_zero: Always exit 0 even if issues are found. + Useful for advisory CI steps that should report but never block. + + Returns: + 0 when all checks pass or ``exit_zero`` is True; 1 when any hard error is found. + The deprecation table is always appended regardless of pass/fail outcome. + + """ + if version is not None: + version = str(version) + version_path = path if Path(path).exists() else None + resolved_version = ( + version if version is not None else _auto_detect_version(_safe_module_name(path), path=version_path) + ) + _print_scan_header(path, resolved_version, user_provided=version is not None) + with _managed_sys_path(path): + wrappers = _scan_path(path, recursive=recursive) + + # Sub-commands run with exit_zero=False so cmd_all sees their truthful exit codes; + # the user-facing --exit-zero is applied to the aggregate below. + check_code = cmd_check(path, recursive=recursive, exit_zero=False, _wrappers=wrappers) + expiry_code = cmd_expiry(path, version=resolved_version, recursive=recursive, exit_zero=False, _wrappers=wrappers) + chains_code = cmd_chains(path, recursive=recursive, exit_zero=False, _wrappers=wrappers) + + # The status table is a display artifact appended after the three gates. Render it defensively: + # a table-rendering failure must never change the aggregate exit code the three checks produced. + try: + cmd_status(path, version=resolved_version, recursive=recursive, _wrappers=wrappers) + except Exception as exc: + _print(f"Could not render the deprecation table: {exc}", stderr=True) + + has_errors = bool(check_code or expiry_code or chains_code) + return 0 if not has_errors or exit_zero else 1 + + +def cmd_status( + path: str = ".", + version: Optional[str] = None, + recursive: bool = True, + style: str = "compact", + include_members: bool = True, + output: Optional[str] = None, + *, + _wrappers: Optional[list[DeprecationWrapperInfo]] = None, +) -> int: + """Print a markdown deprecation status table to stdout. + + Scans the target package for deprecated wrappers and renders their lifecycle + status as a Markdown table. Standalone — runs no checks, always exits 0. + When ``--output`` is given, the table is also written to that file. + + Args: + path: Path to the module, package directory, or importable module name to scan. + version: Current package version for lifecycle status (e.g. ``"2.0.0"``). + Auto-detected from installed package metadata if not provided. + recursive: Scan submodules recursively (default True). Pass ``--norecursive`` to scan top-level only. + style: Table format — ``compact`` (default) or ``matrix``. + include_members: Include deprecated class members such as methods and constructors (default True). + output: Optional file path to write the markdown table. The table is always + printed to stdout regardless of this flag. + + Returns: + Always 0 — status table generation is not a pass/fail gate. + + """ + if version is not None: + version = str(version) + try: + table_style = TableStyle(style) + except ValueError: + valid = ", ".join(s.value for s in TableStyle) + _print(f"Invalid style {style!r}; falling back to 'compact'. Expected one of: {valid}.", stderr=True) + table_style = TableStyle.COMPACT + + # Never resolve the importable module name eagerly: status "always exits 0" (it is not a + # pass/fail gate), so a plain directory without ``__init__.py`` — which ``check`` scans fine and + # for which ``_wrappers`` is already supplied by ``cmd_all`` — must not raise here. ``_safe_module_name`` + # falls back to the raw path, used only as table metadata for version resolution. + module_name = _safe_module_name(path) + resolved_version = version if version is not None else _auto_detect_version(module_name, path=path) + if _wrappers is None: + _print_scan_header(path, resolved_version, user_provided=version is not None) + with _managed_sys_path(path): + _wrappers = _scan_path(path, recursive=recursive, include_members=include_members) + markdown = generate_deprecation_table( + module_name, + current_version=resolved_version, + style=table_style, + _wrappers=_wrappers, + ) + + if _Reporter._HAS_RICH: + from rich.markdown import Markdown + + _Reporter._console().print(Markdown(markdown)) + else: + _print(markdown) + + if output is not None: + out_path = Path(output) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text(markdown, encoding="utf-8") + _print(f"→ Saved to: {out_path}", stderr=True) + + return 0 + + +# --------------------------------------------------------------------------- +# CLI entry point +# --------------------------------------------------------------------------- + + +def _ensure_utf8_streams() -> None: + """Reconfigure stdout/stderr to UTF-8 on platforms where the default encoding may reject non-ASCII characters. + + On Windows the default console codec (``charmap``) cannot encode Unicode emoji used by + :class:`~deprecate.audit.DeprecationStatus`. Calling ``reconfigure`` before any output is written ensures emoji + reach the terminal (or CI log) without a :exc:`UnicodeEncodeError`. + + The call is a no-op when the streams are already UTF-8 or when they lack a ``reconfigure`` method (binary streams, + pytest capture wrappers). + + """ + for stream in (sys.stdout, sys.stderr): + # ``encoding`` may be *present but None* (e.g. some redirected/binary-ish wrappers); ``getattr`` with a + # default only covers a missing attribute, so guard the ``None`` case with ``or "utf-8"`` before ``.lower()``. + encoding = (getattr(stream, "encoding", None) or "utf-8").lower() + if hasattr(stream, "reconfigure") and encoding != "utf-8": + with contextlib.suppress(Exception): + stream.reconfigure(encoding="utf-8") + + +def cli() -> None: + """CLI entry point for pydeprecate. + + The subcommand's integer return value becomes the process exit code, applied *after* ``fire.Fire`` + returns. Raising ``SystemExit`` from inside the Fire trace would abort Fire's own unconsumed-argument + check, silently ignoring unknown or misspelled flags (exit 0 on typos); letting the trace complete + makes Fire report ``Could not consume arg`` and exit 2 for such flags. Acts as the single top-level + exception handler: unhandled exceptions from subcommands are converted to a non-zero exit with the + exception type and message (the type prefix guarantees a non-blank stderr line even when the exception + carries no message). SystemExit (Fire's ``--help`` and error exits) passes through unchanged. + + A path whose name collides with a subcommand (``check``, ``expiry``, ``chains``, ``all``, ``status``) is + treated as that subcommand by the implicit-``check`` shim. Scan such a path explicitly, e.g. + ``pydeprecate check ./check``, so the leading token is the subcommand and the path is its argument. + + """ + _ensure_utf8_streams() + try: + import fire + except ImportError: + sys.exit("The 'pydeprecate' CLI requires the 'fire' package.\nInstall it with: pip install 'pyDeprecate[cli]'") + + subcommands = {"check", "expiry", "chains", "all", "status"} + argv = sys.argv[1:] + if argv and argv[0] not in subcommands and argv[0] not in {"-h", "--help"}: + argv = ["check", *argv] + + exit_code: Optional[int] = None + + def _capture(fn: Callable[..., int]) -> Callable[..., None]: + """Record the cmd_* return code without returning it into the Fire trace. + + Returning the int would make Fire print it and treat it as a further component to consume arguments against; + returning ``None`` keeps the output clean and lets Fire finish its trace. + + """ + + @functools.wraps(fn) + def wrapper(*args: object, **kwargs: object) -> None: + nonlocal exit_code + exit_code = fn(*args, **kwargs) + + return wrapper + + try: + fire.Fire( + { + "check": _capture(cmd_check), + "expiry": _capture(cmd_expiry), + "chains": _capture(cmd_chains), + "all": _capture(cmd_all), + "status": _capture(cmd_status), + }, + command=argv, + ) + except Exception as exc: # SystemExit is BaseException — Fire's own exits pass through untouched + # Prefix the exception type so an exception with an empty message still produces a non-blank stderr + # line (bare ``str(exc)`` on such exceptions exited 1 with nothing printed). + sys.exit(f"{type(exc).__name__}: {exc}") + # exit_code stays None when no subcommand ran (bare `pydeprecate` help) → return normally (exit 0). + if exit_code is not None: + sys.exit(exit_code) diff --git a/.venv/lib/python3.12/site-packages/deprecate/_pkg.py b/.venv/lib/python3.12/site-packages/deprecate/_pkg.py new file mode 100644 index 0000000000000000000000000000000000000000..a0279ca8b5e8b3f38a4874e1236522af213ff1b1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/deprecate/_pkg.py @@ -0,0 +1,348 @@ +"""Package and filesystem helpers for pyDeprecate's CLI. + +Internal utilities that resolve a package's version, locate package directories, and manage ``sys.path`` for scanning. + +Version resolution uses a local ``pyproject.toml`` (development checkout) when available, falling back to installed +distribution metadata via ``importlib.metadata``. + +TOML parsing uses ``tomllib`` (stdlib on Python 3.11+) or ``tomli`` (backport, via ``pip install 'pyDeprecate[audit]'`` +on Python 3.9-3.10). When not available the helpers return ``None`` and callers fall back to ``importlib.metadata``. + +This module is private (no ``__all__``); its surface may change without notice. + +""" + +import importlib +import importlib.metadata +import os +import sys +import warnings +from collections.abc import Generator +from contextlib import contextmanager, suppress +from pathlib import Path +from typing import Any, Optional + + +def _load_toml(path: str) -> dict[str, Any]: + r"""Load a TOML file using ``tomllib`` (Python 3.11+) or ``tomli`` (Python 3.10 backport). + + Returns an empty dict on any failure (missing library, parse error, IO). + + Examples: + >>> import os, tempfile + >>> with tempfile.NamedTemporaryFile(suffix=".toml", mode="w", delete=False) as f: + ... _ = f.write('[project]\nname = "mypkg"\nversion = "1.2.3"\n') + ... name = f.name + >>> _load_toml(name).get("project", {}).get("version") + '1.2.3' + >>> os.unlink(name) + + """ + try: + try: + import tomllib + except ImportError: + import tomli as tomllib # Python 3.10 backport + + with open(path, "rb") as fh: + return dict(tomllib.load(fh)) + except Exception: + return {} + + +def _version_from_dynamic(pkg_name: str, scan_path: str, pyproject_dir: str) -> Optional[str]: + """Import *pkg_name* and return its ``__version__``, or ``None`` on any failure. + + Adds candidate import roots (scan dir, its parent, pyproject dir, ``src/`` + sub-dir) to ``sys.path`` before importing, then restores the original + ``sys.path`` unconditionally via ``finally``. + + Args: + pkg_name: Importable package name declared in ``[project].name``. + scan_path: File-system path originally passed to the CLI (used to + locate the package root). + pyproject_dir: Directory containing the ``pyproject.toml`` file. + + Returns: + Version string from ``pkg.__version__`` or ``None``. + + """ + scan_root = os.path.abspath(scan_path) if os.path.isdir(scan_path) else os.path.dirname(os.path.abspath(scan_path)) + original = list(sys.path) + added: list[str] = [] + for root in (scan_root, os.path.dirname(scan_root), pyproject_dir, os.path.join(pyproject_dir, "src")): + if root and os.path.isdir(root) and root not in added: + added.append(root) + sys.path.insert(0, root) + try: + module = importlib.import_module(pkg_name) + version = getattr(module, "__version__", None) + return version if isinstance(version, str) else None + except Exception: + return None + finally: + sys.path[:] = original + + +def _version_from_toml(toml_path: str, scan_path: str) -> Optional[str]: + """Extract ``[project].version`` from *toml_path*, or ``None``. + + Falls back to importing the package for ``dynamic = ["version"]`` projects. + + Args: + toml_path: Absolute path to a ``pyproject.toml`` file. + scan_path: Original file-system path passed to the CLI (forwarded to + :func:`_version_from_dynamic` for import-root resolution). + + Returns: + Version string or ``None`` when not resolvable. + + """ + data = _load_toml(toml_path) + project = data.get("project", {}) + if not project: + return None + + version = project.get("version") + if isinstance(version, str): + return version + + if "version" in project.get("dynamic", []): + pkg_name = project.get("name") + if isinstance(pkg_name, str) and pkg_name: + return _version_from_dynamic(pkg_name, scan_path, os.path.dirname(toml_path)) + + return None + + +def _read_pyproject_version(path: str) -> Optional[str]: + """Return ``[project].version`` from the nearest ``pyproject.toml`` up to 2 levels above *path*. + + Searches the directory itself, its parent, and its grandparent — stops + as soon as a resolvable version is found or the limit is reached. + + Args: + path: File-system path to start the upward search from. + + Returns: + Version string or ``None`` when not found within 2 levels. + + """ + candidate = os.path.abspath(path) + if not os.path.isdir(candidate): + candidate = os.path.dirname(candidate) + for _ in range(3): # current dir + 2 levels up + toml_path = os.path.join(candidate, "pyproject.toml") + if os.path.isfile(toml_path): + version = _version_from_toml(toml_path, path) + if version is not None: + return version + parent = os.path.dirname(candidate) + if parent == candidate: + break + candidate = parent + return None + + +def _auto_detect_version(module_name: str, path: Optional[str] = None) -> Optional[str]: + """Return the version for *module_name*, or ``None`` on any failure. + + Priority order: + + 1. ``[project].version`` in the nearest ``pyproject.toml`` above *path* (reflects + local development checkouts whose version may differ from the installed dist). + 2. ``importlib.metadata.version(module_name)`` — the installed distribution. + + Args: + module_name: Importable package name whose installed version to look up. + path: Optional file-system path used to locate a local ``pyproject.toml``. + Only consulted when it actually exists on the filesystem; an importable + module *name* passed through here is ignored, because the walk-up from the + current working directory would otherwise pick up an unrelated project's + ``pyproject.toml`` version. When honored, the local file takes precedence + over installed metadata. + + Returns: + Version string (e.g. ``"1.2.3"``) or ``None`` when the package is not + installed or the version cannot be determined. + + """ + # Guard: a bare module name (not an existing path) must not trigger the pyproject.toml + # walk-up — starting from cwd it would grab whatever unrelated project the caller is + # standing in, flipping expiry gates on a foreign version. + if path is not None and os.path.exists(path): + local_ver = _read_pyproject_version(path) + if local_ver is not None: + return local_ver + with suppress(Exception): + return importlib.metadata.version(module_name) + # The import name (deprecate, PIL, sklearn) often differs from the distribution name + # (pyDeprecate, Pillow, scikit-learn) that importlib.metadata.version() requires. Map the + # import package to its distribution and retry before giving up. + dist_name = _distribution_for_import(module_name) + if dist_name is not None: + try: + return importlib.metadata.version(dist_name) + except Exception: + return None + return None + + +def _distribution_for_import(import_name: str) -> Optional[str]: + """Map a top-level import package name to its installed distribution name. + + ``importlib.metadata.version`` needs the *distribution* name (``pyDeprecate``) while the CLI is + handed the *import* name (``deprecate``). Uses ``importlib.metadata.packages_distributions`` on + Python 3.11+ and falls back to scanning each distribution's ``top_level.txt`` on Python <3.11. + + Args: + import_name: Importable (possibly dotted) package name; only the first component is used. + + Returns: + The first distribution name that provides the top-level package, or ``None`` when no + installed distribution exposes it. + + """ + top_level = import_name.split(".")[0] + packages_distributions = getattr(importlib.metadata, "packages_distributions", None) + if callable(packages_distributions): + try: + distributions = packages_distributions().get(top_level) + except Exception: + return None + return distributions[0] if distributions else None + # Python <3.11: packages_distributions is unavailable — read top_level.txt from each distribution. + return _distribution_from_top_level(top_level) + + +def _distribution_from_top_level(top_level: str) -> Optional[str]: + """Return the distribution whose ``top_level.txt`` lists *top_level* (Python <3.11 fallback).""" + try: + distributions = list(importlib.metadata.distributions()) + except Exception: + return None + for dist in distributions: + try: + listed = dist.read_text("top_level.txt") + except Exception: + listed = None + if listed and top_level in listed.split(): + try: + name = dist.metadata["Name"] + except KeyError: + continue + if name: + return name + return None + + +def _is_package_dir(pth: Path) -> bool: + """Return True if *pth* is an importable package directory (contains ``__init__.py``).""" + return (pth / "__init__.py").exists() + + +def _find_child_packages(pth: Path) -> list[Path]: + """Return package sub-directories of *pth*, checking ``src/`` when none found directly. + + Resolution order: + 1. Immediate child directories of ``pth/src/`` that contain ``__init__.py`` + (standard ``src/``-layout projects take precedence). + 2. If none, immediate child directories of *pth* that contain ``__init__.py``. + + Args: + pth: Directory to search. + + Returns: + List of :class:`~pathlib.Path` objects for each package directory found. + + """ + src_dir = pth / "src" + if src_dir.is_dir(): + in_src = [c for c in src_dir.iterdir() if c.is_dir() and _is_package_dir(c)] + if in_src: + return in_src + return [c for c in pth.iterdir() if c.is_dir() and _is_package_dir(c)] + + +@contextmanager +def _managed_sys_path(path: str) -> Generator[None, None, None]: + """Context manager that prepends the import root to ``sys.path`` and restores it after scanning. + + For package directories (containing ``__init__.py``), inserts the parent directory so the package name resolves as + an importable module. For plain directories, inserts the directory itself. Importable module name strings are passed + through unchanged. + + Warning: + Not thread-safe. ``sys.path`` is a process-global list; concurrent use from multiple threads will corrupt + the restored state. Each scan should run in a dedicated process or be serialized via a lock. + + """ + abs_path: Path = Path(path).resolve() + original = list(sys.path) + if abs_path.is_dir(): + if _is_package_dir(abs_path): + import_root = str(abs_path.parent) + else: + src_dir = abs_path / "src" + in_src = src_dir.is_dir() and any(c.is_dir() and _is_package_dir(c) for c in src_dir.iterdir()) + import_root = str(src_dir) if in_src else str(abs_path) + sys.path.insert(0, import_root) + try: + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning, module="deprecate.*") + warnings.filterwarnings("ignore", category=FutureWarning, module="deprecate.*") + yield + finally: + sys.path[:] = original + + +def _resolve_module_name(path: str) -> str: + """Convert a filesystem path to an importable module name. + + Accepts a package directory (with ``__init__.py``) or an importable module + name string. Plain directories and individual ``.py`` files are not supported + because ``validate_deprecation_expiry`` and ``validate_deprecation_chains`` + require an importable module name, not a filesystem path. + + Args: + path: Package directory path or importable module name string. + + Returns: + Importable module name string. + + Raises: + ValueError: If path is a plain directory without ``__init__.py``, a ``.py`` + file, or cannot be resolved to an importable module name. + + """ + pth = Path(path) + if pth.is_file(): + raise ValueError( + f"File paths are not supported: {path!r}. Pass an importable module/package name or a directory instead." + ) + if pth.is_dir(): + if _is_package_dir(pth): + return pth.resolve().name + # Flat src-layout or project root: find package in direct children or src/ subdir. + child_pkgs = _find_child_packages(pth) + if len(child_pkgs) == 1: + return child_pkgs[0].name + if len(child_pkgs) > 1: + names = ", ".join(sorted(c.name for c in child_pkgs)) + raise ValueError( + f"Directory {path!r} contains multiple packages ({names}). " + "Pass the specific package sub-directory instead." + ) + raise ValueError( + f"Plain directories without '__init__.py' are not supported for expiry or chain checks: {path!r}. " + "Use an importable package layout with '__init__.py', or pass an importable module name instead." + ) + return path + + +def _safe_module_name(path: str) -> str: + """Return the importable module name for *path*, falling back to *path* itself.""" + try: + return _resolve_module_name(path) + except ValueError: + return path diff --git a/.venv/lib/python3.12/site-packages/deprecate/_types.py b/.venv/lib/python3.12/site-packages/deprecate/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..777d8c9072ca16b687d340349f02df280ed52cd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/deprecate/_types.py @@ -0,0 +1,664 @@ +"""Shared type definitions for pyDeprecate. + +This module provides typed interfaces consumed by the decorator, proxy, and audit modules so that static analysers can +catch schema mismatches at analysis time rather than silently returning ``None`` at runtime. + +""" + +import copy +import threading +import warnings +from collections.abc import Mapping +from dataclasses import dataclass, field, replace +from enum import Enum +from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Protocol, Union, runtime_checkable + +if TYPE_CHECKING: + from typing_extensions import TypeGuard + + +class TargetMode(Enum): + """Selects ``@deprecated`` behaviour when no callable replacement is provided. + + Attributes: + NOTIFY: Notify-only deprecation -- warn on every call; original body executes unchanged. Replaces + ``target=None``. Passing ``args_mapping`` or ``args_extra`` with this mode emits a :class:`UserWarning` + today; :class:`TypeError` is planned in ``v1.0``. + ARGS_REMAP: Deprecate argument names only -- warn only when deprecated argument names are passed; remaps + kwargs via ``args_mapping`` before calling the original body. Replaces ``target=True``. This mode is + strongly recommended with ``args_mapping``; omitting it emits a :class:`UserWarning` today, and + :class:`TypeError` is planned in ``v1.0``. + ATTRS_REMAP: Selective per-attribute deprecation -- warn only when a deprecated attribute alias listed in + ``attrs_mapping`` is accessed; all other attribute access is forwarded silently. Proxy-specific mode: + only valid for :func:`~deprecate.proxy.deprecated_class`; raises :class:`TypeError` on + :func:`~deprecate.deprecated` decorated functions/methods. Analogous to :attr:`ARGS_REMAP` but for + attribute access instead of call arguments. This mode is selected automatically when ``attrs_mapping`` + is non-empty and no explicit ``target`` is provided. + + Examples: + >>> from deprecate import TargetMode + >>> TargetMode.NOTIFY.value + 'notify' + >>> TargetMode.ARGS_REMAP.value + 'args_remap' + >>> TargetMode.ATTRS_REMAP.value + 'attrs_remap' + + """ + + NOTIFY = "notify" + ARGS_REMAP = "args_remap" + ATTRS_REMAP = "attrs_remap" + + @classmethod + def _from_legacy( + cls, + target: Union[None, bool], + *, + stacklevel: Optional[int] = 3, + ) -> "TargetMode": + """Convert ``target`` sentinel (``None`` / ``True`` / ``False``) to :class:`~deprecate._types.TargetMode`. + + Backwards-compatibility shim for the :func:`~deprecate.deprecated` decorator. Each sentinel is mapped to its + modern equivalent and a deprecation warning is emitted. Pass ``stacklevel=None`` to suppress all warnings. + + Args: + target: Legacy sentinel — ``None`` → :attr:`~deprecate._types.TargetMode.NOTIFY`, + ``True`` → :attr:`~deprecate._types.TargetMode.ARGS_REMAP`, + ``False`` → :attr:`~deprecate._types.TargetMode.NOTIFY` (not a valid mode; :class:`TypeError` in v1.0). + stacklevel: Stack level forwarded to :func:`warnings.warn`. Pass ``None`` to suppress all warnings + entirely. Defaults to ``3``. + + Returns: + The corresponding :class:`~deprecate._types.TargetMode` member. + + Raises: + TypeError: If ``target`` is anything other than ``None``, ``True``, or ``False``. + + Examples: + >>> TargetMode._from_legacy(None, stacklevel=None) + + >>> TargetMode._from_legacy(True, stacklevel=None) + + >>> TargetMode._from_legacy(False, stacklevel=None) + + + """ + if target is None: + if stacklevel is not None: + warnings.warn( + "target=None is deprecated since `v0.8`; use `TargetMode.NOTIFY` instead." + " Will be removed in `v1.0`.", + FutureWarning, + stacklevel=stacklevel, + ) + return cls.NOTIFY + if target is True: + if stacklevel is not None: + warnings.warn( + "target=True is deprecated since `v0.8`; use `TargetMode.ARGS_REMAP` instead." + " Will be removed in `v1.0`.", + FutureWarning, + stacklevel=stacklevel, + ) + return cls.ARGS_REMAP + if target is False: + if stacklevel is not None: + warnings.warn( + "`target=False` is not a valid deprecation mode and will be treated as `TargetMode.NOTIFY`." + " This will be `TypeError` in `v1.0`.", + UserWarning, + stacklevel=stacklevel, + ) + return cls.NOTIFY + raise TypeError( + f"`TargetMode._from_legacy` accepts only None, True, or False; got {type(target).__name__}: {target!r}." + ) + + @classmethod + def _from_legacy_proxy( + cls, + target: Any, # noqa: ANN401 + *, + args_mapping: Optional[Mapping[str, Optional[str]]] = None, + stacklevel: Optional[int] = 3, + ) -> "Union[Callable[..., Any], TargetMode, None]": + """Normalise a proxy-specific legacy ``target`` sentinel for :func:`~deprecate.proxy.deprecated_class`. + + ``True`` and ``False`` are invalid for the proxy context and normalise to + :attr:`~deprecate._types.TargetMode.NOTIFY` + (or :attr:`~deprecate._types.TargetMode.ARGS_REMAP` when ``args_mapping`` is non-empty) + after emitting a warning. + All other values pass through unchanged. Pass ``stacklevel=None`` to suppress warnings. + + Args: + target: Raw ``target`` value from the caller. Only ``True`` and ``False`` trigger normalisation; + any other value is returned as-is. + args_mapping: The ``args_mapping`` dict supplied to :func:`~deprecate.deprecated_class`, or ``None`` when + not provided. When ``target=True`` and ``args_mapping`` is non-empty the result is + :attr:`~deprecate._types.TargetMode.ARGS_REMAP` instead of + :attr:`~deprecate._types.TargetMode.NOTIFY`, and a :class:`FutureWarning` is emitted. + stacklevel: Stack level forwarded to :func:`warnings.warn`. Pass ``None`` to suppress all warnings. + Defaults to ``3``. + + Returns: + :attr:`~deprecate._types.TargetMode.ARGS_REMAP` when ``target=True`` and ``args_mapping`` is non-empty; + :attr:`~deprecate._types.TargetMode.NOTIFY` when ``target`` was ``True`` (without ``args_mapping``) or + ``False``; otherwise ``target`` unchanged. + + Examples: + >>> TargetMode._from_legacy_proxy(True, stacklevel=None) + + >>> TargetMode._from_legacy_proxy(True, args_mapping={"old": "new"}, stacklevel=None) + + >>> TargetMode._from_legacy_proxy(False, stacklevel=None) + + >>> TargetMode._from_legacy_proxy(None) is None + True + >>> TargetMode._from_legacy_proxy(TargetMode.NOTIFY) + + + """ + if target is True: + if args_mapping: + if stacklevel is not None: + warnings.warn( + "`target=True` with `args_mapping` will resolve to `TargetMode.ARGS_REMAP`." + " Will be `TypeError` in `v1.0`.", + FutureWarning, + stacklevel=stacklevel, + ) + return cls.ARGS_REMAP + if stacklevel is not None: + warnings.warn( + "`target=True` without `args_mapping` resolves to `TargetMode.NOTIFY`" + " (warns on every access). Will be `TypeError` in `v1.0`.", + FutureWarning, + stacklevel=stacklevel, + ) + return cls.NOTIFY + if target is False: + if stacklevel is not None: + warnings.warn( + "`target=False` is not valid for `deprecated_class()`. Will be `TypeError` in `v1.0`.", + UserWarning, + stacklevel=stacklevel, + ) + return cls.NOTIFY + return target + + @classmethod + def _validate( + cls, + mode: "TargetMode", + source_name: str, + args_mapping: Optional[Mapping[str, Optional[str]]] = None, + args_extra: Optional[dict[str, Any]] = None, + *, + stacklevel: Optional[int] = 2, + ) -> bool: + """Validate :class:`~deprecate._types.TargetMode` against supplied configuration and emit misconfig warnings. + + Checks three misconfiguration combinations and emits a :class:`UserWarning` for each one found. + These warnings will become :class:`TypeError` in ``v1.0``. + + Misconfiguration warnings are always emitted via :func:`warnings.warn` with ``UserWarning`` — they are + construction-time guards independent of the runtime ``stream`` callable used for deprecation notices. + + Args: + mode: The resolved :class:`~deprecate._types.TargetMode` to validate. + source_name: ``__name__`` of the decorated source callable, used in warning messages. + args_mapping: The ``args_mapping`` dict supplied to :func:`~deprecate.deprecated`, or ``None`` when not + provided. + args_extra: The ``args_extra`` dict supplied to :func:`~deprecate.deprecated`, or ``None`` when not + provided. + stacklevel: Stack level forwarded to :func:`warnings.warn` so that reported locations point at the + decorator application site. Pass ``None`` to suppress all warnings. Defaults to ``2``. + + Returns: + ``True`` if any misconfiguration was detected, ``False`` if the configuration is valid. + + Examples: + >>> TargetMode._validate(TargetMode.ARGS_REMAP, "my_func", args_mapping=None, stacklevel=None) + True + >>> TargetMode._validate(TargetMode.NOTIFY, "my_func", args_mapping={"old": "new"}, stacklevel=None) + True + >>> TargetMode._validate(TargetMode.NOTIFY, "my_func", args_extra={"bias": 1}, stacklevel=None) + True + >>> TargetMode._validate(TargetMode.NOTIFY, "my_func", stacklevel=None) + False + + """ + messages = [] + if mode is cls.ARGS_REMAP and not args_mapping: + messages.append( + f"`@deprecated(target=TargetMode.ARGS_REMAP)` on `{source_name}` requires " + "`args_mapping` to specify which arguments are being renamed. Without it the " + "decorator has zero effect. This will be `TypeError` in `v1.0`." + ) + if mode is cls.NOTIFY and args_mapping: + messages.append( + f"`@deprecated(target=TargetMode.NOTIFY)` on `{source_name}` ignores " + "`args_mapping`. Use `TargetMode.ARGS_REMAP` to rename arguments, or pass a " + "callable target to forward the call. This will be `TypeError` in `v1.0`." + ) + if mode is cls.NOTIFY and args_extra: + messages.append( + f"`@deprecated(target=TargetMode.NOTIFY)` on `{source_name}` ignores " + "`args_extra`. Use a callable target to forward with extra arguments. " + "This will be `TypeError` in `v1.0`." + ) + if stacklevel is not None: + for msg in messages: + warnings.warn(msg, UserWarning, stacklevel=stacklevel) + return bool(messages) + + @classmethod + def _validate_proxy( + cls, + mode: "Union[TargetMode, Callable[..., Any], None]", + source_name: str, + attrs_mapping: Optional[Mapping[str, Optional[str]]] = None, + args_mapping: Optional[Mapping[str, Optional[str]]] = None, + args_extra: Optional[dict[str, Any]] = None, + *, + stacklevel: Optional[int] = 2, + ) -> bool: + """Validate proxy-specific configuration: ``attrs_mapping`` combinations. + + Catches misconfiguration pairs involving ``attrs_mapping`` that the existing + :meth:`~deprecate._types.TargetMode._validate` does not cover (it handles only ``args_mapping`` / + ``args_extra`` and is used by the function-decorator path as well). + + Misconfiguration warnings will become :class:`TypeError` in ``v1.0``. + + Args: + mode: Resolved target (:class:`~deprecate._types.TargetMode` member, callable, or ``None``). + source_name: ``__name__`` of the decorated class, for warning messages. + attrs_mapping: The ``attrs_mapping`` dict passed to :func:`~deprecate.proxy.deprecated_class`, or + ``None``. + args_mapping: The ``args_mapping`` dict, forwarded here so we can detect the + ``ATTRS_REMAP + args_mapping`` combination. + args_extra: The ``args_extra`` dict, forwarded here so we can detect the + ``ATTRS_REMAP + args_extra`` combination — ``ATTRS_REMAP`` governs attribute access only and + does not honour call-time kwarg injection. + stacklevel: Forwarded to :func:`warnings.warn`. Pass ``None`` to suppress warnings. Defaults to ``2``. + + Returns: + ``True`` if any misconfiguration was detected, ``False`` otherwise. + + Examples: + >>> TargetMode._validate_proxy(TargetMode.NOTIFY, "Cls", attrs_mapping={"a": "b"}, stacklevel=None) + True + >>> TargetMode._validate_proxy(TargetMode.ATTRS_REMAP, "Cls", attrs_mapping=None, stacklevel=None) + True + >>> TargetMode._validate_proxy(TargetMode.ATTRS_REMAP, "Cls", attrs_mapping={}, stacklevel=None) + True + >>> TargetMode._validate_proxy(TargetMode.ATTRS_REMAP, "Cls", attrs_mapping={"a": "b"}, stacklevel=None) + False + >>> TargetMode._validate_proxy( + ... TargetMode.ARGS_REMAP, "Cls", + ... args_mapping={"old": "new"}, attrs_mapping={"a": "b"}, stacklevel=None, + ... ) + True + >>> TargetMode._validate_proxy( + ... TargetMode.ATTRS_REMAP, "Cls", + ... args_mapping={"old": "new"}, attrs_mapping={"a": "b"}, stacklevel=None, + ... ) + True + >>> TargetMode._validate_proxy( + ... TargetMode.ATTRS_REMAP, "Cls", + ... attrs_mapping={"a": "b"}, args_extra={"bias": 1}, stacklevel=None, + ... ) + True + + """ + messages = [] + if mode is cls.NOTIFY and attrs_mapping: + messages.append( + f"`deprecated_class(target=TargetMode.NOTIFY)` on `{source_name}` ignores " + "`attrs_mapping`. Drop one of them: `attrs_mapping` switches to selective per-attribute " + "warning, which contradicts NOTIFY's warn-on-every-access semantics. " + "This will be `TypeError` in `v1.0`." + ) + if mode is cls.ARGS_REMAP and args_mapping and attrs_mapping: + messages.append( + f"`deprecated_class` on `{source_name}` has both `args_mapping` and `attrs_mapping` " + "configured with `target=TargetMode.ARGS_REMAP`. `ARGS_REMAP` governs call-time argument " + "renames only; `attrs_mapping` is inactive in this mode. " + "`DeprecationConfig.target` no longer reflects that `attrs_mapping` is also active. " + "Pass an explicit callable `target=` to activate both mappings on the same proxy. " + "This will be `TypeError` in `v1.0`." + ) + if mode is cls.ATTRS_REMAP and not attrs_mapping: + messages.append( + f"`deprecated_class(target=TargetMode.ATTRS_REMAP)` on `{source_name}` requires " + "`attrs_mapping` to specify which attribute names are deprecated. Without it the " + "proxy has zero selective effect. This will be `TypeError` in `v1.0`." + ) + if mode is cls.ATTRS_REMAP and args_mapping: + messages.append( + f"`deprecated_class(target=TargetMode.ATTRS_REMAP)` on `{source_name}` ignores `args_mapping`. " + "`ATTRS_REMAP` only governs attribute access; argument renames on `__call__` are not applied. " + "Use `target=` (with both mappings) or `TargetMode.ARGS_REMAP` (with `args_mapping` only). " + "This will be `TypeError` in `v1.0`." + ) + if mode is cls.ATTRS_REMAP and args_extra: + messages.append( + f"`deprecated_class(target=TargetMode.ATTRS_REMAP)` on `{source_name}` ignores `args_extra`. " + "`ATTRS_REMAP` only governs attribute access; call-time kwarg injection is not applied. " + "Use `target=` to forward calls with extra arguments. " + "This will be `TypeError` in `v1.0`." + ) + if attrs_mapping is not None and len(attrs_mapping) == 0: + messages.append( + f"`deprecated_class` on `{source_name}` received `attrs_mapping={{}}` (empty dict). " + "An empty mapping has no effect — remove it or add deprecated attribute names. " + "This will be `TypeError` in `v1.0`." + ) + if stacklevel is not None: + for msg in messages: + warnings.warn(msg, UserWarning, stacklevel=stacklevel) + return bool(messages) + + +@dataclass(frozen=True) +class DeprecationConfig: + """Static deprecation metadata attached to deprecated callables as ``__deprecated__``. + + All fields are always set — both :func:`~deprecate.deprecated`-decorated functions and + :class:`~deprecate.proxy._DeprecatedProxy` objects use this unified schema. + + Attributes: + deprecated_in: Version string when the callable was deprecated. + remove_in: Version string when the callable will be removed. + name: Display the name of the deprecated source (function or class name). + target: Normalised target — ``None`` (default), :attr:`~deprecate._types.TargetMode.NOTIFY`, + :attr:`~deprecate._types.TargetMode.ARGS_REMAP`, :attr:`~deprecate._types.TargetMode.ATTRS_REMAP`, + or a callable. Legacy sentinels (``True``/``False``) are normalised at decoration time and never + stored verbatim. + args_extra: Optional kwargs injected into forwarded calls; stored for audit visibility. + misconfigured: ``True`` when an invalid raw target sentinel (``False``) was passed at decoration time. + Audit tools surface this via + :attr:`~deprecate.audit.DeprecationWrapperInfo.misconfigured_target`. + docstring_style: Docstring notice output style when ``update_docstring=True``. + template_mgs: Optional custom warning-message template (``%``-style placeholders) that overrides the built-in + templates at warn time. ``None`` (default) keeps the built-in template selected for the active scenario. + Audit tools may surface this for introspection. See :func:`~deprecate.deprecation.deprecated` for the + available placeholders (e.g. ``%(source_name)s``, ``%(target_path)s``, ``%(deprecated_in)s``). + attrs_mapping: Optional mapping of deprecated attribute names to their canonical replacement names (or + ``None`` for warn-only). Set by :func:`~deprecate.proxy.deprecated_class` when + selective per-attribute deprecation is enabled. Non-``None`` redirect targets must be existing attribute + names on the target class when ``target`` is provided, or on the wrapped source class otherwise. + Non-cyclic chains are stored and surfaced by audit tooling. ``None`` (default) means the proxy uses its + blanket-warning behaviour (every attribute access emits a warning). + args_mapping: Optional dict remapping argument names; values are a plain string (new argument name) or + ``None`` (drop the argument). + args_mapping_auto_expanded: Keys that were automatically copied from ``attrs_mapping`` into + ``args_mapping`` by the dataclass dual-surface expansion in + :class:`~deprecate.proxy._DeprecatedProxy`. Empty tuple when no auto-expansion occurred. + Populated at decoration time; read by audit tools to distinguish user-supplied mappings from + auto-generated ones. + args_mapping_positional_only: ``args_mapping`` old-key names whose remapped target name is a + POSITIONAL_ONLY parameter in the target class constructor. Calling the proxy with such + keys as keyword arguments would raise ``TypeError`` without the positional split applied + by the proxy call path (see :attr:`target_positional_only`). Empty tuple when all + remapped targets are kwarg-accessible. Populated at decoration time; surfaced by + :func:`~deprecate.audit.validate_mapping_compatibility`. + target_positional_only: Names of POSITIONAL_ONLY parameters on the forwarding target callable + used with :func:`~deprecate.deprecated`, including ``self`` and ``cls`` when they are + declared positional-only. Non-empty when a ``@deprecated(target=fn)`` call found ``fn`` + declares at least one positional-only parameter. ``self`` and ``cls`` are excluded from + the :class:`UserWarning` message but included here so the split-dispatch gate fires even + when the only positional-only parameter is the instance or class receiver (e.g. + ``def __init__(self, /): ...``). The call dispatcher splits these out of + ``resolved_kwargs`` and forwards them positionally so the target call does not raise + ``TypeError``. For :class:`~deprecate.proxy._DeprecatedProxy` objects this holds the + POSITIONAL_ONLY parameter names of the *active* class constructor (target class when + configured, wrapped class otherwise) so the proxy call path can apply the same + positional split (see also :attr:`args_mapping_positional_only`). Empty frozenset + for non-callable targets. + target_positional_only_order: Full parameter-name sequence of the forwarding target callable, + in declaration order. Pre-computed at decoration time alongside + :attr:`target_positional_only` so the call dispatcher can iterate in declaration order + without calling ``inspect.signature`` on every dispatch. Not included in ``repr``. + Empty tuple when ``target_positional_only`` is empty. + source_positional_only: Names of POSITIONAL_ONLY parameters declared by the decorated + *source* callable itself. The wrapper converts positional args to kwargs internally, + so whenever the dispatcher invokes the source body (NOTIFY, ARGS_REMAP, and the + migrated-caller short-circuit) it must split these names back out of the resolved + kwargs and pass them positionally — otherwise every call would raise ``TypeError``. + Mirrors :attr:`target_positional_only` on the source side. Empty frozenset when the + source declares no ``/``. + source_positional_only_order: Full parameter-name sequence of the decorated source in + declaration order; the source-side twin of :attr:`target_positional_only_order`. + Not included in ``repr``. Empty tuple when :attr:`source_positional_only` is empty. + source_var_positional_prefix: Number of named positional parameters declared before the + source's ``*args``. Used by the forwarding dispatcher to compute the surplus + positional tail (``args[prefix:]``) that must be forwarded to a callable target + rather than silently dropped. ``0`` when the source declares no var-positional + parameter. + target_all_param_names: All parameter names of the forwarding target callable (including any + ``*args`` / ``**kwargs`` names), pre-computed at decoration time so the call-time kwarg + validation in :func:`~deprecate.deprecation._prepare_target_call` does not re-inspect the + target on every forwarded call. ``None`` when facts are not precomputed (manual + ``DeprecationConfig`` construction or non-callable target); ``frozenset()`` for zero-arg + callables. Internal call-time cache — excluded from ``repr`` and equality so audit output + and stored-config comparisons stay stable. + target_accepts_var_positional: ``True`` when the forwarding target declares ``*args``. Pre-computed + decoration-time replacement for the per-call ``inspect.getfullargspec`` probe. Internal cache — + excluded from ``repr`` and equality. + target_accepts_var_keyword: ``True`` when the forwarding target declares ``**kwargs``. Pre-computed + decoration-time replacement for the per-call ``inspect.getfullargspec`` probe. Internal cache — + excluded from ``repr`` and equality. + + Note: + ``@dataclass(frozen=True)`` blocks attribute *rebinding* on the config object itself, but the + stored ``args_mapping`` and ``attrs_mapping`` dicts remain mutable. Code that reads these fields + must not modify them in place; the decorator copies them defensively at decoration time. + + """ + + deprecated_in: str = "" + remove_in: str = "" + name: str = "" + target: Optional[Union[Callable[..., Any], "TargetMode"]] = None + args_mapping: Optional[dict[str, Optional[str]]] = None + args_extra: Optional[dict[str, Any]] = None + misconfigured: bool = False + docstring_style: Literal["rst", "mkdocs"] = "rst" + template_mgs: Optional[str] = None + attrs_mapping: Optional[dict[str, Optional[str]]] = None + args_mapping_auto_expanded: tuple[str, ...] = field(default_factory=tuple) + args_mapping_positional_only: tuple[str, ...] = field(default_factory=tuple) + target_positional_only: frozenset[str] = field(default_factory=frozenset) + target_positional_only_order: tuple[str, ...] = field(default_factory=tuple, repr=False) + source_positional_only: frozenset[str] = field(default_factory=frozenset) + source_positional_only_order: tuple[str, ...] = field(default_factory=tuple, repr=False) + source_var_positional_prefix: int = 0 + target_all_param_names: Optional[frozenset[str]] = field(default=None, repr=False, compare=False) + target_accepts_var_positional: bool = field(default=False, repr=False, compare=False) + target_accepts_var_keyword: bool = field(default=False, repr=False, compare=False) + + +@runtime_checkable +class _HasDeprecationMeta(Protocol): + """Structural type for any callable that carries ``__deprecated__`` metadata. + + Both ``@deprecated``-decorated functions and :class:`~deprecate.proxy._DeprecatedProxy` instances satisfy this + protocol once the decorator has been applied. + + Used as a TypeGuard target so that a ``hasattr`` guard narrows the type of an arbitrary callable to one whose + ``__deprecated__`` attribute is typed — eliminating the need for a ``cast`` after the guard. + + """ + + __deprecated__: DeprecationConfig + __name__: str + + def __call__(self, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + """Call the deprecated object.""" + raise NotImplementedError + + +def _has_deprecation_meta(obj: Any) -> "TypeGuard[_HasDeprecationMeta]": # noqa: ANN401 + """Return ``True`` if *obj* carries typed :class:`~deprecate._types.DeprecationConfig` metadata. + + Using this as a guard narrows the type of *obj* from ``Any`` / ``Callable`` to + :class:`~deprecate._types._HasDeprecationMeta`, + allowing direct typed access to ``obj.__deprecated__`` without a ``cast``. + + Args: + obj: Any object to test. + + Returns: + ``True`` if ``__deprecated__`` exists and is a :class:`~deprecate._types.DeprecationConfig`; + ``False`` otherwise. + + """ + # ``getattr(..., default)`` only swallows ``AttributeError``; a foreign object encountered during a + # recursive audit scan whose ``__getattr__``/``__getattribute__`` raises something else (e.g. a lazy + # proxy raising ``RuntimeError``) would otherwise crash the whole scan. Treat any failure as "no meta". + try: + meta = getattr(obj, "__deprecated__", None) + except Exception: + return False + return isinstance(meta, DeprecationConfig) + + +@dataclass +class _ProxyConfig: + """Private mutable runtime state for :class:`~deprecate.proxy._DeprecatedProxy`. + + This is an internal type — not exported from the package and not referenced outside of :mod:`deprecate.proxy`. + + Attributes: + obj: The wrapped (source) object. + stream: Callable used to emit warnings, or ``None`` to suppress them. + num_warns: Maximum number of warnings to emit; ``-1`` means unlimited. + read_only: When ``True``, write operations through the proxy raise :class:`AttributeError`. + args_extra: Optional dict of extra keyword arguments merged into forwarded calls after ``args_mapping`` has + been applied. Ignored when the proxy is in :attr:`~deprecate._types.TargetMode.NOTIFY` mode. + template_mgs: Optional custom warning-message template (``%``-style placeholders) that overrides the built-in + templates at warn time. ``None`` (default) keeps the built-in templates. See + :func:`~deprecate.proxy.deprecated_class` for the placeholder catalogue. + attrs_mapping: Optional mapping of deprecated attribute names to their canonical replacement names (or + ``None`` for warn-only). When set, the proxy emits warnings only on access to listed names and forwards + all other reads/writes/deletes silently. See :func:`~deprecate.proxy.deprecated_class` for full semantics. + warned: Mutable counter tracking how many global (callable-level) warnings have been emitted so far. + warned_args: Per-argument warning counts for argument-level deprecations. Keys are deprecated argument names; + values are emission counts. + lock: Guards the warn-quota check-then-act sequence (read counter → decide to emit → increment) so that + concurrent first accesses cannot all pass the ``num_warns`` gate and each emit a warning. Excluded from + ``repr`` and equality — it is runtime machinery, not state identity. A fresh lock is created on copy / + deepcopy rather than transferring the original mutex state. + + """ + + obj: Any + stream: Optional[Callable[..., None]] + num_warns: int + read_only: bool + args_extra: Optional[dict[str, Any]] = None + template_mgs: Optional[str] = None + attrs_mapping: Optional[dict[str, Optional[str]]] = None + warned: int = 0 + warned_args: dict[str, int] = field(default_factory=dict) + lock: threading.Lock = field(default_factory=threading.Lock, repr=False, compare=False) + + def __deepcopy__(self, memo: dict[int, Any]) -> "_ProxyConfig": + return replace( + self, + obj=copy.deepcopy(self.obj, memo), + warned_args=copy.deepcopy(self.warned_args, memo), + lock=threading.Lock(), # fresh lock — mutex state is not transferable + ) + + def __getstate__(self) -> dict[str, Any]: + return {k: v for k, v in self.__dict__.items() if k != "lock"} + + def __setstate__(self, state: dict[str, Any]) -> None: + self.__dict__.update(state) + self.lock = threading.Lock() # fresh lock — mutex state is not transferable + + +@dataclass +class _WrapperState: + """Private mutable runtime state for ``@deprecated``-decorated callables. + + This is an internal type — not exported from the package and not referenced outside of :mod:`deprecate.deprecation`. + + Attributes: + called: Total invocation count, including calls where the warning was suppressed. + warned_calls: Number of callable-level deprecation warnings emitted so far. + warned_args: Per-argument warning counts for argument-level deprecations. Keys are deprecated argument names; + values are emission counts. + warned_misconfigured: ``True`` after the one-time misconfiguration UserWarning has been emitted at call time. + lock: Guards the warn-quota check-then-act sequence (read counter → decide to emit → increment) so that + concurrent first calls cannot all pass the ``num_warns`` gate and each emit a warning. Only the warn + path takes this lock; the ``called`` counter is a best-effort diagnostic and stays lock-free. Excluded + from ``repr`` and equality — it is runtime machinery, not state identity. + + """ + + called: int = 0 + warned_calls: int = 0 + warned_args: dict[str, int] = field(default_factory=dict) + warned_misconfigured: bool = False + lock: threading.Lock = field(default_factory=threading.Lock, repr=False, compare=False) + + +@runtime_checkable +class _DeprecatedCallable(Protocol): + """Structural type for a ``@deprecated``-decorated callable with mutable runtime state. + + This protocol describes the shape of a function or method after the ``@deprecated`` decorator has been applied. It + includes both static metadata (``__deprecated__``) and mutable runtime state (``_state``). + + Used to type-safely access ``_state`` on decorated callables without casting. + + """ + + __deprecated__: DeprecationConfig + _state: _WrapperState + + def __call__(self, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + """Call the deprecated callable.""" + raise NotImplementedError + + +@dataclass +class _CallPlan: + """Resolved dispatch plan returned by :func:`deprecate.deprecation._build_call_plan`. + + Captures the outcome of all decision-making shared between the sync and async wrappers in :func:`deprecated`: state + mutation, kwargs assembly, warning emission, target resolution. The wrapper consumes this struct to decide whether + to invoke ``source`` or a forwarded target callable, and with which kwargs shape. + + Attributes: + short_circuit: ``True`` when the wrapper must call ``source`` directly (no warning, no remap, no target + lookup) — this is the "migrated caller using the new arg name" fast path before any warning logic runs. + The wrapper calls ``source(**resolved_kwargs)`` for sources without ``*args``, or + ``source(*args, **original_kwargs)`` when the source declares a var-positional parameter so that + extra positional arguments are forwarded correctly. When ``True``, :attr:`resolved_kwargs` equals the + kwargs after :func:`_update_kwargs_with_args`, before defaults / remap / extras are applied. + original_kwargs: A shallow copy of the wrapper's incoming ``kwargs`` (before positional args were converted to + keyword form). Used by the var-positional branch when no argument-rename reason fired, so that the source + sees its original positional/keyword shape. + resolved_kwargs: Final kwargs after defaults injection, ``args_mapping`` remap, and ``args_extra`` merge when + the normal planning path runs. On the :attr:`short_circuit` path, this instead holds the kwargs produced + immediately after :func:`_update_kwargs_with_args`, and that is what the wrapper passes to ``source``. + reason_argument: Subset of ``args_mapping`` whose old-arg names appeared in the caller's kwargs. Non-empty + value means the argument-rename warning fired (or was suppressed by ``num_warns`` quota). Empty when the + warning reason was callable-deprecation or when no rename was triggered. + target_func: Resolved target callable when forwarding is required, or ``None`` when the source body should be + invoked instead. ``None`` for :attr:`TargetMode.NOTIFY` and :attr:`TargetMode.ARGS_REMAP`; a validated + callable when the user passed a forwarding target. + + """ + + short_circuit: bool + original_kwargs: dict[str, Any] + resolved_kwargs: dict[str, Any] + reason_argument: dict[str, Optional[str]] = field(default_factory=dict) + target_func: Optional[Callable[..., Any]] = None diff --git a/.venv/lib/python3.12/site-packages/deprecate/audit.py b/.venv/lib/python3.12/site-packages/deprecate/audit.py new file mode 100644 index 0000000000000000000000000000000000000000..cfebcdb0fc5c09fe9e68c8cc7eb1ba03b51e668d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/deprecate/audit.py @@ -0,0 +1,1537 @@ +"""Audit tools for deprecation lifecycle management. + +This module provides several complementary utilities for verifying the health of deprecated callables across a +codebase. All are designed to be called from pytest or a CI script against an imported package. + +**Wrapper configuration** (:func:`~deprecate.audit.validate_deprecation_wrapper`, +:func:`~deprecate.audit.find_deprecation_wrappers`): + Detect wrappers that have zero impact — invalid ``args_mapping`` keys, identity mappings, empty mappings, or a + ``target`` pointing back to the same wrapper. + +**Mapping compatibility** (:func:`~deprecate.audit.validate_mapping_compatibility`): + Detect :func:`~deprecate.proxy.deprecated_class` wrappers whose ``args_mapping`` remaps to POSITIONAL_ONLY + constructor params, silently degrading to ``setattr`` at call time. + +**Expiry enforcement** (:func:`~deprecate.audit.validate_deprecation_expiry`): + Detect wrappers whose ``remove_in`` version has been reached or passed, preventing zombie code from shipping past + its scheduled removal deadline. + +**Chain detection** (:func:`~deprecate.audit.validate_deprecation_chains`): + Detect wrappers whose ``target`` is itself a deprecated callable, forming a chain that users traverse + unnecessarily. Two chain kinds are reported via :class:`~deprecate.audit.ChainType`: ``TARGET`` (forwarding chain) + and ``STACKED`` (composed argument or attribute mappings). + +**Report generation** (:func:`~deprecate.audit.generate_deprecation_table`): + Generate a docs-friendly markdown summary from wrapper metadata. + +Results are returned as :class:`~deprecate.audit.DeprecationWrapperInfo` dataclasses, which carry both +identification info and structured validation results for programmatic processing. + +!!! note + :func:`~deprecate.audit.validate_deprecation_expiry` requires the ``packaging`` library for PEP 440 + version comparison. Install with: ``pip install pyDeprecate[audit]`` + +Copyright (C) 2020-2026 Jiri Borovec <6035284+Borda@users.noreply.github.com> + +""" + +# Note: Proxy objects are discoverable via the generic ``callable(obj)`` + +# ``hasattr(obj, "__deprecated__")`` scan in :func:`find_deprecation_wrappers` and +# :func:`validate_deprecation_expiry`. The ``__deprecated__`` schema is now unified +# across ``@deprecated`` and :class:`~deprecate.proxy._DeprecatedProxy` via +# :class:`~deprecate._types.DeprecationConfig` — both always populate the ``name`` field, +# so ``validate_deprecation_wrapper`` can read it correctly for proxy objects too. + +import enum +import importlib +import importlib.metadata +import inspect +import pkgutil +import re +import warnings +from contextlib import suppress +from dataclasses import dataclass, field, is_dataclass, replace +from enum import Enum +from functools import cached_property, wraps +from typing import TYPE_CHECKING, Any, Callable, Optional, Union + +if TYPE_CHECKING: + from packaging.version import Version + +from deprecate._types import DeprecationConfig, TargetMode, _has_deprecation_meta +from deprecate.deprecation import _DeprecatedProperty +from deprecate.proxy import _DeprecatedProxy, deprecated_class +from deprecate.utils import get_func_arguments_types_defaults + + +class TableStyle(str, enum.Enum): + """Markdown table layout produced by :func:`~deprecate.audit.generate_deprecation_table`.""" + + COMPACT = "compact" + MATRIX = "matrix" + + +class DeprecationStatus(str, enum.Enum): + """Lifecycle status labels used in the deprecation report's *Current Status* column. + + Each member's value is the full display string (emoji + text) rendered in the table. + Using a ``str`` enum means members compare equal to their string values and can be + returned wherever a plain string is expected. + + Members are *declared* from least to most urgent for readability, but this enum is **not orderable by + urgency**: because each value starts with an emoji, the inherited ``str`` ordering operators (``<``, ``>``) + compare Unicode codepoints of those emoji, not deprecation urgency. Do not rely on ``status_a > status_b`` + to mean "more urgent" — compare members explicitly (``status is DeprecationStatus.PAST_REMOVAL_DATE``). + The ordering operators are overridden to raise ``TypeError`` so accidental comparisons fail loudly. + + Examples: + >>> DeprecationStatus.ACTIVE_WARNING.value + '📢 Deprecation Active' + >>> DeprecationStatus.PAST_REMOVAL_DATE is DeprecationStatus.PAST_REMOVAL_DATE + True + + """ + + SCHEDULED_DEPRECATION = "🕒 Scheduled Deprecation" # current < deprecated_in + NO_REMOVAL_TARGET = "ℹ️ No Removal Target" # remove_in not set + STATUS_UNKNOWN = "⚪ Status Unknown" # current_version unavailable + INVALID_REMOVAL_TARGET = "⚪ Invalid Removal Target" # remove_in unparsable + ACTIVE_WARNING = "📢 Deprecation Active" # current < remove_in (different base) + REMOVAL_IMMINENT = "⏰ Removal Imminent" # pre-release dev/a/b of remove_in base + REMOVE_BEFORE_RELEASE = "🔔 Remove Before Release" # RC of the remove_in base release + PAST_REMOVAL_DATE = "💥 Past Removal Date" # current >= remove_in + + def __lt__(self, other: object) -> bool: + """Raise TypeError — urgency ordering is not meaningful for emoji-valued status labels.""" + raise TypeError("'<' not supported between instances of 'DeprecationStatus' — compare by identity") + + def __le__(self, other: object) -> bool: + """Raise TypeError — urgency ordering is not meaningful for emoji-valued status labels.""" + raise TypeError("'<=' not supported between instances of 'DeprecationStatus' — compare by identity") + + def __gt__(self, other: object) -> bool: + """Raise TypeError — urgency ordering is not meaningful for emoji-valued status labels.""" + raise TypeError("'>' not supported between instances of 'DeprecationStatus' — compare by identity") + + def __ge__(self, other: object) -> bool: + """Raise TypeError — urgency ordering is not meaningful for emoji-valued status labels.""" + raise TypeError("'>=' not supported between instances of 'DeprecationStatus' — compare by identity") + + +def _normalize_version_string(version: str) -> str: + """Normalize non-standard version strings before PEP 440 parsing. + + Newer ``packaging`` (>=22) is strict PEP 440 and rejects real-world strings that omit trailing digits + on pre/post/dev release labels (e.g. ``"1.8.0.dev"``, ``"1.8.0dev"``, ``"1.8.0.post"``). This helper + performs the minimum normalization needed to make such strings parseable, then defers everything else + (label aliasing like ``alpha`` -> ``a``, case folding, separator handling) to ``packaging.Version``. + + The transformation is conservative: + + 1. Strip a single leading ``v`` or ``V`` prefix (left-anchored, so only one leading ``v`` is removed). + 2. Append ``0`` to bare pre/post/dev labels that lack a trailing digit. Labels recognized: + ``dev``, ``rc``, ``a``, ``b``, ``c``, ``alpha``, ``beta``, ``preview``, ``post``. + + The label normalization runs only over the *public* part of the version — any PEP 440 local segment + (everything after ``+``) is split off first and re-attached verbatim, so a legitimate local like + ``1.2.3+cuda`` is never mangled into ``1.2.3+cuda0`` by the trailing-``a`` label rule. + + No other transformations are applied — case, separators, and label aliases pass through unchanged + so ``packaging.Version`` can apply its own canonicalization. + + Args: + version: Raw version string, possibly missing trailing digits on labels. + + Returns: + Normalized version string ready to be passed to ``packaging.version.Version``. + + Examples: + >>> _normalize_version_string("1.8.0.dev") + '1.8.0.dev0' + >>> _normalize_version_string("1.8.0dev") + '1.8.0dev0' + >>> _normalize_version_string("1.8.0.post") + '1.8.0.post0' + >>> _normalize_version_string("v1.2.3") + '1.2.3' + >>> _normalize_version_string("1.8.0.RC1") + '1.8.0.RC1' + >>> _normalize_version_string("1.2.3") + '1.2.3' + >>> _normalize_version_string("1.2.3+cuda") + '1.2.3+cuda' + >>> _normalize_version_string("v1.8.0.dev+local.a") + '1.8.0.dev0+local.a' + + """ + # Split off any PEP 440 local segment (after ``+``) so the label regex never touches it; labels like + # ``post``/``dev`` never appear in a local segment, and running the rule over it mangles legit locals. + public, plus, local = version.partition("+") + # Strip a single left-anchored leading ``v``/``V`` (``lstrip("vV")`` would strip *all* leading v's). + normalized = re.sub(r"^[vV]", "", public) + # Append ``0`` to bare pre/post/dev labels with no trailing digit. The ordering of the alternatives + # matters: longer labels (``alpha``, ``beta``, ``preview``) must come before their single-letter + # forms (``a``, ``b``) so the regex prefers the longer match. + # Use a negative lookahead for ``[0-9]`` to detect "no trailing digit"; ``(?=$|[^A-Za-z0-9])`` + # ensures the label is a whole token (e.g. ``dev`` but not ``develop``). + pattern = re.compile( + r"(?P\.?)(?P