envTOML 0.2.1__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.
envtoml/__init__.py ADDED
@@ -0,0 +1,104 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ import sys
7
+ from datetime import date, datetime, time
8
+ from typing import Any, BinaryIO, Callable, Dict, List, Match, Optional, Union
9
+
10
+ if sys.version_info >= (3, 11):
11
+ import tomllib
12
+ else: # pragma: no cover - fallback for Python < 3.11
13
+ import tomli as tomllib
14
+
15
+ __version__ = '0.2.1'
16
+
17
+ RE_ENV_VAR: str = r'\$([A-Z_][A-Z0-9_]+)'
18
+
19
+ TOMLDict = Dict[str, 'TOMLValue']
20
+ TOMLList = List['TOMLValue']
21
+ TOMLPrimitive = Union[str, int, float, bool, datetime, date, time]
22
+ TOMLValue = Union[TOMLPrimitive, TOMLDict, TOMLList]
23
+ ParseFloat = Callable[[str], float]
24
+
25
+
26
+ def env_replace(match: Match[str]) -> str:
27
+ env_var = match.group(1)
28
+ return os.environ.get(env_var, '')
29
+
30
+
31
+ def _load_inline_value(value: str, parse_float: ParseFloat) -> TOMLValue:
32
+ data = tomllib.loads(f'v = {value}', parse_float=parse_float)
33
+ return data['v']
34
+
35
+
36
+ def _replace_env_value(
37
+ value: str,
38
+ parse_float: ParseFloat,
39
+ ) -> Optional[TOMLValue]:
40
+ if not re.match(RE_ENV_VAR, value):
41
+ return None
42
+
43
+ replaced = re.sub(RE_ENV_VAR, env_replace, value)
44
+
45
+ # Try to parse the value as TOML (float, bool, inline table, etc.).
46
+ # If that fails, fall back to a basic string.
47
+ try:
48
+ return _load_inline_value(replaced, parse_float)
49
+ except tomllib.TOMLDecodeError:
50
+ quoted = json.dumps(replaced)
51
+ return _load_inline_value(quoted, parse_float)
52
+
53
+
54
+ def process(item: TOMLValue, parse_float: ParseFloat) -> None:
55
+ if isinstance(item, dict):
56
+ for key, val in item.items():
57
+ if isinstance(val, (dict, list)):
58
+ process(val, parse_float)
59
+ elif isinstance(val, str):
60
+ replaced = _replace_env_value(val, parse_float)
61
+ if replaced is not None:
62
+ item[key] = replaced
63
+ elif isinstance(item, list):
64
+ for index, val in enumerate(item):
65
+ if isinstance(val, (dict, list)):
66
+ process(val, parse_float)
67
+ elif isinstance(val, str):
68
+ replaced = _replace_env_value(val, parse_float)
69
+ if replaced is not None:
70
+ item[index] = replaced
71
+
72
+
73
+ def load(
74
+ fp: BinaryIO,
75
+ /,
76
+ *,
77
+ parse_float: ParseFloat = float,
78
+ ) -> dict[str, Any]:
79
+ """Parse TOML from a binary file object and replace environment variables.
80
+
81
+ Args:
82
+ fp: Binary file object to read.
83
+ parse_float: Callable to parse TOML float values.
84
+ """
85
+ data = tomllib.load(fp, parse_float=parse_float)
86
+ process(data, parse_float)
87
+ return data
88
+
89
+
90
+ def loads(
91
+ s: str,
92
+ /,
93
+ *,
94
+ parse_float: ParseFloat = float,
95
+ ) -> dict[str, Any]:
96
+ """Parse TOML from a string and replace environment variables.
97
+
98
+ Args:
99
+ s: TOML string to parse.
100
+ parse_float: Callable to parse TOML float values.
101
+ """
102
+ data = tomllib.loads(s, parse_float=parse_float)
103
+ process(data, parse_float)
104
+ return data
envtoml/py.typed ADDED
File without changes
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: envTOML
3
+ Version: 0.2.1
4
+ Summary: A simple way of using environment variables in TOML configs (via interpolation)
5
+ Project-URL: Repository, https://github.com/mrshu/envtoml
6
+ Author-email: "mr.Shu" <mr@shu.io>
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Keywords: TOML,config,environment,variables
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.8
23
+ Requires-Dist: tomli>=2.0; python_version < '3.11'
24
+ Description-Content-Type: text/x-rst
25
+
26
+ envTOML
27
+ =======
28
+
29
+ .. image:: https://img.shields.io/pypi/v/envtoml.svg
30
+ :target: https://pypi.python.org/pypi/envtoml
31
+ :alt: PyPI Status
32
+
33
+ .. image:: https://img.shields.io/pypi/pyversions/envtoml.svg
34
+ :target: https://pypi.python.org/pypi/envtoml
35
+ :alt: Python Versions
36
+
37
+ .. image:: https://img.shields.io/pypi/wheel/envtoml.svg
38
+ :target: https://pypi.python.org/pypi/envtoml
39
+ :alt: Wheel Status
40
+
41
+ .. image:: https://img.shields.io/pypi/dm/envtoml.svg
42
+ :target: https://pypi.python.org/pypi/envtoml
43
+ :alt: PyPI Downloads
44
+
45
+ .. image:: https://coveralls.io/repos/github/mrshu/envtoml/badge.svg?branch=master
46
+ :target: https://coveralls.io/github/mrshu/envtoml?branch=master
47
+ :alt: Code coverage Status
48
+
49
+ .. image:: https://img.shields.io/pypi/l/envtoml.svg
50
+ :target: ./LICENSE
51
+ :alt: License Status
52
+
53
+ ``envTOML`` is an answer to a fairly simple problem: including values from
54
+ environment variables in TOML configuration files. In this way, it is very
55
+ similar to both `envyaml <https://github.com/thesimj/envyaml>`_ and
56
+ `varyaml <https://github.com/abe-winter/varyaml>`_ which provide very
57
+ similar functionality for YAML and which greatly inspired this small
58
+ package.
59
+
60
+ Under the hood it uses the standard library ``tomllib`` (and ``tomli`` as a
61
+ fallback for Python < 3.11).
62
+
63
+ Example
64
+ -------
65
+
66
+ Suppose we have the following configuration saved in ``config.toml``
67
+
68
+ .. code:: toml
69
+
70
+ [db]
71
+ host = "$DB_HOST"
72
+ port = "$DB_PORT"
73
+ username = "$DB_USERNAME"
74
+ password = "$DB_PASSWORD"
75
+ name = "my_database"
76
+
77
+ with the environment variables being set to the following
78
+
79
+ .. code::
80
+
81
+ DB_HOST=some-host.tld
82
+ DB_PORT=3306
83
+ DB_USERNAME=user01
84
+ DB_PASSWORD=veryToughPas$w0rd
85
+
86
+ this config can then be parsed with ``envTOML`` in the following way:
87
+
88
+
89
+ .. code:: python
90
+
91
+ import envtoml
92
+
93
+ cfg = envtoml.load(open('./config.toml', 'rb'))
94
+
95
+ print(cfg)
96
+ # {'db': {'host': 'some-host.tld',
97
+ # 'port': 3306,
98
+ # 'username': 'user01',
99
+ # 'password': 'veryToughPas$w0rd',
100
+ # 'name': 'my_database'}}
101
+
102
+ Tests
103
+ -----
104
+
105
+ This project uses `uv <https://github.com/astral-sh/uv>`_. After installing it,
106
+ run the following from the project's root directory:
107
+
108
+ .. code:: bash
109
+
110
+ uv sync --group dev
111
+ uv run pytest
112
+
113
+ For coverage:
114
+
115
+ .. code:: bash
116
+
117
+ uv run pytest --cov=envtoml
118
+
119
+
120
+ License
121
+ -------
122
+
123
+ Licensed under the MIT license (see `LICENSE <./LICENSE>`_ file for more
124
+ details).
@@ -0,0 +1,6 @@
1
+ envtoml/__init__.py,sha256=D7CAJLiCnKt5IorC0KOmv8REfjpw_Gzv05iC35k97mk,2957
2
+ envtoml/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ envtoml-0.2.1.dist-info/METADATA,sha256=Gif0oqkB8zjvw_bb_dvLYWjyZbo0VCAipT0_h0QUiOs,3434
4
+ envtoml-0.2.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ envtoml-0.2.1.dist-info/licenses/LICENSE,sha256=t7ueYYR3D93iNvDVAAz3I5MI-TuywdhWvxInchEN5X0,1068
6
+ envtoml-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Marek Suppa
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 all
13
+ 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 THE
21
+ SOFTWARE.