python-simpleconf 0.9.3a1__py3-none-any.whl → 0.9.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-simpleconf
3
- Version: 0.9.3a1
3
+ Version: 0.9.5
4
4
  Summary: Simple configuration management with python.
5
5
  Project-URL: Homepage, https://github.com/pwwang/simpleconf
6
6
  Project-URL: Repository, https://github.com/pwwang/simpleconf
@@ -29,7 +29,7 @@ Requires-Dist: liquidpy<0.9,>=0.8; extra == 'liquid'
29
29
  Provides-Extra: liquidpy
30
30
  Requires-Dist: liquidpy<0.9,>=0.8; extra == 'liquidpy'
31
31
  Provides-Extra: toml
32
- Requires-Dist: rtoml<0.13,>=0.12; (sys_platform == 'linux') and extra == 'toml'
32
+ Requires-Dist: rtoml<1,>=0.12; (sys_platform == 'linux') and extra == 'toml'
33
33
  Requires-Dist: tomli<3,>=2.0; (sys_platform != 'linux') and extra == 'toml'
34
34
  Provides-Extra: yaml
35
35
  Requires-Dist: pyyaml<7,>=6; extra == 'yaml'
@@ -347,9 +347,9 @@ conf = Config.load('config.liq.toml')
347
347
  # conf.section1.a == 1
348
348
  # conf.section2.a == 2
