|
1 | | -try: |
| 1 | +"""Compute the version number and store it in the `__version__` variable. |
| 2 | +
|
| 3 | +Based on <https://github.com/maresb/hatch-vcs-footgun-example>. |
| 4 | +""" |
| 5 | + |
| 6 | + |
| 7 | +def _get_hatch_version(): |
| 8 | + """Compute the most up-to-date version number in a development environment. |
| 9 | +
|
| 10 | + Returns `None` if Hatchling is not installed, e.g. in a production environment. |
| 11 | +
|
| 12 | + For more details, see <https://github.com/maresb/hatch-vcs-footgun-example/>. |
| 13 | + """ |
| 14 | + import os |
| 15 | + |
| 16 | + try: |
| 17 | + from hatchling.metadata.core import ProjectMetadata |
| 18 | + from hatchling.plugin.manager import PluginManager |
| 19 | + from hatchling.utils.fs import locate_file |
| 20 | + except ImportError: |
| 21 | + # Hatchling is not installed, so probably we are not in |
| 22 | + # a development environment. |
| 23 | + return None |
| 24 | + |
| 25 | + pyproject_toml = locate_file(__file__, "pyproject.toml") |
| 26 | + if pyproject_toml is None: |
| 27 | + raise RuntimeError("pyproject.toml not found although hatchling is installed") |
| 28 | + root = os.path.dirname(pyproject_toml) |
| 29 | + metadata = ProjectMetadata(root=root, plugin_manager=PluginManager()) |
| 30 | + # Version can be either statically set in pyproject.toml or computed dynamically: |
| 31 | + return metadata.core.version or metadata.hatch.version.cached |
| 32 | + |
| 33 | + |
| 34 | +def _get_importlib_metadata_version(): |
| 35 | + """Compute the version number using importlib.metadata. |
| 36 | +
|
| 37 | + This is the official Pythonic way to get the version number of an installed |
| 38 | + package. However, it is only updated when a package is installed. Thus, if a |
| 39 | + package is installed in editable mode, and a different version is checked out, |
| 40 | + then the version number will not be updated. |
| 41 | + """ |
2 | 42 | from importlib.metadata import version |
3 | | -except ModuleNotFoundError: |
4 | | - from importlib_metadata import version # type: ignore - py37 |
5 | 43 |
|
6 | | -try: |
7 | | - __version__ = version("openprotein-python") |
8 | | -except: |
9 | | - __version__ = "None" |
| 44 | + __version__ = version(__package__) # type: ignore |
| 45 | + return __version__ |
| 46 | + |
| 47 | + |
| 48 | +__version__ = _get_hatch_version() or _get_importlib_metadata_version() |
0 commit comments