python-simpleconf 0.9.1__py3-none-any.whl → 0.9.3__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,41 +1,38 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-simpleconf
3
- Version: 0.9.1
3
+ Version: 0.9.3
4
4
  Summary: Simple configuration management with python.
5
+ Project-URL: Homepage, https://github.com/pwwang/simpleconf
6
+ Project-URL: Repository, https://github.com/pwwang/simpleconf
7
+ Author-email: pwwang <pwwang@pwwang.com>
5
8
  License: MIT
6
9
  License-File: LICENSE
7
- Author: pwwang
8
- Author-email: pwwang@pwwang.com
9
- Requires-Python: >=3.9,<4.0
10
- Classifier: License :: OSI Approved :: MIT License
11
- Classifier: Programming Language :: Python :: 3
12
- Classifier: Programming Language :: Python :: 3.9
13
- Classifier: Programming Language :: Python :: 3.10
14
- Classifier: Programming Language :: Python :: 3.11
15
- Classifier: Programming Language :: Python :: 3.12
16
- Classifier: Programming Language :: Python :: 3.13
17
- Classifier: Programming Language :: Python :: 3.14
10
+ Requires-Python: >=3.9
11
+ Requires-Dist: diot<0.4,>=0.3.3
12
+ Requires-Dist: panpath<0.5,>=0.4.8
18
13
  Provides-Extra: all
14
+ Requires-Dist: iniconfig<3,>=2.0; extra == 'all'
15
+ Requires-Dist: python-dotenv<2,>=1.1; extra == 'all'
16
+ Requires-Dist: pyyaml<7,>=6; extra == 'all'
17
+ Requires-Dist: rtoml<0.13,>=0.12; (sys_platform == 'linux') and extra == 'all'
18
+ Requires-Dist: tomli<3,>=2.0; (sys_platform != 'linux') and extra == 'all'
19
19
  Provides-Extra: async
20
+ Requires-Dist: aiofiles>=23.0.0; extra == 'async'
20
21
  Provides-Extra: env
22
+ Requires-Dist: python-dotenv<2,>=1.1; extra == 'env'
21
23
  Provides-Extra: ini
24
+ Requires-Dist: iniconfig<3,>=2.0; extra == 'ini'
22
25
  Provides-Extra: jinja2
26
+ Requires-Dist: jinja2<4,>=3.0; extra == 'jinja2'
23
27
  Provides-Extra: liquid
28
+ Requires-Dist: liquidpy<0.9,>=0.8; extra == 'liquid'
24
29
  Provides-Extra: liquidpy
30
+ Requires-Dist: liquidpy<0.9,>=0.8; extra == 'liquidpy'
25
31
  Provides-Extra: toml
32
+ Requires-Dist: rtoml<0.13,>=0.12; (sys_platform == 'linux') and extra == 'toml'
33
+ Requires-Dist: tomli<3,>=2.0; (sys_platform != 'linux') and extra == 'toml'
26
34
  Provides-Extra: yaml
27
- Requires-Dist: aiofiles (>=23.0.0) ; extra == "async"
28
- Requires-Dist: diot (>=0.3.2,<0.4.0)
29
- Requires-Dist: iniconfig (>=2.0,<3.0) ; extra == "ini" or extra == "all"
30
- Requires-Dist: jinja2 (>=3.0,<4.0) ; extra == "jinja2"
31
- Requires-Dist: liquidpy (>=0.8,<0.9) ; extra == "liquid" or extra == "liquidpy"
32
- Requires-Dist: panpath (>=0.4.8,<0.5.0)
33
- Requires-Dist: python-dotenv (>=1.1,<2.0) ; extra == "env" or extra == "all"
34
- Requires-Dist: pyyaml (>=6,<7) ; extra == "yaml" or extra == "all"
35
- Requires-Dist: rtoml (>=0.12,<0.13) ; (sys_platform == "linux") and (extra == "toml" or extra == "all")
36
- Requires-Dist: tomli (>=2.0,<3.0) ; (sys_platform != "linux") and (extra == "toml" or extra == "all")
37
- Project-URL: Homepage, https://github.com/pwwang/simpleconf
38
- Project-URL: Repository, https://github.com/pwwang/simpleconf
35
+ Requires-Dist: pyyaml<7,>=6; extra == 'yaml'
39
36
  Description-Content-Type: text/markdown
40
37
 
41
38
  # simpleconf
@@ -350,4 +347,57 @@ conf = Config.load('config.liq.toml')
350
347
  # conf.section1.a == 1
