Skip to content

Commit

Permalink
refactor: remove jython and pypy compatiblity helpers, remove setup.py
Browse files Browse the repository at this point in the history
  • Loading branch information
ThirVondukr committed Sep 13, 2024
1 parent 6c10f06 commit 807ef3d
Show file tree
Hide file tree
Showing 12 changed files with 51 additions and 297 deletions.
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import sys
import os
from passlib import __version__ as release
import cloud_sptheme as csp
import cloud_sptheme as csp # type: ignore[import-untyped]
import datetime

# If extensions (or modules to document with autodoc) are in another directory,
Expand Down
4 changes: 2 additions & 2 deletions passlib/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
splitcomma,
)
from passlib.utils.compat import (
num_types,
numeric_types,
unicode_or_bytes,
)
from passlib.utils.decor import deprecated_method, memoized_property
Expand Down Expand Up @@ -1309,7 +1309,7 @@ def _render_ini_value(key, value):
value = ", ".join(value)

# convert numbers to strings
elif isinstance(value, num_types):
elif isinstance(value, numeric_types):
if isinstance(value, float) and key[2] == "vary_rounds":
value = ("%.2f" % value).rstrip("0") if value else "0"
else:
Expand Down
3 changes: 1 addition & 2 deletions passlib/crypto/scrypt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from passlib import exc
from passlib.utils import to_bytes
from passlib.utils.compat import PYPY


