Coverage for abb_rws_client_python_rw6/core/env.py: 99%
51 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-13 22:17 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-13 22:17 +0000
1# abb_rws_client/core/env.py
2"""Environment configuration loader for abb_rws_client_python_rw6.
4Author: Clement RACINET
6Resolves and loads a ``.env`` file into :data:`os.environ` using
7:mod:`python-dotenv` (already a runtime dependency). The lookup walks
8up the directory tree from a given starting point, so it works correctly
9regardless of the current working directory or script nesting depth.
11This module is part of the library's public API. Any application or script can
12call :func:`load_env` to bootstrap the environment before instantiating
13:class:`~abb_rws_client_python_rw6.RWSClient`.
15Environment variables recognised by :class:`~abb_rws_client_python_rw6.RWSClient`:
16 - ``RWS_HOST`` : Controller IP or hostname (required if not passed explicitly).
17 - ``RWS_USER`` : RWS username (default: ``"Default User"``).
18 - ``RWS_PASSWORD`` : RWS password (default: ``"robotics"``).
19 - ``RWS_PORT`` : HTTP port as integer string (default: ``"80"``).
20 - ``RWS_TIMEOUT`` : HTTP timeout in seconds as float string (default: no timeout).
21 Set to a number (e.g. ``"30"``) to limit request duration.
22 - ``RWS_LOG_LEVEL``: Logging level for :func:`~abb_rws_client_python_rw6.configure_logging`
23 (default: ``"WARNING"``).
24"""
26from __future__ import annotations
28import os
29from pathlib import Path
32def load_env(
33 env_path: Path | str | None = None,
34 *,
35 override: bool = False,
36) -> Path | None:
37 """Locate and load a ``.env`` file into :data:`os.environ`.
39 Uses :func:`dotenv.load_dotenv` under the hood (``python-dotenv``).
40 When *env_path* is ``None``, the function walks up the directory tree
41 starting from the **caller's file location** (via :data:`Path.cwd`)
42 until it finds a ``.env`` file or reaches the filesystem root.
44 Already-set variables are **never overwritten** unless *override* is
45 ``True`` — safe to call multiple times.
47 Args:
48 env_path: Explicit path to a ``.env`` file or directory
49 containing one. When ``None``, the function searches
50 upward from :func:`Path.cwd`.
51 override: When ``True``, existing environment variables are
52 overwritten by values from the ``.env`` file. Defaults to
53 ``False`` (``os.environ.setdefault`` semantics).
55 Returns:
56 The resolved :class:`Path` of the loaded ``.env`` file, or
57 ``None`` if no file was found (no error is raised).
59 Raises:
60 FileNotFoundError: If *env_path* is given explicitly but does
61 not exist.
63 Example:
64 Automatic discovery from current working directory::
66 from abb_rws_client_python_rw6import load_env
67 load_env()
69 Explicit path::
71 from abb_rws_client_python_rw6import load_env
72 from pathlib import Path
73 load_env(Path("/etc/myrobot/.env"))
75 Override existing variables::
77 from abb_rws_client_python_rw6import load_env
78 load_env(override=True)
79 """
80 try:
81 from dotenv import load_dotenv # python-dotenv
82 except ImportError as exc: # pragma: no cover
83 raise ImportError(
84 "python-dotenv is required for load_env(). Install it with: pip install python-dotenv"
85 ) from exc
87 resolved: Path | None
89 if env_path is not None:
90 resolved = Path(env_path).resolve()
91 if resolved.is_dir():
92 resolved = resolved / ".env"
93 if not resolved.is_file():
94 raise FileNotFoundError(f".env file not found: {resolved}")
95 else:
96 resolved = _find_env(Path.cwd())
97 if resolved is None: 97 ↛ 100line 97 didn't jump to line 100 because the condition on line 97 was always true
98 return None
100 load_dotenv(dotenv_path=resolved, override=override)
101 return resolved
104def _find_env(start: Path) -> Path | None:
105 """Walk up the directory tree looking for a ``.env`` file.
107 Args:
108 start: Directory from which to begin the upward search.
110 Returns:
111 The first ``.env`` :class:`Path` found, or ``None`` if the
112 filesystem root is reached without finding one.
114 Example:
115 >>> from pathlib import Path
116 >>> from abb_rws_client_python_rw6.core.env import _find_env
117 >>> _find_env(Path("/home/user/projects/robot/examples/02"))
118 PosixPath('/home/user/projects/robot/.env') # if it exists there
119 """
120 current = start
121 while True:
122 candidate = current / ".env"
123 if candidate.is_file():
124 return candidate
125 parent = current.parent
126 if parent == current:
127 return None
128 current = parent
131def get_env_str(key: str, default: str) -> str:
132 """Read a string environment variable with a fallback default.
134 Args:
135 key: Environment variable name.
136 default: Value returned when the variable is absent or empty.
138 Returns:
139 The environment variable value, or *default*.
141 Example:
142 >>> host = get_env_str("RWS_HOST", "192.168.125.1")
143 """
144 return os.environ.get(key, default) or default
147def get_env_int(key: str, default: int) -> int:
148 """Read an integer environment variable with a fallback default.
150 Args:
151 key: Environment variable name.
152 default: Value returned when the variable is absent, empty,
153 or not a valid integer.
155 Returns:
156 The parsed integer value, or *default*.
158 Example:
159 >>> port = get_env_int("RWS_PORT", 80)
160 """
161 raw = os.environ.get(key, "")
162 try:
163 return int(raw)
164 except ValueError:
165 return default
168def get_env_float(key: str, default: float) -> float:
169 """Read a float environment variable with a fallback default.
171 Args:
172 key: Environment variable name.
173 default: Value returned when the variable is absent, empty,
174 or not a valid float.
176 Returns:
177 The parsed float value, or *default*.
179 Example:
180 >>> timeout = get_env_float("RWS_TIMEOUT", 10.0)
181 """
182 raw = os.environ.get(key, "")
183 try:
184 return float(raw)
185 except ValueError:
186 return default
189def get_env_float_or_none(key: str, default: float | None) -> float | None:
190 """Read a float-or-None environment variable with a fallback default.
192 Accepts ``"none"``, ``"inf"``, ``"infinite"``, ``"infinity"``
193 (case-insensitive) as special string values mapping to ``None``
194 (no timeout). When the variable is absent or empty, *default* is
195 returned as-is.
197 Args:
198 key: Environment variable name.
199 default: Value returned when the variable is absent, empty, or invalid.
201 Returns:
202 The parsed float, ``None`` (no timeout), or *default*.
204 Example:
205 >>> timeout = get_env_float_or_none("RWS_TIMEOUT", None)
206 >>> timeout is None # → no timeout
207 True
208 """
209 raw = os.environ.get(key, "").strip().lower()
210 if not raw:
211 return default
212 if raw in {"none", "inf", "infinite", "infinity"}:
213 return None
214 try:
215 return float(raw)
216 except ValueError:
217 return default