python-simpleconf 0.9.3__py3-none-any.whl → 0.9.4__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.
- {python_simpleconf-0.9.3.dist-info → python_simpleconf-0.9.4.dist-info}/METADATA +109 -5
- {python_simpleconf-0.9.3.dist-info → python_simpleconf-0.9.4.dist-info}/RECORD +8 -8
- {python_simpleconf-0.9.3.dist-info → python_simpleconf-0.9.4.dist-info}/WHEEL +1 -1
- simpleconf/__init__.py +1 -1
- simpleconf/config.py +32 -1
- simpleconf/loaders/__init__.py +101 -7
- simpleconf/utils.py +115 -23
- {python_simpleconf-0.9.3.dist-info → python_simpleconf-0.9.4.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python-simpleconf
|
|
3
|
-
Version: 0.9.
|
|
3
|
+
Version: 0.9.4
|
|
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<
|
|
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
|
|
350
|
+
#### Loader directive
|
|
351
351
|
|
|
352
|
-
Instead of using a special file extension, you can embed a loader directive in the
|
|
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,108 @@ 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 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"] }}`.
|
|
408
|
+
|
|
409
|
+
The directive format is:
|
|
410
|
+
|
|
411
|
+
```
|
|
412
|
+
# simpleconf-loadenv
|
|
413
|
+
# simpleconf-loadenv: /path/to/.env
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
When no path is given, `./.env` is loaded (relative to the config file's directory).
|
|
417
|
+
|
|
418
|
+
Supported comment prefixes: `#`, `;`, `//` (case-insensitive).
|
|
419
|
+
|
|
420
|
+
**Example — using `$env:VAR` references:**
|
|
421
|
+
|
|
422
|
+
`.env`
|
|
423
|
+
```env
|
|
424
|
+
DB_HOST=localhost
|
|
425
|
+
DB_PORT=@int:5432
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
`config.yaml`
|
|
429
|
+
```yaml
|
|
430
|
+
# simpleconf-loadenv
|
|
431
|
+
db:
|
|
432
|
+
host: $env:DB_HOST
|
|
433
|
+
port: $env:DB_PORT
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
```python
|
|
437
|
+
from simpleconf import Config
|
|
438
|
+
|
|
439
|
+
conf = Config.load('config.yaml')
|
|
440
|
+
# conf.db.host == 'localhost'
|
|
441
|
+
# conf.db.port == 5432 # @int: cast to int
|
|
442
|
+
```
|
|
443
|
+
|
|
444
|
+
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"`.
|
|
445
|
+
|
|
446
|
+
Lookup order: the loaded `.env` file is checked first, then `os.environ` as a fallback.
|
|
447
|
+
|
|
448
|
+
**Modifiers — controlling what happens when a variable is not found**
|
|
449
|
+
|
|
450
|
+
The `$env:` syntax supports optional modifiers to control the behavior when a variable is not found:
|
|
451
|
+
|
|
452
|
+
| Syntax | Behavior when VAR not found |
|
|
453
|
+
|---|---|
|
|
454
|
+
| `$env:VAR` | **Default** — raises `ValueError` |
|
|
455
|
+
| `$env:VAR:required` | Explicit form — raises `ValueError` |
|
|
456
|
+
| `$env:VAR:optional-asis` | Keeps the literal `$env:VAR` string unchanged |
|
|
457
|
+
| `$env:VAR:optional-empty` | Resolves to an empty string `""` |
|
|
458
|
+
|
|
459
|
+
**Example — using modifiers:**
|
|
460
|
+
|
|
461
|
+
`.env`
|
|
462
|
+
```env
|
|
463
|
+
DB_HOST=localhost
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
`config.yaml`
|
|
467
|
+
```yaml
|
|
468
|
+
# simpleconf-loadenv
|
|
469
|
+
db:
|
|
470
|
+
host: $env:DB_HOST
|
|
471
|
+
port: $env:DB_PORT:optional-asis # keeps "$env:DB_PORT" as-is when not found
|
|
472
|
+
timeout: $env:TIMEOUT:optional-empty # becomes "" when not found
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
```python
|
|
476
|
+
from simpleconf import Config
|
|
477
|
+
|
|
478
|
+
conf = Config.load('config.yaml')
|
|
479
|
+
# conf.db.host == 'localhost'
|
|
480
|
+
# conf.db.port == '$env:DB_PORT'
|
|
481
|
+
# conf.db.timeout == ''
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
**Example — using `env` in templates:**
|
|
485
|
+
|
|
486
|
+
`.env`
|
|
487
|
+
```env
|
|
488
|
+
DB_HOST=localhost
|
|
489
|
+
DB_PORT=5432
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
`config.toml`
|
|
493
|
+
```toml
|
|
494
|
+
# simpleconf-loadenv
|
|
495
|
+
# simpleconf-loader: liq
|
|
496
|
+
[default]
|
|
497
|
+
url = "{{ env.DB_HOST }}:{{ env.DB_PORT }}"
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
```python
|
|
501
|
+
from simpleconf import Config
|
|
502
|
+
|
|
503
|
+
conf = Config.load('config.toml')
|
|
504
|
+
# conf.default.url == 'localhost:5432'
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
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=
|
|
1
|
+
simpleconf/__init__.py,sha256=VOsGsKvRKKpZnFcYYRKxs40KZjm4AfIRgwtOYP5Uk1Y,104
|
|
2
2
|
simpleconf/caster.py,sha256=qHnegp1FZzbUWm-UbCaGjQKN6d9rN1v_0Wa4I_CMEi4,2379
|
|
3
|
-
simpleconf/config.py,sha256=
|
|
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=
|
|
7
|
-
simpleconf/loaders/__init__.py,sha256=
|
|
6
|
+
simpleconf/utils.py,sha256=Oyuthm2RdK2mhhjwDU28LAvDwEh2abRXVGZ4_fx8ecE,8737
|
|
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.
|
|
16
|
-
python_simpleconf-0.9.
|
|
17
|
-
python_simpleconf-0.9.
|
|
18
|
-
python_simpleconf-0.9.
|
|
15
|
+
python_simpleconf-0.9.4.dist-info/METADATA,sha256=kPT35p8JYK_3W0hEwmiwhh8Bj1OJQDRKNxqhHeAULeA,11595
|
|
16
|
+
python_simpleconf-0.9.4.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
17
|
+
python_simpleconf-0.9.4.dist-info/licenses/LICENSE,sha256=2j7OLS2vXIEshgbSkiCU9RgYJY1M4OBBtO6ECbo7OB8,1056
|
|
18
|
+
python_simpleconf-0.9.4.dist-info/RECORD,,
|
simpleconf/__init__.py
CHANGED
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
|
|
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()
|
simpleconf/loaders/__init__.py
CHANGED
|
@@ -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
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
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,38 @@ _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
|
+
if not path.exists():
|
|
42
|
+
return []
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
return path.read_text(errors="replace").split("\n")[:5]
|
|
46
|
+
except Exception:
|
|
47
|
+
return []
|
|
48
|
+
|
|
20
49
|
|
|
21
50
|
def detect_loader_directive(conf: Any, current_ext: str) -> str:
|
|
22
|
-
"""Detect if the first
|
|
51
|
+
"""Detect if the first few lines of a config file contain a loader
|
|
52
|
+
directive.
|
|
23
53
|
|
|
24
54
|
Supports comment styles::
|
|
25
55
|
|
|
@@ -42,36 +72,98 @@ def detect_loader_directive(conf: Any, current_ext: str) -> str:
|
|
|
42
72
|
The overriding extension string, or *current_ext* when no directive
|
|
43
73
|
is present.
|
|
44
74
|
"""
|
|
45
|
-
|
|
75
|
+
lines = _read_first_lines(conf)
|
|
76
|
+
if not lines:
|
|
46
77
|
return current_ext
|
|
47
78
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
79
|
+
for line in lines:
|
|
80
|
+
match = _LOADER_DIRECTIVE_RE.match(line)
|
|
81
|
+
if not match:
|
|
82
|
+
continue
|
|
51
83
|
|
|
52
|
-
|
|
53
|
-
first_line = path.read_text(errors="replace").split("\n", 1)[0]
|
|
54
|
-
except Exception:
|
|
55
|
-
return current_ext
|
|
84
|
+
directive = match.group(1).lower()
|
|
56
85
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
86
|
+
# Derive the base format name
|
|
87
|
+
# (strip any existing template suffix)
|
|
88
|
+
parts = current_ext.split(".")
|
|
89
|
+
base_ext = parts[0] if parts[-1] in ("j2", "liq") else current_ext
|
|
90
|
+
|
|
91
|
+
if directive in ("liq", "liquid"):
|
|
92
|
+
return base_ext + ".liq"
|
|
93
|
+
|
|
94
|
+
if directive in ("j2", "jinja", "jinja2"):
|
|
95
|
+
return base_ext + ".j2"
|
|
96
|
+
|
|
97
|
+
# Treat as an explicit loader extension name
|
|
98
|
+
return directive
|
|
99
|
+
|
|
100
|
+
return current_ext
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def detect_loadenv_directive(conf: Any) -> str | None:
|
|
104
|
+
"""Detect if the first few lines of a config file contain a loadenv
|
|
105
|
+
directive.
|
|
106
|
+
|
|
107
|
+
Supports both a bare directive (defaults to ``./.env``) and a path::
|
|
108
|
+
|
|
109
|
+
# simpleconf-loadenv
|
|
110
|
+
# simpleconf-loadenv: /path/to/.env
|
|
111
|
+
; simpleconf-loadenv: ../shared/.env
|
|
112
|
+
// simpleconf-loadenv
|
|
113
|
+
|
|
114
|
+
The path is resolved relative to the config file's directory.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
conf: The configuration source. Dicts and stream objects are
|
|
118
|
+
ignored (returns ``None``).
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
The absolute path to the ``.env`` file, or ``None`` when no
|
|
122
|
+
directive is present.
|
|
123
|
+
"""
|
|
124
|
+
lines = _read_first_lines(conf)
|
|
125
|
+
if not lines:
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
for line in lines:
|
|
129
|
+
match = _LOADENV_DIRECTIVE_RE.match(line)
|
|
130
|
+
if not match:
|
|
131
|
+
continue
|
|
132
|
+
|
|
133
|
+
raw_path = (match.group(1) or "").strip()
|
|
134
|
+
conf_dir = Path(conf).parent
|
|
60
135
|
|
|
61
|
-
|
|
136
|
+
if not raw_path:
|
|
137
|
+
return str(conf_dir.resolve() / ".env")
|
|
62
138
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
139
|
+
env_path = Path(raw_path)
|
|
140
|
+
if not env_path.is_absolute():
|
|
141
|
+
env_path = (conf_dir / env_path).resolve()
|
|
142
|
+
return str(env_path)
|
|
66
143
|
|
|
67
|
-
|
|
68
|
-
return base_ext + ".liq"
|
|
144
|
+
return None
|
|
69
145
|
|
|
70
|
-
if directive in ("j2", "jinja", "jinja2"):
|
|
71
|
-
return base_ext + ".j2"
|
|
72
146
|
|
|
73
|
-
|
|
74
|
-
|
|
147
|
+
def load_dotenv_file(env_path: str) -> Dict[str, str]:
|
|
148
|
+
"""Load environment variables from a ``.env`` file.
|
|
149
|
+
|
|
150
|
+
Uses ``python-dotenv`` to parse the file. Returns only the variables
|
|
151
|
+
defined in the file — does **not** modify ``os.environ``.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
env_path: Path to the ``.env`` file.
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
A dict of variable names to values. Returns an empty dict when
|
|
158
|
+
the file does not exist.
|
|
159
|
+
"""
|
|
160
|
+
dotenv = require_package("dotenv")
|
|
161
|
+
dotenv_file = Path(env_path)
|
|
162
|
+
if not dotenv_file.exists():
|
|
163
|
+
return {}
|
|
164
|
+
content = dotenv_file.read_text()
|
|
165
|
+
sio = io.StringIO(content)
|
|
166
|
+
return dict(dotenv.dotenv_values(stream=sio))
|
|
75
167
|
|
|
76
168
|
|
|
77
169
|
def config_to_ext(conf: Any, secondary: bool = True) -> str:
|
|
File without changes
|