ecmwf-findlibs-db0f544/0000775000175000017500000000000015225405734015210 5ustar alastairalastairecmwf-findlibs-db0f544/.github/0000775000175000017500000000000015225405734016550 5ustar alastairalastairecmwf-findlibs-db0f544/.github/ci-hpc-config.yml0000664000175000017500000000016515225405734021703 0ustar alastairalastairbuild: python: 3.10 parallel: 1 pytest_cmd: | FINDLIBS_DISABLE_PACKAGE=no pytest --cov=./ --cov-report=xml ecmwf-findlibs-db0f544/.github/workflows/0000775000175000017500000000000015225405734020605 5ustar alastairalastairecmwf-findlibs-db0f544/.github/workflows/ci.yml0000664000175000017500000000240615225405734021725 0ustar alastairalastairname: ci on: # Trigger the workflow on push to master or develop, except tag creation push: branches: - 'master' - 'develop' tags-ignore: - '**' # Trigger the workflow on pull request pull_request: # Trigger the workflow manually workflow_dispatch: # Trigger after public PR approved for CI pull_request_target: types: [labeled] jobs: # Run CI including downstream packages on self-hosted runners downstream-ci: name: downstream-ci if: ${{ !github.event.pull_request.head.repo.fork && github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci' }} uses: ecmwf/downstream-ci/.github/workflows/downstream-ci.yml@main with: findlibs: ecmwf/findlibs@${{ github.event.pull_request.head.sha || github.sha }} codecov_upload: true python_qa: true secrets: inherit # Build downstream packages on HPC downstream-ci-hpc: name: downstream-ci-hpc if: ${{ !github.event.pull_request.head.repo.fork && github.event.action != 'labeled' || github.event.label.name == 'approved-for-ci' }} uses: ecmwf/downstream-ci/.github/workflows/downstream-ci-hpc.yml@main with: findlibs: ecmwf/findlibs@${{ github.event.pull_request.head.sha || github.sha }} secrets: inherit ecmwf-findlibs-db0f544/.github/workflows/label-public-pr.yml0000664000175000017500000000034315225405734024302 0ustar alastairalastair# Manage labels of pull requests that originate from forks name: label-public-pr on: pull_request_target: types: [opened, synchronize] jobs: label: uses: ecmwf/reusable-workflows/.github/workflows/label-pr.yml@v2 ecmwf-findlibs-db0f544/.github/workflows/cd-pypi.yml0000664000175000017500000000022315225405734022672 0ustar alastairalastairname: cd on: push: tags: - '**' jobs: pypi: uses: ecmwf/reusable-workflows/.github/workflows/cd-pypi.yml@v2 secrets: inherit ecmwf-findlibs-db0f544/pyproject.toml0000664000175000017500000000314315225405734020125 0ustar alastairalastair# (C) Copyright 2020 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation # nor does it submit to any jurisdiction. [build-system] requires = ["setuptools", "wheel"] build-backend = "setuptools.build_meta" [project] name = "findlibs" dynamic = [ "version" ] description = "A package to search for shared libraries on various platforms" readme = "README.md" license = { text = "Apache License Version 2.0" } authors = [ { name = "European Centre for Medium-Range Weather Forecasts (ECMWF)", email = "software@ecmwf.int" } ] requires-python = ">=3.10" keywords = ["tool"] classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Operating System :: OS Independent" ] dependencies = [] [project.urls] homepage = "https://github.com/ecmwf/findlibs" [tool.setuptools.packages.find] include = ["findlibs"] [tool.setuptools.dynamic] version = {attr = "findlibs.__version__"} [project.optional-dependencies] test = ["pytest", "pyfakefs"] ecmwf-findlibs-db0f544/tests/0000775000175000017500000000000015225405734016352 5ustar alastairalastairecmwf-findlibs-db0f544/tests/test_config_file.py0000664000175000017500000000572115225405734022234 0ustar alastairalastair#!/usr/bin/env python3 # (C) Copyright 2020 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation # nor does it submit to any jurisdiction. import sys from pathlib import Path import pyfakefs # noqa registers a fixture called "fs" with pytest import pytest import findlibs extension = findlibs.EXTENSIONS.get(sys.platform, ".so") testlib_path = f"/usr/lib/libtest{extension}" config_paths = [ str(Path(p).expanduser()) for p in ["~/.config/findlibs/findlibs.conf", "~/.findlibs"] ] def test_no_config_file(fs): "Check that findlibs works with no config file" fs.create_file(testlib_path) assert findlibs.find("test") == testlib_path def test_both_config_files(fs): "Check that it throws an error if two config files are present" for p in config_paths: fs.create_file(p) with pytest.raises(ValueError): findlibs._get_paths_from_config() def test_relative_path(fs): "Check that it throws an error on relative paths" fs.create_file( config_paths[0], contents=""" [Paths] relative/path """, ) with pytest.raises(ValueError): findlibs._get_paths_from_config() def test_file(fs): "Check that it throws an error when files are included" fs.create_file( config_paths[0], contents=""" [Paths] /path/to/file.so """, ) with pytest.raises(ValueError): findlibs._get_paths_from_config() def test_empty_config_file(fs): "Check that it works with an empty config file" fs.create_file(testlib_path) fs.create_file(config_paths[0]) assert findlibs.find("test") == testlib_path def test_empty_search_paths(fs): "Check that it works with an empty config file" fs.create_file(testlib_path) fs.create_file( config_paths[0], contents=""" [Paths] """, ) assert findlibs.find("test") == testlib_path # Parametrised tests over # search_dir: a path you could put into .findlibs.yml # testlib_path: a concrete test path to check we can find tings in search_dir @pytest.mark.parametrize( "search_dir,testlib_path", [ ("/test/usr", f"/test/usr/lib/libtest{extension}"), # absolute paths ("/test/usr", f"/test/usr/lib64/libtest{extension}"), # lib64 aswell as lib ( "~/.local", Path(f"~/.local/lib/libtest{extension}").expanduser(), ), # ~ expansion ( "$HOME/.local", Path(f"~/.local/lib/libtest{extension}").expanduser(), ), # $HOME expansion ], ) def test_config(fs, search_dir, testlib_path): fs.create_file(testlib_path) fs.create_file( config_paths[0], contents=f""" [Paths] {search_dir} """, ) assert findlibs.find("test") == str(testlib_path) ecmwf-findlibs-db0f544/tests/downstream-ci-requirements.txt0000664000175000017500000000003215225405734024403 0ustar alastairalastairpytest pytest-cov pyfakefsecmwf-findlibs-db0f544/tests/transitive/0000775000175000017500000000000015225405734020542 5ustar alastairalastairecmwf-findlibs-db0f544/tests/transitive/__init__.py0000664000175000017500000000000015225405734022641 0ustar alastairalastairecmwf-findlibs-db0f544/tests/transitive/modAlib/0000775000175000017500000000000015225405734022111 5ustar alastairalastairecmwf-findlibs-db0f544/tests/transitive/modAlib/__init__.py0000664000175000017500000000004415225405734024220 0ustar alastairalastairfindlibs_dependencies = ["modBlib"] ecmwf-findlibs-db0f544/tests/transitive/modAlib/lib64/0000775000175000017500000000000015225405734023031 5ustar alastairalastairecmwf-findlibs-db0f544/tests/transitive/modAlib/lib64/libmodA.so0000664000175000017500000000000015225405734024731 0ustar alastairalastairecmwf-findlibs-db0f544/tests/transitive/modBlib/0000775000175000017500000000000015225405734022112 5ustar alastairalastairecmwf-findlibs-db0f544/tests/transitive/modBlib/__init__.py0000664000175000017500000000000015225405734024211 0ustar alastairalastairecmwf-findlibs-db0f544/tests/transitive/modBlib/lib64/0000775000175000017500000000000015225405734023032 5ustar alastairalastairecmwf-findlibs-db0f544/tests/transitive/modBlib/lib64/libmodB.so0000664000175000017500000000000015225405734024733 0ustar alastairalastairecmwf-findlibs-db0f544/tests/transitive/test_transitive.py0000664000175000017500000000226515225405734024350 0ustar alastairalastairimport sys import typing from pathlib import Path import findlibs def test_transitive(monkeypatch) -> None: """There is a module modAlibs in this directory that mocks expected bin wheel contract: - modulename ends with 'lib' - contains libmodA.so - inside __init__ there is the findlibs_dependencies, containing modBlib This test checks that when such module is findlibs-found, the (mock) ld loaded the libmodB """ # so that modAlibs and modBlibs are visible sys.path.append(str(Path(__file__).parent)) # the files in test are not real .so, we thus just track what got loaded loaded_libs = set() def libload_accumulator(path: str, mode: typing.Any): loaded_libs.add(path) monkeypatch.setattr(findlibs, "CDLL", libload_accumulator) monkeypatch.setattr( sys, "platform", "tests" ) # this makes the test behave like linux default # test found = findlibs.find("modA") expected_found = str(Path(__file__).parent / "modAlib" / "lib64" / "libmodA.so") assert found == expected_found expected_dylib = str(Path(__file__).parent / "modBlib" / "lib64" / "libmodB.so") assert loaded_libs == {expected_dylib} ecmwf-findlibs-db0f544/tests/test_basic.py0000664000175000017500000000270615225405734021051 0ustar alastairalastair#!/usr/bin/env python3 # (C) Copyright 2020 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation # nor does it submit to any jurisdiction. import os import sys from pathlib import Path import pyfakefs # noqa registers a fixture called "fs" with pytest import pytest import findlibs pkg_name = "foobar" extension = findlibs.EXTENSIONS.get(sys.platform, ".so") libname = f"lib{pkg_name}{extension}" conda_prefix = "/test/conda/prefix" os.environ["CONDA_PREFIX"] = conda_prefix env_variable_location = os.environ[f"{pkg_name}_HOME"] = "/test/environment/variable" ld_library_location = os.environ["LD_LIBRARY_PATH"] = "/test/ld_library/" # A list of test locations in order of precedence # test_find checks that if a file is placed in any of these locations then it is found test_locations = [ sys.prefix, conda_prefix, env_variable_location, "/", "/usr/", "/usr/local/", "/opt/", "/opt/homebrew/", os.path.expanduser("~/.local"), ] @pytest.mark.parametrize("location", test_locations) def test_find(fs, location): libpath = Path(location) / "lib" / libname print(f"creating {libpath}") fs.create_file(libpath) assert findlibs.find(pkg_name) == str(libpath) ecmwf-findlibs-db0f544/LICENSE0000664000175000017500000002613515225405734016224 0ustar alastairalastair Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ecmwf-findlibs-db0f544/setup.cfg0000664000175000017500000000007215225405734017030 0ustar alastairalastair[flake8] max-line-length = 110 extend-ignore = E203, W503 ecmwf-findlibs-db0f544/README.md0000664000175000017500000000614215225405734016472 0ustar alastairalastair# findlibs A Python package that searches for shared libraries on various platforms. ## Usage ```python import findlibs lib = findlibs.find("eccodes") # If package name differs from library name use: lib = findlibs.find(lib_name="odccore", pkg_name="odc") ``` ## Installation ```bash pip install findlibs ``` ## Testing ```bash git clone https://github.com/ecmwf/findlibs cd findlibs pip install -e ".[test]" pytest ``` ## find The module only contains the `find()` function. ```python def find(lib_name, pkg_name=None) ``` Returns the path to the selected library, or None if not found. **Arguments**: - `lib_name` _str_ - Library name without the `lib` prefix. The name of the library to find is formed using `lib_name` and a platform specific suffix (by default ".so"). E.g. when `lib_name` is "eccodes" the library name will be "libeccodes.so" on Linux and "libeccodes.dylib" on macOS. - `pkg_name` _str, optional_ - Package name if it differs from the library name. **Returns**: str or None: Path to selected library The **algorithm** to find the library is as follows: - First, tries to find the library in an installed python module package with the given name, e.g. eccodeslib, eckitlib. Disable this search option by setting environment variable `FINDLIBS_DISABLE_PACKAGE=yes`. - Next, tries the `lib` and `lib64` directories under `sys.prefix` and `$CONDA_PREFIX`. Disable this search option by setting environment variable `FINDLIBS_DISABLE_PYTHON=yes`. - Next, tries the `lib` and `lib64` directories under the paths defined by the `pkg_name + "_HOME"` and `pkg_name + "_DIR"` environment variables. Both lowercase and uppercase versions are tested. E.g. if `pkg_name` is "eccodes" it will check the paths defined by `$eccodes_dir`, `$eccodes_home`, `$ECCODES_DIR` and `$ECCODES_HOME`. Disable this search option by setting environment variable `FINDLIBS_DISABLE_HOME=yes`. - Next, tries to load the search paths from the user defined `~/.findlibs` or `~/.config/findlibs/findlibs.conf` INI configuration files. Then for all the user defined search paths, the `lib` and `lib64` subdirectories are tried. Please note that only one of these files can exist. The configuration file can contain multiple search paths, but no relative paths or paths to files are allowed. The file can even be completely empty or can contain no paths at all. The file format is as follows: ``` [Paths] /path/to/lib_directory ``` Disable this search option by setting environment variable `FINDLIBS_DISABLE_CONFIG_PATHS=yes`. - Next, tries the directories defined by the `$LD_LIBRARY_PATH` and `$DYLD_LIBRARY_PATH` environment variables. Disable this search option by setting environment variable `FINDLIBS_DISABLE_LD_PATH=yes`. - Next, tries the `lib` and `lib64` directories under the following paths "/", "/usr/", "/usr/local/", "/opt/", "/opt/homebrew/" and "~/.local/". Disable this search option by setting environment variable `FINDLIBS_DISABLE_SYS=yes`. - Finally, tries calling the `ctypes.util.find_library` function. Disable this search option by setting environment variable `FINDLIBS_DISABLE_CTYPES_UTIL=yes`.ecmwf-findlibs-db0f544/.gitignore0000664000175000017500000000056615225405734017207 0ustar alastairalastair__pycache__/ *.old *.pyc ?.* build/ *.egg-info/ ### VisualStudioCode ### .vscode/ # Local History for Visual Studio Code .history/ # Built Visual Studio Code Extensions *.vsix ### VisualStudioCode Patch ### # Ignore all local history of files .history .ionide # Support for Project snippet scope .vscode/*.code-snippets # Ignore code-workspaces *.code-workspace *swp ecmwf-findlibs-db0f544/findlibs/0000775000175000017500000000000015225405734017002 5ustar alastairalastairecmwf-findlibs-db0f544/findlibs/__init__.py0000664000175000017500000002604315225405734021120 0ustar alastairalastair#!/usr/bin/env python3 # (C) Copyright 2020 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation # nor does it submit to any jurisdiction. # import configparser import ctypes.util import importlib import logging import os import re import sys import warnings from collections import defaultdict from ctypes import CDLL, RTLD_GLOBAL from pathlib import Path from types import ModuleType from typing import Union __version__ = "0.1.3" logger = logging.getLogger(__name__) EXTENSIONS = defaultdict( lambda: ".so", darwin=".dylib", win32=".dll", ) EXTENSIONS_RE = defaultdict( lambda: r"^.*\.so(.[0-9]+)?$", darwin=r"^.*\.dylib$", win32=r"^.*\.dll$", ) def _load_globally(path: str) -> CDLL: """Loads the library to make it accessible to subsequently loaded libraries and extensions""" # NOTE this doesnt ultimately work on MacOS -- without corresponding `rpath`s on the lib, we end up # failing asserts in `eckit::system::LibraryRegistry::enregister`. Possibly, fixing that assert, # making library names correct, etc, could make this work return CDLL(path, mode=RTLD_GLOBAL) def _single_preload_deps(path: str) -> None: """See _find_in_package""" logger.debug(f"initiating recursive search at {path}") for lib in os.listdir(path): logger.debug(f"considering {lib}") if re.match(EXTENSIONS_RE[sys.platform], lib): logger.debug(f"loading {lib} at {path}") _ = _load_globally(f"{path}/{lib}") logger.debug(f"loaded {lib}") def _transitive_preload_deps(module: ModuleType) -> None: """See _find_in_package""" # NOTE consider replacing hasattr with entrypoint-based declaration # https://packaging.python.org/en/latest/specifications/entry-points/ if hasattr(module, "findlibs_dependencies"): for module_name in module.findlibs_dependencies: logger.debug(f"consider transitive dependency preload of {module_name}") try: rec_into = importlib.import_module(module_name) # NOTE we need *first* to evaluate recursive call, *then* preload, # to ensure that dependencies are already in place _transitive_preload_deps(rec_into) for ext_path in ( str(Path(rec_into.__file__).parent / "lib"), str(Path(rec_into.__file__).parent / "lib64"), ): if os.path.exists(ext_path): _single_preload_deps(ext_path) except ImportError: # NOTE we don't use ImportWarning here as thats off by default m = f"unable to import {module_name} yet declared as dependency of {module.__name__}" warnings.warn(m) logger.debug(m) def _find_in_package( lib_name: str, pkg_name: str, preload_deps: Union[bool, None] = None ) -> Union[str, None]: """Tries to find the library in an installed python module `{pgk_name}`. Examples of packages with such expositions are `eckitlib` or `odclib`. If preload deps is True, it additionally opens all dylibs of this library and its transitive dependencies This is needed if the `.so`s in the wheel don't have correct rpath -- which is effectively impossible in non-trivial venvs. It would be tempting to just extend LD_LIBRARY_PATH -- alas, that won't have any effect as the linker has been configured already by the time cpython is running""" if preload_deps is None: preload_deps = ( sys.platform != "darwin" ) # NOTE see _load_globally for explanation try: module = importlib.import_module(pkg_name) logger.debug(f"found package {pkg_name}; with {preload_deps=}") if preload_deps: _transitive_preload_deps(module) for venv_wheel_lib in ( str((Path(module.__file__).parent / "lib" / lib_name)), str((Path(module.__file__).parent / "lib64" / lib_name)), ): if os.path.exists(venv_wheel_lib): return venv_wheel_lib except ImportError: pass return None def _find_in_python(lib_name: str, pkg_name: str) -> Union[str, None]: """Tries to find the library installed directly to Conda/Python sys.prefix libs""" roots = [sys.prefix] if "CONDA_PREFIX" in os.environ: roots.append(os.environ["CONDA_PREFIX"]) for root in roots: for lib in ("lib", "lib64"): fullname = os.path.join(root, lib, lib_name) if os.path.exists(fullname): return fullname return None def _find_in_home(lib_name: str, pkg_name: str) -> Union[str, None]: env_prefixes = [pkg_name.upper(), pkg_name.lower()] if pkg_name.endswith("lib"): # if eg "eckitlib" is pkg name, consider also "eckit" prefix env_prefixes += [pkg_name.upper()[:-3], pkg_name.lower()[:-3]] env_suffixes = ["HOME", "DIR"] envs = ["{}_{}".format(x, y) for x in env_prefixes for y in env_suffixes] for env in envs: if env in os.environ: home = os.path.expanduser(os.environ[env]) for lib in ("lib", "lib64"): fullname = os.path.join(home, lib, lib_name) if os.path.exists(fullname): return fullname return None def _get_paths_from_config(): locations = [ Path(p).expanduser() for p in [ "~/.config/findlibs/findlibs.conf", "~/.findlibs", ] ] locations = [p for p in locations if p.exists()] if len(locations) == 0: return [] if len(locations) > 1: raise ValueError( f"There are multiple config files! Delete all but one of {locations}" ) config = configparser.RawConfigParser( allow_no_value=True ) # Allow keys without values config.optionxform = lambda option: option # Preserve case of keys with open(locations[0], "r"): config.read(locations[0]) if "Paths" not in config: return [] # replace $HOME with ~, expand ~ to full path, # resolve any relative paths to absolute paths paths = {Path(p.replace("$HOME", "~")).expanduser() for p in config["Paths"] or []} relative_paths = [p for p in paths if not p.is_absolute()] if relative_paths: raise ValueError( ( f"Don't use relative paths in the config file ({locations[0]})," f" offending paths are: {relative_paths}" ) ) files = [p for p in paths if not p.is_dir()] if files: raise ValueError( f"Don't put files in the config file ({locations[0]}), offending files are: {files}" ) return paths def _find_in_config_paths(lib_name: str, pkg_name: str) -> Union[str, None]: paths = _get_paths_from_config() for root in paths: for lib in ("lib", "lib64"): filepath = root / lib / lib_name if filepath.exists(): return str(filepath) return None def _find_in_ld_path(lib_name: str, pkg_name: str) -> Union[str, None]: for path in ( "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", ): for home in os.environ.get(path, "").split(":"): fullname = os.path.join(home, lib_name) if os.path.exists(fullname): return fullname return None def _find_in_sys(lib_name: str, pkg_name: str) -> Union[str, None]: for root in ( "/", "/usr/", "/usr/local/", "/opt/", "/opt/homebrew/", os.path.expanduser("~/.local"), ): for lib in ("lib", "lib64"): fullname = os.path.join(root, lib, lib_name) if os.path.exists(fullname): return fullname return None def _find_in_ctypes_util(lib_name: str, pkg_name: str) -> Union[str, None]: # NOTE this is a bit unreliable function, as for some libraries/sources, # it returns full path, in others just a filename. It still may be worth # it as a fallback even in the filename-only case, to help troubleshoot some # yet unknown source return ctypes.util.find_library(lib_name) or ctypes.util.find_library( lib_name.removeprefix("lib") ) def find(lib_name: str, pkg_name: Union[str, None] = None) -> Union[str, None]: """Returns the path to the selected library, or None if not found. Searches over multiple sources in this order: - importible python module ("PACKAGE") - python's sys.prefix and conda's libs ("PYTHON") - package's home like ECCODES_HOME ("HOME") - findlibs config like .findlibs ("CONFIG_PATHS") - ld library path ("LD_PATH") - system's libraries ("SYS") - invocation of ctypes.util ("CTYPES_UTIL") each can be disabled via setting FINDLIBS_DISABLE_{method} to "yes", so eg `export FINDLIBS_DISABLE_PACKAGE=yes`. Consult the code for each individual method implementation and further configurability. Arguments --------- lib_name : str Library name without the `lib` prefix. The name of the library to find is formed using ``lib_name`` and a platform specific suffix (by default ".so"). E.g. when ``lib_name`` is "eccodes" the library name will be "libeccodes.so" on Linux and "libeccodes.dylib" on macOS. pkg_name : str, optional Package name if it differs from the library name. Defaults to None, which sets it to f"{lib_name}lib". Used by python module import and home sources, with the home source considering also `lib`-less name. Returns -------- str or None Path to selected library """ pkg_name = pkg_name or f"{lib_name}lib" extension = EXTENSIONS[sys.platform] lib_name = "lib{}{}".format(lib_name, extension) sources = ( (_find_in_package, "PACKAGE"), (_find_in_python, "PYTHON"), (_find_in_home, "HOME"), (_find_in_config_paths, "CONFIG_PATHS"), (_find_in_ld_path, "LD_PATH"), (_find_in_sys, "SYS"), (_find_in_ctypes_util, "CTYPES_UTIL"), ) sources_filtered = ( source_clb for source_clb, source_name in sources if os.environ.get(f"FINDLIBS_DISABLE_{source_name}", None) not in ("yes", "1") ) for source in sources_filtered: logger.debug(f"about to search for {lib_name}/{pkg_name} in {source}") if result := source(lib_name, pkg_name): logger.debug(f"found {lib_name}/{pkg_name} in {source}") return result return None def load(lib_name: str, pkg_name: Union[str, None] = None) -> CDLL: """Convenience method to find a library and load it right away (recursively)""" path = find(lib_name, pkg_name) if not path: raise ModuleNotFoundError( f"unable to find {pkg_name+'.' if pkg_name else ''}{lib_name}" ) else: return _load_globally(path)