Coverage for src / beamme / utils / environment.py: 97%
37 statements
« prev ^ index » next coverage.py v7.12.0, created at 2025-11-21 12:57 +0000
« prev ^ index » next coverage.py v7.12.0, created at 2025-11-21 12:57 +0000
1# The MIT License (MIT)
2#
3# Copyright (c) 2018-2025 BeamMe Authors
4#
5# Permission is hereby granted, free of charge, to any person obtaining a copy
6# of this software and associated documentation files (the "Software"), to deal
7# in the Software without restriction, including without limitation the rights
8# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9# copies of the Software, and to permit persons to whom the Software is
10# furnished to do so, subject to the following conditions:
11#
12# The above copyright notice and this permission notice shall be included in
13# all copies or substantial portions of the Software.
14#
15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21# THE SOFTWARE.
22"""Helper functions to interact with the BeamMe environment."""
24import os as _os
25import shutil as _shutil
26import subprocess as _subprocess # nosec B404
27import sys as _sys
28from importlib.util import find_spec as _find_spec
29from pathlib import Path as _Path
30from typing import Optional as _Optional
31from typing import Tuple as _Tuple
34def cubitpy_is_available() -> bool:
35 """Check if CubitPy is installed.
37 Returns:
38 True if CubitPy is installed, False otherwise
39 """
41 if _find_spec("cubitpy") is None:
42 return False
43 return True
46def is_mybinder():
47 """Check if the current environment is running on mybinder."""
48 return "BINDER_LAUNCH_HOST" in _os.environ.keys()
51def is_testing():
52 """Check if the current environment is a pytest testing run."""
53 return "PYTEST_CURRENT_TEST" in _os.environ
56def get_env_variable(name, *, default="default_not_set"):
57 """Return the value of an environment variable.
59 Args
60 ----
61 name: str
62 Name of the environment variable
63 default:
64 Value to be returned if the given named environment variable does
65 not exist. If this is not set and the name is not in the env
66 variables, then an error will be thrown.
67 """
68 if name in _os.environ.keys():
69 return _os.environ[name]
70 elif default == "default_not_set":
71 raise ValueError(f"Environment variable {name} is not set")
72 return default
75def get_git_data(repo_path: _Path) -> _Tuple[_Optional[str], _Optional[str]]:
76 """Return the hash and date of the current git commit of a git repo for a
77 given repo path.
79 Args:
80 repo_path: Path to the git repository.
81 Returns:
82 A tuple with the hash and date of the current git commit
83 if available, otherwise None.
84 """
86 git = _shutil.which("git")
87 if git is None:
88 raise RuntimeError("Git executable not found")
90 out_sha = _subprocess.run( # nosec B603
91 [git, "rev-parse", "HEAD"],
92 cwd=repo_path,
93 stdout=_subprocess.PIPE,
94 stderr=_subprocess.DEVNULL,
95 )
97 out_date = _subprocess.run( # nosec B603
98 [git, "show", "-s", "--format=%ci"],
99 cwd=repo_path,
100 stdout=_subprocess.PIPE,
101 stderr=_subprocess.DEVNULL,
102 )
104 if not out_sha.returncode + out_date.returncode == 0:
105 return None, None
107 git_sha = out_sha.stdout.decode("ascii").strip()
108 git_date = out_date.stdout.decode("ascii").strip()
110 return git_sha, git_date
113def get_application_path() -> _Path | None:
114 """Returns the application path which created this input file and ensures
115 that the file exists.
117 Returns:
118 A path to the file, which created this input file or None.
119 """
121 # return valid application path if it exists.
122 if _Path(_sys.argv[0]).resolve().exists():
123 return _Path(_sys.argv[0]).resolve()
125 return None