349
349
  ```
350
- #### Loader directive in the first line
350
+ #### Loader directive
351
351
 
352
- Instead of using a special file extension, you can embed a loader directive in the **first line** of a configuration file as a comment. This allows a plain `config.toml` to be processed by the Liquid engine without renaming the file.
352
+ Instead of using a special file extension, you can embed a loader directive in the first lines of a configuration file as a comment. This allows a plain `config.toml` to be processed by the Liquid engine without renaming the file.
353
353
 
354
354
  The directive format is:
355
355
 
@@ -400,4 +400,120 @@ from simpleconf import Config
400
400
 
401
401
  conf = Config.load('config.yaml')
402
402
  # conf.default.a == 2
403
- ```
403
+ ```
404
+
405
+ #### Loadenv directive
406
+
407
+ You will need `python-dotenv` installed to use the `loadenv` directive. You can install it with:
408
+
409
+ ```shell
410
+ pip install python-simpleconf[toml,env]
411
+ ```
412
+ if you only need TOML and dotenv support, or
413
+
414
+ ```shell
415
+ pip install python-simpleconf[all]
416
+ ```
417
+ if you want all supported formats.
418
+
419
+ You can also embed a `# simpleconf-loadenv` directive in the first few lines of a configuration file to load environment variables from a `.env` file. This allows you to reference environment variables directly in your config values using `$env:VAR` syntax, and makes them available as `env` in Jinja2/Liquid templates via `{{ env.VAR }}` or `{{ env["VAR"] }}`.
420
+
421
+ The directive format is:
422
+
423
+ ```
424
+ # simpleconf-loadenv
425
+ # simpleconf-loadenv: /path/to/.env
426
+ ```
427
+
428
+ When no path is given, `./.env` is loaded (relative to the config file's directory).
429
+
430
+ Supported comment prefixes: `#`, `;`, `//` (case-insensitive).
431
+
432
+ **Example — using `$env:VAR` references:**
433
+
434
+ `.env`
435
+ ```env
436
+ DB_HOST=localhost
437
+ DB_PORT=@int:5432
438
+ ```
439
+
440
+ `config.yaml`
441
+ ```yaml
442
+ # simpleconf-loadenv
443
+ db:
444
+ host: $env:DB_HOST
445
+ port: $env:DB_PORT
446
+ ```
447
+
448
+ ```python
449
+ from simpleconf import Config
450
+
451
+ conf = Config.load('config.yaml')
452
+ # conf.db.host == 'localhost'
453
+ # conf.db.port == 5432 # @int: cast to int
454
+ ```
455
+
456
+ The `$env:VAR` syntax works in all supported formats (YAML, TOML, INI, JSON, .env). In formats that require quoted strings (TOML), wrap the reference in quotes: `"$env:DB_HOST"`.
457
+
458
+ Lookup order: the loaded `.env` file is checked first, then `os.environ` as a fallback.
459
+
460
+ **Modifiers — controlling what happens when a variable is not found**
461
+
462
+ The `$env:` syntax supports optional modifiers to control the behavior when a variable is not found:
463
+
464
+ | Syntax | Behavior when VAR not found |
465
+ |---|---|
466
+ | `$env:VAR` | **Default** — raises `ValueError` |
467
+ | `$env:VAR:required` | Explicit form — raises `ValueError` |
468
+ | `$env:VAR:optional-asis` | Keeps the literal `$env:VAR` string unchanged |
469
+ | `$env:VAR:optional-empty` | Resolves to an empty string `""` |
470
+
471
+ **Example — using modifiers:**
472
+
473
+ `.env`
474
+ ```env
475
+ DB_HOST=localhost
476
+ ```
477
+
478
+ `config.yaml`
479
+ ```yaml
480
+ # simpleconf-loadenv
481
+ db:
482
+ host: $env:DB_HOST
483
+ port: $env:DB_PORT:optional-asis # keeps "$env:DB_PORT" as-is when not found
484
+ timeout: $env:TIMEOUT:optional-empty # becomes "" when not found
485
+ ```
486
+
487
+ ```python
488
+ from simpleconf import Config
489
+
490
+ conf = Config.load('config.yaml')
491
+ # conf.db.host == 'localhost'
492
+ # conf.db.port == '$env:DB_PORT'
493
+ # conf.db.timeout == ''
494
+ ```
495
+
496
+ **Example — using `env` in templates:**
497
+
498
+ `.env`
499
+ ```env
500
+ DB_HOST=localhost
501
+ DB_PORT=5432
502
+ ```
503
+
504
+ `config.toml`
505
+ ```toml
506
+ # simpleconf-loadenv
507
+ # simpleconf-loader: liq
508
+ [default]
509
+ url = "{{ env.DB_HOST }}:{{ env.DB_PORT }}"
510
+ ```
511
+
512
+ ```python
513
+ from simpleconf import Config
514
+
515
+ conf = Config.load('config.toml')
516
+ # conf.default.url == 'localhost:5432'
517
+ ```
518
+
519
+ Both directives (`simpleconf-loader` and `simpleconf-loadenv`) can coexist in the same file on different lines. The order does not matter.
@@ -1,10 +1,10 @@
1
- simpleconf/__init__.py,sha256=V3G4vrJauZva5CUPH--DkZnsBFdLNcpumcK5qu27o24,104
1
+ simpleconf/__init__.py,sha256=wrkpYialYF4KkMHvjDPalFW7VZOusyaCU7iGDEa6Gc8,104
2
2
  simpleconf/caster.py,sha256=qHnegp1FZzbUWm-UbCaGjQKN6d9rN1v_0Wa4I_CMEi4,2379
3
- simpleconf/config.py,sha256=B6h-mgeiyI7op-R-i1C_z0oyc4pt7Tv7zKWgzsDy4xw,17922
3
+ simpleconf/config.py,sha256=Wf6zCoUs3QGHVFdYTFldcIVk6vmmqnf9bth4Wz0F2Lw,18677
4
4
  simpleconf/exceptions.py,sha256=Tb7w9gMO2XU4mE-Rc2HAnuHWDUpMzdl39oGVjeAv254,171
5
5
  simpleconf/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
- simpleconf/utils.py,sha256=prO5mN64Ir_7bmNnn6kEh-xZAAYiXTOxpiuFhiw9HpI,6247
7
- simpleconf/loaders/__init__.py,sha256=HeIlfn-bw6NHpS-r7fQqyGRnTZXdApENSd2cGW9y4VE,5482
6
+ simpleconf/utils.py,sha256=JXnmdGd3JE6QDPvL9QSQi_lC07vQLDuIbof6b4idEIA,8856
7
+ simpleconf/loaders/__init__.py,sha256=ZuWgb_D8UUwniWKltg7jtjAhEUm0J6sCZrFkXVSSweM,8491
8
8
  simpleconf/loaders/dict.py,sha256=8Az511i9OLLXosSBMMXiEfiQVScQ5SIqsF6EHlAkKdM,801
9
9
  simpleconf/loaders/env.py,sha256=cOYZbHk08MrBjxtNfV8Cv5LHrZg_flzap1lOM3GVdRk,3729
10
10
  simpleconf/loaders/ini.py,sha256=a8ahJIzw24SIEnGbZmYNoxo8O1tYi6pG_GrOil0Rcx0,3739
@@ -12,7 +12,7 @@ simpleconf/loaders/json.py,sha256=0NTKB9JidB8vbeODxNYAY8fJP6__znetuIUAClFeNIo,19
12
12
  simpleconf/loaders/osenv.py,sha256=K829KFiHLl3pS8HSCep8JoPVG_d7VRxPAb7SPYFRypg,1779
13
13
  simpleconf/loaders/toml.py,sha256=OJCukg_R3zlmas_q_CrdeKUsw8Wj5LoSnkNJ7Flt86w,2525
14
14
  simpleconf/loaders/yaml.py,sha256=IoKMaQF5y5HWEjQsnUwL2UvABVj9A-0AmBhn8s7lE54,2146
15
- python_simpleconf-0.9.3a1.dist-info/METADATA,sha256=l8gY5UovwMiMQpYyK22uuObTeSyQ5QADNu-3mwdZsaM,8949
16
- python_simpleconf-0.9.3a1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
17
- python_simpleconf-0.9.3a1.dist-info/licenses/LICENSE,sha256=2j7OLS2vXIEshgbSkiCU9RgYJY1M4OBBtO6ECbo7OB8,1056
18
- python_simpleconf-0.9.3a1.dist-info/RECORD,,
15
+ python_simpleconf-0.9.5.dist-info/METADATA,sha256=7Nj2Ku_RsdJGLpeReGByUurGdh9-dp6eF_yVDQfaBOo,11876
16
+ python_simpleconf-0.9.5.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
17
+ python_simpleconf-0.9.5.dist-info/licenses/LICENSE,sha256=2j7OLS2vXIEshgbSkiCU9RgYJY1M4OBBtO6ECbo7OB8,1056
18
+ python_simpleconf-0.9.5.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.29.0
2
+ Generator: hatchling 1.31.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
simpleconf/__init__.py CHANGED
@@ -2,4 +2,4 @@ from .config import Config, ProfileConfig
2
2
 
3
3
  __all__ = ["Config", "ProfileConfig"]
4
4
 
5
- __version__ = "0.9.3"
5
+ __version__ = "0.9.5"
simpleconf/config.py CHANGED
@@ -5,12 +5,31 @@ from typing import Any, List, Generator, Union, Sequence
5
5
 
6
6
  from diot import Diot
7
7
 
8
- from .utils import config_to_ext, detect_loader_directive, get_loader, POOL_KEY, META_KEY
8
+ from .utils import (
9
+ config_to_ext,
10
+ detect_loader_directive,
11
+ detect_loadenv_directive,
12
+ load_dotenv_file,
13
+ get_loader,
14
+ POOL_KEY,
15
+ META_KEY,
16
+ )
9
17
  from .loaders import Loader
10
18
 
11
19
  LoaderType = Union[str, Loader, None]
12
20
 
13
21
 
22
+ def _inject_env_vars(loader: Loader, config: Any) -> None:
23
+ """Detect ``# simpleconf-loadenv`` directive and inject env vars into loader.
24
+
25
+ If the config file contains a loadenv directive, the referenced ``.env``
26
+ file is loaded and its contents are stored in ``loader.env_vars``.
27
+ """
28
+ env_path = detect_loadenv_directive(config)
29
+ if env_path is not None:
30
+ loader.env_vars = load_dotenv_file(env_path)
31
+
32
+
14
33
  class Config:
15
34
  """The configuration class"""
16
35
 
@@ -121,6 +140,8 @@ class Config:
121
140
  else:
122
141
  loader = get_loader(loader)
123
142
 
143
+ _inject_env_vars(loader, config)
144
+
124
145
  return loader.load(config, ignore_nonexist)
125
146
 
126
147
  @classmethod
@@ -151,6 +172,8 @@ class Config:
151
172
  else:
152
173
  loader = get_loader(loader)
153
174
 
175
+ _inject_env_vars(loader, config)
176
+
154
177
  return await loader.a_load(config, ignore_nonexist)
155
178
 
156
179
 
@@ -209,6 +232,8 @@ class ProfileConfig:
209
232
  else:
210
233
  lder = get_loader(lder)
211
234
 
235
+ _inject_env_vars(lder, conf)
236
+
212
237
  loaded = lder.load_with_profiles(conf, ignore_nonexist)
213
238
  for profile, value in loaded.items():
214
239
  profile = profile.lower()
@@ -279,6 +304,8 @@ class ProfileConfig:
279
304
  else:
280
305
  lder = get_loader(lder)
281
306
 
307
+ _inject_env_vars(lder, conf)
308
+
282
309
  loaded = await lder.a_load_with_profiles(conf, ignore_nonexist)
283
310
  for profile, value in loaded.items():
284
311
  profile = profile.lower()
@@ -332,6 +359,8 @@ class ProfileConfig:
332
359
  else:
333
360
  loader = get_loader(loader)
334
361
 
362
+ _inject_env_vars(loader, conf)
363
+
335
364
  loaded = loader.load_with_profiles(conf, ignore_nonexist)
336
365
  for profile, value in loaded.items():
337
366
  profile = profile.lower()
@@ -388,6 +417,8 @@ class ProfileConfig:
388
417
  else:
389
418
  loader = get_loader(loader)
390
419
 
420
+ _inject_env_vars(loader, conf)
421
+
391
422
  loaded = await loader.a_load_with_profiles(conf, ignore_nonexist)
392
423
  for profile, value in loaded.items():
393
424
  profile = profile.lower()
@@ -1,18 +1,44 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import os
3
4
  from abc import ABC, abstractmethod
4
5
  from typing import Any, Callable, List, Dict
5
6
  from pathlib import Path
6
7
 
7
8
  from diot import Diot
8
9
  from panpath import PanPath
9
- from ..caster import cast
10
+ from ..caster import (
11
+ cast,
12
+ cast_value,
13
+ int_caster,
14
+ float_caster,
15
+ bool_caster,
16
+ none_caster,
17
+ python_caster,
18
+ py_caster,
19
+ json_caster,
20
+ toml_caster,
21
+ )
22
+
23
+ _ENV_CASTERS = [
24
+ int_caster,
25
+ float_caster,
26
+ bool_caster,
27
+ none_caster,
28
+ python_caster,
29
+ py_caster,
30
+ json_caster,
31
+ toml_caster,
32
+ ]
10
33
 
11
34
 
12
35
  class Loader(ABC):
13
36
 
14
37
  CASTERS: List[Callable[[str, bool], Any]] | None = None
15
38
 
39
+ def __init__(self) -> None:
40
+ self.env_vars: Dict[str, str] = {}
41
+
16
42
  @staticmethod
17
43
  def _convert_path(conf: str | Path) -> Path:
18
44
  """Convert the conf to Path if it is a string"""
@@ -36,6 +62,62 @@ class Loader(ABC):
36
62
 
37
63
  return Diot(loaded)
38
64
 
65
+ def _resolve_env_vars(self, loaded: Diot) -> Diot:
66
+ """Resolve ``$env:VAR`` references in loaded config values.
67
+
68
+ Called after ``_convert()`` (i.e., after casters have been applied).
69
+ Recursively walks the config and replaces string values matching
70
+ ``$env:KEY`` with the corresponding environment variable.
71
+
72
+ Lookup order:
73
+ 1. ``self.env_vars`` (loaded from ``.env`` file via directive)
74
+ 2. ``os.environ`` (system environment variables)
75
+
76
+ Resolved values are re-cast through :attr:`CASTERS`.
77
+
78
+ Returns the mutated Diot for chaining.
79
+ """
80
+ dict_type = type({})
81
+
82
+ KNOWN_MODIFIERS = frozenset(
83
+ {"required", "optional-asis", "optional-empty"}
84
+ )
85
+
86
+ def _walk(value):
87
+ if isinstance(value, dict_type):
88
+ for k, v in value.items():
89
+ value[k] = _walk(v)
90
+ return value
91
+ if isinstance(value, str) and value.startswith("$env:"):
92
+ rest = value[5:]
93
+ if ":" in rest:
94
+ var_name, modifier = rest.rsplit(":", 1)
95
+ if modifier not in KNOWN_MODIFIERS:
96
+ # Unknown modifier — treat whole string as var name
97
+ var_name, modifier = rest, "required"
98
+ else:
99
+ var_name, modifier = rest, "required"
100
+
101
+ resolved = self.env_vars.get(var_name)
102
+ if resolved is None:
103
+ resolved = os.environ.get(var_name)
104
+
105
+ if resolved is not None:
106
+ return cast_value(resolved, _ENV_CASTERS)
107
+
108
+ # Not found — behavior depends on modifier
109
+ if modifier == "optional-empty":
110
+ return ""
111
+ if modifier == "optional-asis":
112
+ return f"$env:{var_name}"
113
+ # required (default)
114
+ raise ValueError(
115
+ f"Environment variable '{var_name}' not found."
116
+ )
117
+ return value
118
+
119
+ return _walk(loaded)
120
+
39
121
  @classmethod
40
122
  def _convert_with_profiles(cls, conf: Any, loaded: Any) -> Diot:
41
123
  """Convert the loaded configuration with profiles to Diot"""
@@ -69,7 +151,7 @@ class Loader(ABC):
69
151
  """
70
152
  path = self.__class__._convert_path(conf)
71
153
  loaded = self.loading(path, ignore_nonexist)
72
- return self.__class__._convert(conf, loaded)
154
+ return self._resolve_env_vars(self.__class__._convert(conf, loaded))
73
155
 
74
156
  async def a_load(self, conf: Any, ignore_nonexist: bool = False) -> Diot:
75
157
  """Asynchronously load the configuration from the path or configurations
@@ -83,7 +165,7 @@ class Loader(ABC):
83
165
  """
84
166
  path = self.__class__._convert_path(conf)
85
167
  loaded = await self.a_loading(path, ignore_nonexist)
86
- return self.__class__._convert(conf, loaded)
168
+ return self._resolve_env_vars(self.__class__._convert(conf, loaded))
87
169
 
88
170
  def load_with_profiles( # type: ignore[override]
89
171
  self,
@@ -101,7 +183,9 @@ class Loader(ABC):
101
183
  """
102
184
  path = self.__class__._convert_path(conf)
103
185
  loaded = self.loading(path, ignore_nonexist)
104
- return self.__class__._convert_with_profiles(conf, loaded)
186
+ return self._resolve_env_vars(
187
+ self.__class__._convert_with_profiles(conf, loaded)
188
+ )
105
189
 
106
190
  async def a_load_with_profiles( # type: ignore[override]
107
191
  self,
@@ -119,7 +203,9 @@ class Loader(ABC):
119
203
  """
120
204
  path = self.__class__._convert_path(conf)
121
205
  loaded = await self.a_loading(path, ignore_nonexist)
122
- return self.__class__._convert_with_profiles(conf, loaded)
206
+ return self._resolve_env_vars(
207
+ self.__class__._convert_with_profiles(conf, loaded)
208
+ )
123
209
 
124
210
 
125
211
  class NoConvertingPathMixin(ABC):
@@ -148,7 +234,11 @@ class J2ModifierMixin(LoaderModifierMixin):
148
234
  def _modifier(self, content: str | bytes) -> str | bytes:
149
235
  """Modify the content of the configuration file before loading"""
150
236
  from jinja2 import Template
151
- return Template(content).render() # type: ignore
237
+ env_vars = getattr(self, "env_vars", {})
238
+ casted_env = {
239
+ k: cast_value(v, _ENV_CASTERS) for k, v in env_vars.items()
240
+ }
241
+ return Template(content).render(env=casted_env) # type: ignore
152
242
 
153
243
 
154
244
  class LiqModifierMixin(LoaderModifierMixin):
@@ -159,4 +249,8 @@ class LiqModifierMixin(LoaderModifierMixin):
159
249
  from liquid import Liquid # type: ignore[import]
160
250
  str_content = content.decode() if isinstance(content, bytes) else content
161
251
  liq = Liquid(str_content, from_file=False, mode="wild") # type: ignore
162
- return liq.render()
252
+ env_vars = getattr(self, "env_vars", {})
253
+ casted_env = {
254
+ k: cast_value(v, _ENV_CASTERS) for k, v in env_vars.items()
255
+ }
256
+ return liq.render(env=casted_env) # type: ignore
simpleconf/utils.py CHANGED
@@ -1,10 +1,11 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import io
3
4
  import re
4
5
  from pathlib import Path
5
6
  from importlib import import_module
6
7
  from types import ModuleType
7
- from typing import Any
8
+ from typing import Any, Dict, List
8
9
 
9
10
  from .exceptions import FormatNotSupported
10
11
  from .loaders import Loader
@@ -17,9 +18,42 @@ _LOADER_DIRECTIVE_RE = re.compile(
17
18
  re.IGNORECASE,
18
19
  )
19
20
 
21
+ _LOADENV_DIRECTIVE_RE = re.compile(
22
+ r"^\s*(?:#|;|//)\s*simpleconf-loadenv(?::\s*(.+))?$",
23
+ re.IGNORECASE,
24
+ )
25
+
26
+
27
+ def _read_first_lines(conf: Any) -> List[str]:
28
+ """Read the first few lines of a config file for directive detection.
29
+
30
+ Args:
31
+ conf: The configuration source.
32
+
33
+ Returns:
34
+ A list of lines (up to 5) from the beginning of the file,
35
+ or an empty list if *conf* is not a readable file.
36
+ """
37
+ if isinstance(conf, dict) or hasattr(conf, "read"):
38
+ return []
39
+
40
+ path = Path(conf)
41
+ try:
42
+ if not path.exists():
43
+ return []
44
+ except Exception: # pragma: no cover
45
+ # e.g. OSError: Filename too long
46
+ return []
47
+
48
+ try:
49
+ return path.read_text(errors="replace").split("\n")[:5]
50
+ except Exception:
51
+ return []
52
+
20
53
 
21
54
  def detect_loader_directive(conf: Any, current_ext: str) -> str:
22
- """Detect if the first line of a config file contains a loader directive.
55
+ """Detect if the first few lines of a config file contain a loader
56
+ directive.
23
57
 
24
58
  Supports comment styles::
25
59
 
@@ -42,36 +76,98 @@ def detect_loader_directive(conf: Any, current_ext: str) -> str:
42
76
  The overriding extension string, or *current_ext* when no directive
43
77
  is present.
44
78
  """
45
- if isinstance(conf, dict) or hasattr(conf, "read"):
79
+ lines = _read_first_lines(conf)
80
+ if not lines:
46
81
  return current_ext
47
82
 
48
- path = Path(conf)
49
- if not path.exists():
50
- return current_ext
83
+ for line in lines:
84
+ match = _LOADER_DIRECTIVE_RE.match(line)
85
+ if not match:
86
+ continue
51
87
 
52
- try:
53
- first_line = path.read_text(errors="replace").split("\n", 1)[0]
54
- except Exception:
55
- return current_ext
88
+ directive = match.group(1).lower()
56
89
 
57
- match = _LOADER_DIRECTIVE_RE.match(first_line)
58
- if not match:
59
- return current_ext
90
+ # Derive the base format name
91
+ # (strip any existing template suffix)
92
+ parts = current_ext.split(".")
93
+ base_ext = parts[0] if parts[-1] in ("j2", "liq") else current_ext
60
94
 
61
- directive = match.group(1).lower()
95
+ if directive in ("liq", "liquid"):
96
+ return base_ext + ".liq"
62
97
 
63
- # Derive the base format name (strip any existing template suffix)
64
- parts = current_ext.split(".")
65
- base_ext = parts[0] if parts[-1] in ("j2", "liq") else current_ext
98
+ if directive in ("j2", "jinja", "jinja2"):
99
+ return base_ext + ".j2"
66
100
 
67
- if directive in ("liq", "liquid"):
68
- return base_ext + ".liq"
101
+ # Treat as an explicit loader extension name
102
+ return directive
69
103
 
70
- if directive in ("j2", "jinja", "jinja2"):
71
- return base_ext + ".j2"
104
+ return current_ext
72
105
 
73
- # Treat as an explicit loader extension name
74
- return directive
106
+
107
+ def detect_loadenv_directive(conf: Any) -> str | None:
108
+ """Detect if the first few lines of a config file contain a loadenv
109
+ directive.
110
+
111
+ Supports both a bare directive (defaults to ``./.env``) and a path::
112
+
113
+ # simpleconf-loadenv
114
+ # simpleconf-loadenv: /path/to/.env
115
+ ; simpleconf-loadenv: ../shared/.env
116
+ // simpleconf-loadenv
117
+
118
+ The path is resolved relative to the config file's directory.
119
+
120
+ Args:
121
+ conf: The configuration source. Dicts and stream objects are
122
+ ignored (returns ``None``).
123
+
124
+ Returns:
125
+ The absolute path to the ``.env`` file, or ``None`` when no
126
+ directive is present.
127
+ """
128
+ lines = _read_first_lines(conf)
129
+ if not lines:
130
+ return None
131
+
132
+ for line in lines:
133
+ match = _LOADENV_DIRECTIVE_RE.match(line)
134
+ if not match:
135
+ continue
136
+
137
+ raw_path = (match.group(1) or "").strip()
138
+ conf_dir = Path(conf).parent
139
+
140
+ if not raw_path:
141
+ return str(conf_dir.resolve() / ".env")
142
+
143
+ env_path = Path(raw_path)
144
+ if not env_path.is_absolute():
145
+ env_path = (conf_dir / env_path).resolve()
146
+ return str(env_path)
147
+
148
+ return None
149
+
150
+
151
+ def load_dotenv_file(env_path: str) -> Dict[str, str]:
152
+ """Load environment variables from a ``.env`` file.
153
+
154
+ Uses ``python-dotenv`` to parse the file. Returns only the variables
155
+ defined in the file — does **not** modify ``os.environ``.
156
+
157
+ Args:
158
+ env_path: Path to the ``.env`` file.
159
+
160
+ Returns:
161
+ A dict of variable names to values. Returns an empty dict when
162
+ the file does not exist.
163
+ """
164
+ dotenv = require_package("dotenv")
165
+ dotenv_file = Path(env_path)
166
+ if not dotenv_file.exists():
167
+ return {}
168
+ content = dotenv_file.read_text()
169
+ sio = io.StringIO(content)
170
+ return dict(dotenv.dotenv_values(stream=sio))
75
171
 
76
172
 
77
173
  def config_to_ext(conf: Any, secondary: bool = True) -> str: