diff --git a/src/ewatercycle/util.py b/src/ewatercycle/util.py index 3f20f972..49e1fd0c 100644 --- a/src/ewatercycle/util.py +++ b/src/ewatercycle/util.py @@ -3,6 +3,7 @@ from collections.abc import Iterable from configparser import ConfigParser from datetime import datetime +from importlib.metadata import entry_points, version from pathlib import Path from typing import Any @@ -329,3 +330,25 @@ class CaseConfigParser(ConfigParser): def optionxform(self, optionstr): """Do not convert option names to lowercase.""" return optionstr + + +def extract_package_name(value: str) -> str: + """Extract package name from entry point value. + + E.g. "ewatercycle_HBV.model:HBV" will return + "ewatercycle_HBV". + """ + source = value.split(":")[0] + return source.split(".")[0] + + +def get_package_versions() -> dict[str, str]: + """Get the version numbers of the ewatercycle package and its plugins.""" + eps = [ep for ep in entry_points() if "ewatercycle" in ep.group] + packages = {extract_package_name(ep.value) for ep in eps} + + package_versions = {} + package_versions["ewatercycle"] = version("ewatercycle") + package_versions["grpc4bmi"] = version("grpc4bmi") + package_versions.update({pkg: version(pkg) for pkg in packages}) + return package_versions diff --git a/tests/src/test_util.py b/tests/src/test_util.py index 3f0c3d14..3e05a9a6 100644 --- a/tests/src/test_util.py +++ b/tests/src/test_util.py @@ -5,9 +5,11 @@ import xarray as xr from numpy.testing import assert_array_equal +import ewatercycle from ewatercycle.util import ( find_closest_point, fit_extents_to_grid, + get_package_versions, get_time, merge_esvmaltool_datasets, reindex, @@ -250,3 +252,9 @@ def test_merge_datasets_multivar(esmvaltool_output): esmvaltool_output[i]["second_var"] = esmvaltool_output[i]["tas"] + 1 with pytest.raises(ValueError, match="More than one variable found in dataset"): merge_esvmaltool_datasets(esmvaltool_output) + + +def test_version_getter(): + versions = get_package_versions() + assert versions["ewatercycle"] == ewatercycle.__version__ + assert "grpc4bmi" in versions