351
348
  # conf.section2.a == 2
352
349
  ```
350
+ #### Loader directive in the first line
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.
353
+
354
+ The directive format is:
355
+
356
+ ```
357
+ # simpleconf-loader: <loader>
358
+ ```
359
+
360
+ Supported comment prefixes: `#`, `;`, `//` (case-insensitive).
361
+
362
+ The `<loader>` value can be:
363
+
364
+ | Value | Meaning |
365
+ |---|---|
366
+ | `liq` or `liquid` | Use the Liquid loader for this file's format |
367
+ | `j2`, `jinja`, or `jinja2` | Use the Jinja2 loader for this file's format |
368
+ | A full extension (e.g. `toml.liq`) | Use the exact loader specified |
369
+
370
+ **Example — Liquid in a plain `.toml` file:**
371
+
372
+ `config.toml`
373
+ ```toml
374
+ # simpleconf-loader: liq
375
+ {% set x = 10 %}
376
+ [default]
377
+ a = {{ 1 + 1 }}
378
+ b = {{ x + 2 }}
379
+ ```
380
+
381
+ ```python
382
+ from simpleconf import Config
383
+
384
+ conf = Config.load('config.toml')
385
+ # conf.default.a == 2
386
+ # conf.default.b == 12
387
+ ```
388
+
389
+ **Example — Jinja2 in a plain `.yaml` file:**
390
+
391
+ `config.yaml`
392
+ ```yaml
393
+ # simpleconf-loader: j2
394
+ default:
395
+ a: {{ 1 + 1 }}
396
+ ```
397
+
398
+ ```python
399
+ from simpleconf import Config
353
400
 
401
+ conf = Config.load('config.yaml')
402
+ # conf.default.a == 2
403
+ ```
@@ -0,0 +1,18 @@
1
+ simpleconf/__init__.py,sha256=V3G4vrJauZva5CUPH--DkZnsBFdLNcpumcK5qu27o24,104
2
+ simpleconf/caster.py,sha256=qHnegp1FZzbUWm-UbCaGjQKN6d9rN1v_0Wa4I_CMEi4,2379
3
+ simpleconf/config.py,sha256=B6h-mgeiyI7op-R-i1C_z0oyc4pt7Tv7zKWgzsDy4xw,17922
4
+ simpleconf/exceptions.py,sha256=Tb7w9gMO2XU4mE-Rc2HAnuHWDUpMzdl39oGVjeAv254,171
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
8
+ simpleconf/loaders/dict.py,sha256=8Az511i9OLLXosSBMMXiEfiQVScQ5SIqsF6EHlAkKdM,801
9
+ simpleconf/loaders/env.py,sha256=cOYZbHk08MrBjxtNfV8Cv5LHrZg_flzap1lOM3GVdRk,3729
10
+ simpleconf/loaders/ini.py,sha256=a8ahJIzw24SIEnGbZmYNoxo8O1tYi6pG_GrOil0Rcx0,3739
11
+ simpleconf/loaders/json.py,sha256=0NTKB9JidB8vbeODxNYAY8fJP6__znetuIUAClFeNIo,1929
12
+ simpleconf/loaders/osenv.py,sha256=K829KFiHLl3pS8HSCep8JoPVG_d7VRxPAb7SPYFRypg,1779
13
+ simpleconf/loaders/toml.py,sha256=OJCukg_R3zlmas_q_CrdeKUsw8Wj5LoSnkNJ7Flt86w,2525
14
+ simpleconf/loaders/yaml.py,sha256=IoKMaQF5y5HWEjQsnUwL2UvABVj9A-0AmBhn8s7lE54,2146
15
+ python_simpleconf-0.9.3.dist-info/METADATA,sha256=LCMMZMyXDzmxBZsNsQGETPRJIzhOeu1-uZUo7mDV-SY,8947
16
+ python_simpleconf-0.9.3.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
17
+ python_simpleconf-0.9.3.dist-info/licenses/LICENSE,sha256=2j7OLS2vXIEshgbSkiCU9RgYJY1M4OBBtO6ECbo7OB8,1056
18
+ python_simpleconf-0.9.3.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 2.3.1
2
+ Generator: hatchling 1.29.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
simpleconf/__init__.py CHANGED
@@ -1,3 +1,5 @@
1
1
  from .config import Config, ProfileConfig
2
2
 
3
- __version__ = "0.9.1"
3
+ __all__ = ["Config", "ProfileConfig"]
4
+
5
+ __version__ = "0.9.3"
simpleconf/config.py CHANGED
@@ -5,7 +5,7 @@ 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, get_loader, POOL_KEY, META_KEY
8
+ from .utils import config_to_ext, detect_loader_directive, get_loader, POOL_KEY, META_KEY
9
9
  from .loaders import Loader
10
10
 
11
11
  LoaderType = Union[str, Loader, None]
@@ -116,6 +116,7 @@ class Config:
116
116
  raise ValueError("'loader' must be specified for stream")
117
117
 
118
118
  ext = config_to_ext(config)
119
+ ext = detect_loader_directive(config, ext)
119
120
  loader = get_loader(ext)
120
121
  else:
121
122
  loader = get_loader(loader)
@@ -145,6 +146,7 @@ class Config:
145
146
  raise ValueError("'loader' must be specified for stream")
146
147
 
147
148
  ext = config_to_ext(config)
149
+ ext = detect_loader_directive(config, ext)
148
150
  loader = get_loader(ext)
149
151
  else:
150
152
  loader = get_loader(loader)
@@ -202,6 +204,7 @@ class ProfileConfig:
202
204
 
203
205
  if lder is None:
204
206
  ext = config_to_ext(conf)
207
+ ext = detect_loader_directive(conf, ext)
205
208
  lder = get_loader(ext)
206
209
  else:
207
210
  lder = get_loader(lder)
@@ -271,6 +274,7 @@ class ProfileConfig:
271
274
 
272
275
  if lder is None:
273
276
  ext = config_to_ext(conf)
277
+ ext = detect_loader_directive(conf, ext)
274
278
  lder = get_loader(ext)
275
279
  else:
276
280
  lder = get_loader(lder)
@@ -323,6 +327,7 @@ class ProfileConfig:
323
327
  raise ValueError("'loader' must be specified for stream")
324
328
 
325
329
  ext = config_to_ext(conf)
330
+ ext = detect_loader_directive(conf, ext)
326
331
  loader = get_loader(ext)
327
332
  else:
328
333
  loader = get_loader(loader)
@@ -378,6 +383,7 @@ class ProfileConfig:
378
383
  raise ValueError("'loader' must be specified for stream")
379
384
 
380
385
  ext = config_to_ext(conf)
386
+ ext = detect_loader_directive(conf, ext)
381
387
  loader = get_loader(ext)
382
388
  else:
383
389
  loader = get_loader(loader)
@@ -148,7 +148,7 @@ class J2ModifierMixin(LoaderModifierMixin):
148
148
  def _modifier(self, content: str | bytes) -> str | bytes:
149
149
  """Modify the content of the configuration file before loading"""
150
150
  from jinja2 import Template
151
- return Template(content).render()
151
+ return Template(content).render() # type: ignore
152
152
 
153
153
 
154
154
  class LiqModifierMixin(LoaderModifierMixin):
@@ -156,5 +156,7 @@ class LiqModifierMixin(LoaderModifierMixin):
156
156
 
157
157
  def _modifier(self, content: str | bytes) -> str | bytes:
158
158
  """Modify the content of the configuration file before loading"""
159
- from liquid import Liquid
160
- return Liquid(content, from_file=False, mode="wild").render()
159
+ from liquid import Liquid # type: ignore[import]
160
+ str_content = content.decode() if isinstance(content, bytes) else content
161
+ liq = Liquid(str_content, from_file=False, mode="wild") # type: ignore
162
+ return liq.render()
@@ -7,7 +7,7 @@ class DictLoader(Loader):
7
7
  """Dict loader"""
8
8
 
9
9
  @staticmethod
10
- def _convert_path(conf):
10
+ def _convert_path(conf: Any) -> Any: # type: ignore[override]
11
11
  return conf
12
12
 
13
13
  def loading(self, conf: Any, ignore_nonexist: bool) -> Dict[str, Any]:
simpleconf/loaders/env.py CHANGED
@@ -45,15 +45,19 @@ class EnvLoader(Loader, LoaderModifierMixin):
45
45
  """Load the configuration from a .env file"""
46
46
  if hasattr(conf, "read"):
47
47
  content = conf.read()
48
- return dotenv.dotenv_values(stream=io.StringIO(content))
48
+ str_content = content.decode() if isinstance(content, bytes) else content
49
+ sio = io.StringIO(str_content) # type: ignore[arg-type]
50
+ return dotenv.dotenv_values(stream=sio)
49
51
 
50
52
  if not self._exists(conf, ignore_nonexist):
51
53
  return {}
52
54
 
53
55
  conf = self.__class__._convert_path(conf)
54
56
  content = conf.read_text() # so that cloud paths work
55
- content = self._modifier(content)
56
- return dotenv.dotenv_values(stream=io.StringIO(content))
57
+ modified = self._modifier(content)
58
+ str_modified = modified.decode() if isinstance(modified, bytes) else modified
59
+ sio = io.StringIO(str_modified) # type: ignore[arg-type]
60
+ return dotenv.dotenv_values(stream=sio)
57
61
 
58
62
  async def a_loading(self, conf, ignore_nonexist):
59
63
  """Asynchronously load the configuration from a .env file"""
@@ -63,16 +67,21 @@ class EnvLoader(Loader, LoaderModifierMixin):
63
67
  content = await content
64
68
  if isinstance(content, bytes):
65
69
  content = content.decode()
66
- content = self._modifier(content)
67
- return dotenv.dotenv_values(stream=io.StringIO(content))
70
+ modified = self._modifier(content)
71
+ str_modified = modified.decode() if isinstance(modified, bytes) else modified
72
+ sio = io.StringIO(str_modified) # type: ignore[arg-type]
73
+ return dotenv.dotenv_values(stream=sio)
68
74
 
69
75
  if not await self._a_exists(conf, ignore_nonexist):
70
76
  return {}
71
77
 
72
78
  conf = self.__class__._convert_path(conf)
73
- content = await conf.a_read_text() # so that cloud paths work
74
- content = self._modifier(content)
75
- return dotenv.dotenv_values(stream=io.StringIO(content))
79
+ # so that cloud paths work
80
+ content = await conf.a_read_text() # type: ignore[attr-defined]
81
+ modified = self._modifier(content)
82
+ str_modified = modified.decode() if isinstance(modified, bytes) else modified
83
+ sio = io.StringIO(str_modified) # type: ignore[arg-type]
84
+ return dotenv.dotenv_values(stream=sio)
76
85
 
77
86
  @classmethod