__all__ = [
Expand Down Expand Up @@ -154,7 +153,7 @@ def _load_builtin_backend():
"""
Load pure-python scrypt implementation built into passlib.
"""
slowdown = 10 if PYPY else 100
slowdown = 100
warn(
"Using builtin scrypt backend, which is %dx slower than is required "
"for adequate security. Installing scrypt support (via 'pip install scrypt') "
Expand Down
4 changes: 2 additions & 2 deletions passlib/totp.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
getrandstr,
)
from passlib.utils.binary import BASE64_CHARS, b32encode, b32decode
from passlib.utils.compat import bascii_to_str, num_types
from passlib.utils.compat import bascii_to_str, numeric_types
from passlib.utils.decor import hybrid_method, memoized_property
from passlib.crypto.digest import lookup_hash, compile_hmac, pbkdf2_hmac

Expand Down Expand Up @@ -768,7 +768,7 @@ def norm_param(attr, value):

if now is not None:
assert (
isinstance(now(), num_types) and now() >= 0
isinstance(now(), numeric_types) and now() >= 0
), "now() function must return non-negative int/float"
subcls.now = staticmethod(now)

Expand Down
8 changes: 3 additions & 5 deletions passlib/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from codecs import lookup as _lookup_codec
from collections.abc import Sequence, Iterable

from typing import Union
from typing import Union, Optional

import unicodedata

Expand All @@ -37,7 +37,6 @@
b64s_decode,
)
from passlib.utils.compat import (
JYTHON,
join_bytes,
join_unicode,
add_doc,
Expand All @@ -59,7 +58,6 @@
"BCRYPT_CHARS",
"Base64Engine",
"HASH64_CHARS",
"JYTHON",
"LazyBase64Engine",
"ab64_decode",
"ab64_encode",
Expand Down Expand Up @@ -604,7 +602,7 @@ def to_bytes(
source: Union[str, bytes],
encoding: str = "utf-8",
param: str = "value",
source_encoding: str = None,
source_encoding: Optional[str] = None,
) -> bytes:
"""Helper to normalize input to bytes.
Expand Down Expand Up @@ -762,7 +760,7 @@ def is_safe_crypt_input(value):
_safe_crypt_lock = threading.Lock()

try:
import legacycrypt
import legacycrypt # type: ignore[import-untyped]

_crypt = legacycrypt.crypt
except ImportError:
Expand Down
6 changes: 5 additions & 1 deletion passlib/utils/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
b32encode as _b32encode,
)
from binascii import b2a_base64, a2b_base64, Error as _BinAsciiError
from typing import Mapping, Union

from passlib import exc
from passlib.utils.compat import (
bascii_to_str,
Expand Down Expand Up @@ -93,7 +95,9 @@
_TRANSLATE_SOURCE = list(iter_byte_chars(ALL_BYTE_VALUES))


def compile_byte_translation(mapping, source=None):
def compile_byte_translation(
mapping: Mapping[Union[int, str, bytes], Union[int, str]], source=None
) -> bytes:
"""
return a 256-byte string for translating bytes using specified mapping.
bytes not specified by mapping will be left alone.
Expand Down
95 changes: 20 additions & 75 deletions passlib/utils/compat/__init__.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,21 @@
"""passlib.utils.compat - python 2/3 compatibility helpers"""

import logging
import sys

from contextlib import nullcontext
from types import ModuleType
import logging


# make sure it's not an unsupported version, even if we somehow got this far
if sys.version_info < (3, 5):
raise RuntimeError("Passlib requires Python >= 3.5 (as of passlib 1.8)")


JYTHON = sys.platform.startswith("java")

PYPY = hasattr(sys, "pypy_version_info")

if PYPY and sys.pypy_version_info < (2, 0):
raise RuntimeError("passlib requires pypy >= 2.0 (as of passlib 1.7)")
from typing import Callable


def add_doc(obj, doc):
def add_doc(obj: object, doc: str) -> None:
"""add docstring to an object"""
obj.__doc__ = doc


__all__ = [
# type detection
## 'is_mapping',
"num_types",
"numeric_types",
"unicode_or_bytes",
# unicode/bytes types & helpers
"bascii_to_str",
Expand All @@ -43,7 +31,7 @@ def add_doc(obj, doc):

# begin accumulating mapping of lazy-loaded attrs,
# 'merged' into module at bottom
_lazy_attrs = dict()
_lazy_attrs: dict[str, object] = dict()

# =============================================================================
# unicode & bytes types
Expand All @@ -52,24 +40,24 @@ def add_doc(obj, doc):
#: alias for isinstance() tests to detect any string type
unicode_or_bytes = (str, bytes)


join_unicode = "".join
join_bytes = b"".join

if True: # legacy PY3 indent

def bascii_to_str(s):
assert isinstance(s, bytes)
return s.decode("ascii")
def bascii_to_str(s):
assert isinstance(s, bytes)
return s.decode("ascii")


def str_to_bascii(s):
assert isinstance(s, str)
return s.encode("ascii")
def str_to_bascii(s):
assert isinstance(s, str)
return s.encode("ascii")

def iter_byte_chars(s):
assert isinstance(s, bytes)
# FIXME: there has to be a better way to do this
return (bytes([c]) for c in s)

def iter_byte_chars(s):
assert isinstance(s, bytes)
# FIXME: there has to be a better way to do this
return (bytes([c]) for c in s)


# TODO: move docstrings to funcs...
Expand All @@ -80,53 +68,14 @@ def iter_byte_chars(s):

add_doc(iter_byte_chars, "iterate over byte string as sequence of 1-byte strings")

# =============================================================================
# numeric
# =============================================================================

num_types = (int, float)
numeric_types = (int, float)

# =============================================================================
# typing
# =============================================================================
##def is_mapping(obj):
## # non-exhaustive check, enough to distinguish from lists, etc
## return hasattr(obj, "items")

# =============================================================================
# introspection
# =============================================================================


def get_method_function(func):
def get_method_function(func: Callable) -> Callable:
"""given (potential) method, return underlying function"""
return getattr(func, "__func__", func)


# =============================================================================
# context managers
# =============================================================================

try:
# new in py37
from contextlib import nullcontext
except ImportError:

class nullcontext(object):
"""
Context manager that does no additional processing.
"""

def __init__(self, enter_result=None):
self.enter_result = enter_result

def __enter__(self):
return self.enter_result

def __exit__(self, *exc_info):
pass


def _import_object(source):
"""helper to import object from module; accept format `path.to.object`"""
modname, modattr = source.rsplit(".", 1)
Expand Down Expand Up @@ -194,7 +143,3 @@ def __dir__(self):

# replace this module with overlay that will lazily import attributes.
_LazyOverlayModule.replace_module(__name__, _lazy_attrs)

# =============================================================================
# eof
# =============================================================================
2 changes: 1 addition & 1 deletion passlib/utils/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ class GenericHandler(MinimalHandler):
setting_kwds: Optional[tuple[str, ...]] = None

# providing default since most classes don't use this at all.
context_kwds = ()
context_kwds: tuple[str, ...] = ()

# optional prefix that uniquely identifies hash
ident: Optional[str] = None
Expand Down
Loading

0 comments on commit 807ef3d

Please sign in to comment.