Skip to content

Commit

Permalink
Add TCH/T10/FA lints and sync conda.deprecations (#5178)
Browse files Browse the repository at this point in the history
  • Loading branch information
kenodegard authored Feb 12, 2024
1 parent ec50bdf commit 46dfcf8
Show file tree
Hide file tree
Showing 33 changed files with 230 additions and 80 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ ci:
# ignore patches/diffs since slight reformatting can break them
exclude: |
(?x)^(
conda_build/version.py |
tests/(
archives |
index_data |
Expand Down Expand Up @@ -47,7 +48,6 @@ repos:
- id: insert-license
files: \.py$
args: [--license-filepath, .github/disclaimer.txt, --no-extra-eol]
exclude: ^conda_build/version.py
- repo: https://github.com/asottile/blacken-docs
rev: 1.16.0
hooks:
Expand Down
16 changes: 8 additions & 8 deletions conda_build/cli/main_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,17 @@
import logging
import sys
import warnings
from argparse import Namespace
from glob import glob
from itertools import chain
from os.path import abspath, expanduser, expandvars
from pathlib import Path
from typing import Sequence
from typing import TYPE_CHECKING

from conda.auxlib.ish import dals
from conda.common.io import dashlist

from .. import api, build, source, utils
from ..conda_interface import (
ArgumentParser,
add_parser_channels,
binstar_upload,
cc_conda_build,
)
from ..conda_interface import add_parser_channels, binstar_upload, cc_conda_build
from ..config import (
get_channel_urls,
get_or_merge_config,
Expand All @@ -32,6 +26,12 @@
from .actions import KeyValueAction
from .main_render import get_render_parser

if TYPE_CHECKING:
from argparse import Namespace
from typing import Sequence

from ..conda_interface import ArgumentParser


def parse_args(args: Sequence[str] | None) -> tuple[ArgumentParser, Namespace]:
parser = get_render_parser()
Expand Down
7 changes: 5 additions & 2 deletions conda_build/cli/main_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
from __future__ import annotations

import logging
from argparse import Namespace
from os.path import abspath, expanduser
from typing import Sequence
from typing import TYPE_CHECKING

from .. import api
from ..conda_interface import ArgumentParser

if TYPE_CHECKING:
from argparse import Namespace
from typing import Sequence

logging.basicConfig(level=logging.INFO)

epilog = """
Expand Down
7 changes: 5 additions & 2 deletions conda_build/cli/main_debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@

import logging
import sys
from argparse import ArgumentParser
from typing import Sequence
from typing import TYPE_CHECKING

from .. import api
from ..utils import on_win
from . import validators as valid
from .main_render import get_render_parser

if TYPE_CHECKING:
from argparse import ArgumentParser
from typing import Sequence

logging.basicConfig(level=logging.INFO)


Expand Down
7 changes: 5 additions & 2 deletions conda_build/cli/main_develop.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@
from __future__ import annotations

import logging
from argparse import Namespace
from typing import Sequence
from typing import TYPE_CHECKING

from conda.base.context import context, determine_target_prefix

from .. import api
from ..conda_interface import ArgumentParser, add_parser_prefix

if TYPE_CHECKING:
from argparse import Namespace
from typing import Sequence

logging.basicConfig(level=logging.INFO)


Expand Down
7 changes: 5 additions & 2 deletions conda_build/cli/main_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,19 @@

import logging
import sys
from argparse import Namespace
from os.path import expanduser
from pprint import pprint
from typing import Sequence
from typing import TYPE_CHECKING

from conda.base.context import context, determine_target_prefix

from .. import api
from ..conda_interface import ArgumentParser, add_parser_prefix

if TYPE_CHECKING:
from argparse import Namespace
from typing import Sequence

logging.basicConfig(level=logging.INFO)


Expand Down
7 changes: 5 additions & 2 deletions conda_build/cli/main_metapackage.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@

import argparse
import logging
from argparse import Namespace
from typing import Sequence
from typing import TYPE_CHECKING

from .. import api
from ..conda_interface import ArgumentParser, add_parser_channels, binstar_upload

if TYPE_CHECKING:
from argparse import Namespace
from typing import Sequence

logging.basicConfig(level=logging.INFO)


Expand Down
7 changes: 5 additions & 2 deletions conda_build/cli/main_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@

import argparse
import logging
from argparse import Namespace
from pprint import pprint
from typing import Sequence
from typing import TYPE_CHECKING

import yaml
from yaml.parser import ParserError
Expand All @@ -18,6 +17,10 @@
from ..utils import LoggingContext
from ..variants import get_package_variants, set_language_env_vars

if TYPE_CHECKING:
from argparse import Namespace
from typing import Sequence

log = logging.getLogger(__name__)


Expand Down
7 changes: 5 additions & 2 deletions conda_build/cli/main_skeleton.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@
import os
import pkgutil
import sys
from argparse import Namespace
from typing import Sequence
from typing import TYPE_CHECKING

from .. import api
from ..conda_interface import ArgumentParser
from ..config import Config

if TYPE_CHECKING:
from argparse import Namespace
from typing import Sequence

thisdir = os.path.dirname(os.path.abspath(__file__))
logging.basicConfig(level=logging.INFO)

Expand Down
5 changes: 4 additions & 1 deletion conda_build/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import time
from collections import namedtuple
from os.path import abspath, expanduser, expandvars, join
from pathlib import Path
from typing import TYPE_CHECKING

from .conda_interface import (
binstar_upload,
Expand All @@ -33,6 +33,9 @@
)
from .variants import get_default_variant

if TYPE_CHECKING:
from pathlib import Path

invocation_time = ""


Expand Down
5 changes: 4 additions & 1 deletion conda_build/create_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@
import os
from os.path import basename, exists, isfile, join
from pathlib import Path
from typing import TYPE_CHECKING

from .metadata import MetaData
from .utils import copy_into, ensure_list, on_win, rm_rf

if TYPE_CHECKING:
from .metadata import MetaData


def create_files(m: MetaData, test_dir: Path) -> bool:
"""
Expand Down
88 changes: 70 additions & 18 deletions conda_build/deprecations.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@

import sys
import warnings
from argparse import Action
from functools import wraps
from types import ModuleType
from typing import Any, Callable
from typing import TYPE_CHECKING

from packaging.version import Version, parse
if TYPE_CHECKING:
from argparse import Action
from typing import Any, Callable

from packaging.version import Version

from . import __version__

Expand All @@ -22,17 +25,52 @@ class DeprecatedError(RuntimeError):
# inspired by deprecation (https://deprecation.readthedocs.io/en/latest/) and
# CPython's warnings._deprecated
class DeprecationHandler:
_version: Version
_version: str | None
_version_tuple: tuple[int, ...] | None
_version_object: Version | None

def __init__(self, version: Version | str):
def __init__(self, version: str):
"""Factory to create a deprecation handle for the specified version.
:param version: The version to compare against when checking deprecation statuses.
"""
self._version = version
# Try to parse the version string as a simple tuple[int, ...] to avoid
# packaging.version import and costlier version comparisons.
self._version_tuple = self._get_version_tuple(version)
self._version_object = None

@staticmethod
def _get_version_tuple(version: str) -> tuple[int, ...] | None:
"""Return version as non-empty tuple of ints if possible, else None.
:param version: Version string to parse.
"""
try:
self._version = parse(version)
except TypeError:
self._version = parse("0.0.0.dev0+placeholder")
return tuple(int(part) for part in version.strip().split(".")) or None
except (AttributeError, ValueError):
return None

def _version_less_than(self, version: str) -> bool:
"""Test whether own version is less than the given version.
:param version: Version string to compare against.
"""
if self._version_tuple:
if version_tuple := self._get_version_tuple(version):
return self._version_tuple < version_tuple

# If self._version or version could not be represented by a simple
# tuple[int, ...], do a more elaborate version parsing and comparison.
# Avoid this import otherwise to reduce import time for conda activate.
from packaging.version import parse

if self._version_object is None:
try:
self._version_object = parse(self._version)
except TypeError:
self._version_object = parse("0.0.0.dev0+placeholder")
return self._version_object < parse(version)

def __call__(
self,
Expand Down Expand Up @@ -281,16 +319,33 @@ def _get_module(self, stack: int) -> tuple[ModuleType, str]:
:param stack: The stacklevel increment.
:return: The module and module name.
"""
import inspect # expensive

try:
frame = sys._getframe(2 + stack)
module = inspect.getmodule(frame)
if module is not None:
return (module, module.__name__)
except IndexError:
# IndexError: 2 + stack is out of range
pass
else:
# Shortcut finding the module by manually inspecting loaded modules.
try:
filename = frame.f_code.co_filename
except AttributeError:
# AttributeError: frame.f_code.co_filename is undefined
pass
else:
for module in sys.modules.values():
if not isinstance(module, ModuleType):
continue
if not hasattr(module, "__file__"):
continue
if module.__file__ == filename:
return (module, module.__name__)

# If above failed, do an expensive import and costly getmodule call.
import inspect

module = inspect.getmodule(frame)
if module is not None:
return (module, module.__name__)

raise DeprecatedError("unable to determine the calling module")

Expand All @@ -309,14 +364,11 @@ def _generate_message(
:param addendum: Additional messaging. Useful to indicate what to do instead.
:return: The warning category (if applicable) and the message.
"""
deprecate_version = parse(deprecate_in)
remove_version = parse(remove_in)

category: type[Warning] | None
if self._version < deprecate_version:
if self._version_less_than(deprecate_in):
category = PendingDeprecationWarning
warning = f"is pending deprecation and will be removed in {remove_in}."
elif self._version < remove_version:
elif self._version_less_than(remove_in):
category = DeprecationWarning
warning = f"is deprecated and will be removed in {remove_in}."
else:
Expand Down
5 changes: 4 additions & 1 deletion conda_build/inspect_pkg.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from os.path import abspath, basename, dirname, exists, join, normcase
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Iterable, Literal
from typing import TYPE_CHECKING

from conda.api import Solver
from conda.core.index import get_index
Expand Down Expand Up @@ -40,6 +40,9 @@
package_has_file,
)

if TYPE_CHECKING:
from typing import Iterable, Literal

log = get_logger(__name__)


Expand Down
Loading

0 comments on commit 46dfcf8

Please sign in to comment.