78
87
  def _convert_with_profiles( # type: ignore[override]
@@ -89,7 +98,7 @@ class EnvLoader(Loader, LoaderModifierMixin):
89
98
  profile = profile.lower()
90
99
  out.setdefault(profile, Diot())[key] = v
91
100
 
92
- return cast(out, cls.CASTERS)
101
+ return cast(out, cls.CASTERS or [])
93
102
 
94
103
 
95
104
  class EnvsLoader(NoConvertingPathMixin, EnvLoader): # type: ignore[misc]
simpleconf/loaders/ini.py CHANGED
@@ -99,7 +99,7 @@ class IniLoader(Loader, LoaderModifierMixin):
99
99
  if len(keys) == 0 or keys[0].lower() != "default":
100
100
  raise ValueError(f"{pathname}: Only the default section can be loaded.")
101
101
 
102
- return cast(Diot(loaded[keys[0]]), cls.CASTERS)
102
+ return cast(Diot(loaded[keys[0]]), cls.CASTERS or [])
103
103
 
104
104
  @classmethod
105
105
  def _convert_with_profiles( # type: ignore[override]
@@ -109,7 +109,7 @@ class IniLoader(Loader, LoaderModifierMixin):
109
109
  ) -> Diot:
110
110
  out = Diot()
111
111
  for k, v in loaded.items():
112
- out[k.lower()] = cast(v, cls.CASTERS)
112
+ out[k.lower()] = cast(v, cls.CASTERS or [])
113
113
  return out
114
114
 
115
115
 
simpleconf/utils.py CHANGED
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import re
3
4
  from pathlib import Path
4
5
  from importlib import import_module
5
6
  from types import ModuleType
@@ -11,6 +12,67 @@ from .loaders import Loader
11
12
  POOL_KEY = "_SIMPLECONF_POOL"
12
13
  META_KEY = "_SIMPLECONF_META"
13
14
 
15
+ _LOADER_DIRECTIVE_RE = re.compile(
16
+ r"^\s*(?:#|;|//)\s*simpleconf-loader:\s*(\S+)",
17
+ re.IGNORECASE,
18
+ )
19
+
20
+
21
+ def detect_loader_directive(conf: Any, current_ext: str) -> str:
22
+ """Detect if the first line of a config file contains a loader directive.
23
+
24
+ Supports comment styles::
25
+
26
+ # simpleconf-loader: toml.liq
27
+ # simpleconf-loader: liq
28
+ # simpleconf-loader: liquid
29
+ ; simpleconf-loader: ini.liq
30
+ // simpleconf-loader: json.j2
31
+
32
+ Short aliases ``liq``/``liquid`` and ``j2``/``jinja``/``jinja2`` are
33
+ expanded relative to the base format of *current_ext*.
34
+ Any other value is used verbatim as the loader extension.
35
+
36
+ Args:
37
+ conf: The configuration source. Dicts and stream objects are
38
+ ignored (returns *current_ext* unchanged).
39
+ current_ext: The extension string already derived from the filename.
40
+
41
+ Returns:
42
+ The overriding extension string, or *current_ext* when no directive
43
+ is present.
44
+ """
45
+ if isinstance(conf, dict) or hasattr(conf, "read"):
46
+ return current_ext
47
+
48
+ path = Path(conf)
49
+ if not path.exists():
50
+ return current_ext
51
+
52
+ try:
53
+ first_line = path.read_text(errors="replace").split("\n", 1)[0]
54
+ except Exception:
55
+ return current_ext
56
+
57
+ match = _LOADER_DIRECTIVE_RE.match(first_line)
58
+ if not match:
59
+ return current_ext
60
+
61
+ directive = match.group(1).lower()
62
+
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
66
+
67
+ if directive in ("liq", "liquid"):
68
+ return base_ext + ".liq"
69
+
70
+ if directive in ("j2", "jinja", "jinja2"):
71
+ return base_ext + ".j2"
72
+
73
+ # Treat as an explicit loader extension name
74
+ return directive
75
+
14
76
 
15
77
  def config_to_ext(conf: Any, secondary: bool = True) -> str:
16
78
  """Find the extension(flag) of the configuration"""
@@ -1,18 +0,0 @@
1
- simpleconf/__init__.py,sha256=2oS2zzmxaXtJ5EjB9zFEa3id6iqorLBXZNxijkgzOog,65
2
- simpleconf/caster.py,sha256=qHnegp1FZzbUWm-UbCaGjQKN6d9rN1v_0Wa4I_CMEi4,2379
3
- simpleconf/config.py,sha256=GpQXxehF6p8hPpX1quy0HmIl1X3nnhG3eetPFaKASRY,17567
4
- simpleconf/exceptions.py,sha256=Tb7w9gMO2XU4mE-Rc2HAnuHWDUpMzdl39oGVjeAv254,171
5
- simpleconf/loaders/__init__.py,sha256=aEWpcrtkpJRuHhobhOZci864vi8f_rIGubgTVOxmvuY,5322
6
- simpleconf/loaders/dict.py,sha256=uGY0ufQFwcEinSUFyNSb96RDgynm6tHW5fcEdc-A0Sc,763
7
- simpleconf/loaders/env.py,sha256=7jwh3TCxxdmJNROSBcGyb9muNC6BZ-rEGi0tznhHSnM,3132
8
- simpleconf/loaders/ini.py,sha256=PweI85VoTgN5IA4uQUdYZNKP9r0iCna5hb0smsG7_kg,3727
9
- simpleconf/loaders/json.py,sha256=0NTKB9JidB8vbeODxNYAY8fJP6__znetuIUAClFeNIo,1929
10
- simpleconf/loaders/osenv.py,sha256=K829KFiHLl3pS8HSCep8JoPVG_d7VRxPAb7SPYFRypg,1779
11
- simpleconf/loaders/toml.py,sha256=OJCukg_R3zlmas_q_CrdeKUsw8Wj5LoSnkNJ7Flt86w,2525
12
- simpleconf/loaders/yaml.py,sha256=IoKMaQF5y5HWEjQsnUwL2UvABVj9A-0AmBhn8s7lE54,2146
13
- simpleconf/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
- simpleconf/utils.py,sha256=XKE2fi-jKuqbxkgB_3_usdhc6kkUfj37JeJHNSWPuj8,4414
15
- python_simpleconf-0.9.1.dist-info/METADATA,sha256=poHLSqB6pyAFQgDK9buaGibbSo5DR5Sq-0e90bBwX1U,7979
16
- python_simpleconf-0.9.1.dist-info/WHEEL,sha256=kJCRJT_g0adfAJzTx2GUMmS80rTJIVHRCfG0DQgLq3o,88
17
- python_simpleconf-0.9.1.dist-info/licenses/LICENSE,sha256=2j7OLS2vXIEshgbSkiCU9RgYJY1M4OBBtO6ECbo7OB8,1056
18
- python_simpleconf-0.9.1.dist-info/RECORD,,