From 81cf47cdf748ff5877505125d147c895aa46cbc1 Mon Sep 17 00:00:00 2001 From: Arpan Mahanty Date: Sat, 30 Mar 2024 11:10:14 +0530 Subject: [PATCH] Refactor code for resolving version information --- fastboot/__init__.py | 15 ++------------- fastboot/settings.py | 10 +++++++++- fastboot/version.py | 25 +++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 14 deletions(-) create mode 100644 fastboot/version.py diff --git a/fastboot/__init__.py b/fastboot/__init__.py index 38810f6..e7aff31 100644 --- a/fastboot/__init__.py +++ b/fastboot/__init__.py @@ -1,19 +1,8 @@ -import importlib.metadata -import tomllib +from fastboot.version import VERSION __all__ = ["__version__"] # Project Information +__version__ = VERSION __author__ = ["Arpan Mahanty "] __license__ = "MIT" - -try: - from fastboot.settings import PROJECT_DIR - - # Read version from pyproject file during development - with open(PROJECT_DIR / "pyproject.toml", mode="rb") as pyproject_file: - __version__: str = tomllib.load(pyproject_file)["tool"]["poetry"]["version"] - -except FileNotFoundError: # pragma: no cover - # Read from the package metadata - __version__: str = importlib.metadata.version(__package__ or __name__.split(".", maxsplit=1)[0]) diff --git a/fastboot/settings.py b/fastboot/settings.py index f569978..62b8efa 100644 --- a/fastboot/settings.py +++ b/fastboot/settings.py @@ -1,7 +1,15 @@ import pathlib from typing import Any -PROJECT_DIR: pathlib.Path = pathlib.Path(__file__).parents[1] +# Known Paths +PROJECT_ROOT: pathlib.Path = pathlib.Path(__file__).parents[1] +PROJECT_CONFIG_TOML: pathlib.Path = PROJECT_ROOT / "pyproject.toml" + +# Settings: +DEVELOP: bool = PROJECT_CONFIG_TOML.exists() + + +# Settings Schema KNOWN_SETTINGS: dict[str, Any] = { "port": {}, diff --git a/fastboot/version.py b/fastboot/version.py new file mode 100644 index 0000000..b15f4df --- /dev/null +++ b/fastboot/version.py @@ -0,0 +1,25 @@ +import importlib.metadata +import tomllib +from typing import Any + +from fastboot.settings import DEVELOP, PROJECT_CONFIG_TOML + + +def read_version_from_pyproject() -> str: + """Reads version string from the pyproject file located at the project root. Mostly used during development only.""" + + with open(PROJECT_CONFIG_TOML, mode="rb") as f: + pyproject: dict[str, Any] = tomllib.load(f) + + return pyproject["tool"]["poetry"]["version"] + + +def read_version_from_package_metadata() -> str: # pragma: no cover + """Reads version string from the package metadata for the current project.""" + + pkg_name: str = __package__ or __name__.split(".", maxsplit=1)[0] + return importlib.metadata.version(pkg_name) + + +# Version Information +VERSION: str = read_version_from_pyproject() if DEVELOP else read_version_from_package_metadata()