Skip to content

Commit

Permalink
[*] pretty version info
Browse files Browse the repository at this point in the history
  • Loading branch information
autumnjolitz committed Dec 12, 2023
1 parent a62f8fc commit 25055e4
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 24 deletions.
3 changes: 2 additions & 1 deletion dev-requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ twine
build
black
invoke
packaging
# bump-my-version
# git-changelog
mypy
mypy
59 changes: 54 additions & 5 deletions generate_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
import shlex
from contextlib import suppress

try:
from packaging.version import parse as parse_version
except ImportError:
from setuptools._vendor.packaging.version import parse as parse_version

here = os.path.dirname(os.path.abspath(__file__))

with open(os.path.join(here, "CURRENT_VERSION.txt")) as fh:
Expand All @@ -12,21 +17,65 @@
continue
version = line.strip()
break
else:
fh.seek(0)
raise LookupError(f"Cannot find a version inside file! It has {fh.read()!r}")

empty_s = ""
current_sha = ""
if os.path.exists(os.path.join(here, ".git")):
current_sha = subprocess.check_output(shlex.split("git rev-parse HEAD")).strip().decode()

full_version = version
if current_sha:
full_version = f"{version}+git.{current_sha}"
parsed_version = parse_version(full_version)


with open(os.path.join(here, "instruct/about.py"), "w") as fh:
fh.write(
f"""# Autogenerated from `generate_version`
def write_about_and_emit_version():
with open(os.path.join(here, "instruct/about.py"), "w") as fh:
fh.write(
f"""# Autogenerated from `attr: generate_version.write_about_and_emit_version`
# it is run on setup.py/pip installs!
from typing import NamedTuple, Optional, Tuple
from functools import total_ordering
@total_ordering
class VersionInfo(NamedTuple):
major: int
minor: int
micro: int
pre: Optional[Tuple[str, int]]
post: Optional[int]
local: Optional[str]
def __eq__(self, other):
return self[:3] == other[:3]
def __lt__(self, other):
return self[:3] < other[:3]
@property
def release(self):
return self[:3]
@property
def public(self) -> str:
return "{full_version}"
__version__ = "{full_version}"
__version__: str = "{full_version}"
__version_info__: VersionInfo = VersionInfo(
{parsed_version.major!r},
{parsed_version.minor!r},
{parsed_version.micro!r},
{parsed_version.pre!r},
{parsed_version.post!r},
{parsed_version.local or None!r},
)
__commit__: Optional[str] = {parsed_version.local or None!r}
"""
)
)
return version
29 changes: 14 additions & 15 deletions instruct/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
import inflection
from jinja2 import Environment, PackageLoader

from .about import __version__
from .about import __version__, __version_info__
from .typedef import (
parse_typedef,
ismetasubclass,
Expand Down Expand Up @@ -94,7 +94,7 @@
from .constants import NoPickle, NoJSON, NoIterable, Range, NoHistory, RangeFlags

T = TypeVar("T")
__version__ # Silence unused import warning.
__version__, __version_info__ # Silence unused import warning.

logger = logging.getLogger(__name__)
env = Environment(loader=PackageLoader(__name__, "templates"))
Expand Down Expand Up @@ -161,7 +161,7 @@ def public_class(
return public_atomic_classes[0]
return public_atomic_classes
else:
next_cls, = atomic_classes
(next_cls,) = atomic_classes
return public_class(next_cls, *rest, preserve_subtraction=preserve_subtraction)
cls = cls.__public_class__()
if preserve_subtraction and any((cls._skipped_fields, cls._modified_fields)):
Expand Down Expand Up @@ -254,7 +254,7 @@ def keys(
return cls._all_accessible_fields
return KeysView(tuple(cls._slots))
if len(property_path) == 1:
key, = property_path
(key,) = property_path
if key not in cls._nested_atomic_collection_keys:
return keys(cls._slots[key])
if len(cls._nested_atomic_collection_keys[key]) == 1:
Expand Down Expand Up @@ -587,7 +587,6 @@ def key_func(item: Type) -> int:
def make_class_cell():
return CellType(None)


else:

def make_class_cell() -> CellType:
Expand All @@ -605,7 +604,7 @@ def bar():
return bar

fake_function = closure_maker()
class_cell, = fake_function.__closure__
(class_cell,) = fake_function.__closure__
del fake_function
return class_cell

Expand Down Expand Up @@ -1182,9 +1181,10 @@ def apply_skip_keys(
current_coerce = None
else:
while hasattr(current_coerce_cast_function, "__union_subtypes__"):
current_coerce_types, current_coerce_cast_function = (
current_coerce_cast_function.__union_subtypes__
)
(
current_coerce_types,
current_coerce_cast_function,
) = current_coerce_cast_function.__union_subtypes__
current_coerce = (current_coerce_types, current_coerce_cast_function)
del current_coerce_types, current_coerce_cast_function

Expand Down Expand Up @@ -1280,8 +1280,7 @@ class AtomicMeta(type):

if TYPE_CHECKING:
_annotated_metadata: Dict[str, Tuple[Any, ...]]
BINARY_JSON_ENCODERS
Dict[str, Callable[[Union[bytearray, bytes]], Any]]
BINARY_JSON_ENCODERS: Dict[str, Callable[[Union[bytearray, bytes]], Any]]
_set_defaults: Callable[[], None]
_data_class: Atomic
_slots: Mapping[str, Union[Type, Tuple[Type, ...]]]
Expand Down Expand Up @@ -2255,10 +2254,10 @@ def listener(self, name: str, old, new):
... elif name == 'field_two':
... if new_value < 0:
... self.field_two = 0
...
...
>>> astuple(Foo('', -1))
('No empty!', 0, None)
>>>
>>>
"""

def wrapper(func):
Expand Down Expand Up @@ -2287,7 +2286,7 @@ def handle_type_error(*fields: str):
... pass
... else:
... return True
...
...
>>> f = Foo('My Foo', '255')
>>> astuple(f)
('My Foo', 255, None)
Expand Down Expand Up @@ -2400,7 +2399,7 @@ def _create_invalid_type(cls, field_name, val, val_type, types_required):
rest = ", ".join([x for x in rest_types])
expects = f"either an {rest} or a {end}"
else:
expected_type, = types_required_names
(expected_type,) = types_required_names
expects = f"a {expected_type}"
return InstructTypeError(
f"Unable to set {field_name} to {val!r} ({val_type.__name__}). {field_name} expects "
Expand Down
5 changes: 2 additions & 3 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ protocols = True

[metadata]
name = instruct
version = attr: generate_version.version
version = attr: generate_version.write_about_and_emit_version
author = Autumn Jolitz
description = Compact/flexible/fast/strictly-typed/(add other ridiculous demands) object system - similar to Pydantic but focused on `__slot__`ed objects
url = https://github.com/autumnjolitz/instruct
Expand Down Expand Up @@ -48,7 +48,7 @@ include_package_data = True
include =
instruct
instruct.*
exclude =
exclude =
contrib
docs
tests*
Expand Down Expand Up @@ -87,4 +87,3 @@ mock_traceback_monkeypatch = true
filterwarnings =
ignore::ResourceWarning
ignore::DeprecationWarning

0 comments on commit 25055e4

Please sign in to comment.