Skip to content

Commit

Permalink
Get metadata version from packages_distributions
Browse files Browse the repository at this point in the history
  • Loading branch information
SmileyChris committed May 7, 2024
1 parent 69b197a commit c2a23df
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ requires-python = ">=3.8"
dependencies = [
"click",
"importlib-resources>=5; python_version<'3.10'",
"importlib-metadata=4.6.*; python_version<'3.10'",
"incremental",
"jinja2",
"tomli; python_version<'3.11'",
Expand Down
33 changes: 27 additions & 6 deletions src/towncrier/_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
Responsible for getting the version and name from a project.
"""


from __future__ import annotations

import sys
Expand All @@ -18,6 +17,12 @@
from incremental import Version as IncrementalVersion


try:
from importlib.metadata import packages_distributions
except ImportError:
from importlib_metadata import packages_distributions


def _get_package(package_dir: str, package: str) -> ModuleType:
try:
module = import_module(package)
Expand All @@ -39,15 +44,31 @@ def _get_package(package_dir: str, package: str) -> ModuleType:
return module


def get_version(package_dir: str, package: str) -> str:
module = _get_package(package_dir, package)
def _get_metadata_version(package: str) -> str | None:
distributions = packages_distributions()
distribution_names = distributions.get(package)
if not len(distribution_names) == 1:
# We can't determine the version if there are multiple distributions.
return None
try:
version = metadata_version(f"{module}")
return metadata_version(distribution_names[0])
except PackageNotFoundError:
version = getattr(module, "__version__", None)
return None


def get_version(package_dir: str, package: str) -> str:
# First try to get the version from the package metadata.
if version := _get_metadata_version(package):
return version

module = _get_package(package_dir, package)

version = getattr(module, "__version__", None)

if not version:
raise Exception("No __version__, I don't know how else to look")
raise Exception(
f"No __version__ or metadata version info for the {package} package."
)

if isinstance(version, str):
return version.strip()
Expand Down

0 comments on commit c2a23df

Please sign in to comment.