envkeep 0.1.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.
envkeep/yamlutil.py ADDED
@@ -0,0 +1,101 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Hashable
4
+ from typing import Any
5
+
6
+ import yaml
7
+
8
+ _MERGE_TAG = "tag:yaml.org,2002:merge"
9
+
10
+
11
+ class YamlSyntaxError(ValueError):
12
+ """The text isn't valid YAML. The message gives a position, never source text."""
13
+
14
+
15
+ class _DuplicateKeyError(yaml.YAMLError):
16
+ """A mapping key was written twice. Carries only a position, never the key text."""
17
+
18
+ def __init__(self, line: int, column: int) -> None:
19
+ super().__init__("duplicate key")
20
+ self.line = line
21
+ self.column = column
22
+
23
+
24
+ def _describe_syntax_error(exc: yaml.YAMLError) -> str:
25
+ """Describe a YAML error by position only, never by source text.
26
+
27
+ PyYAML's own message embeds the offending source line, which could be a secret.
28
+ """
29
+ mark = getattr(exc, "problem_mark", None) or getattr(exc, "context_mark", None)
30
+ if mark is None:
31
+ return "invalid YAML syntax"
32
+ return f"invalid YAML syntax at line {mark.line + 1}, column {mark.column + 1}"
33
+
34
+
35
+ class _UniqueKeyLoader(yaml.SafeLoader):
36
+ """A SafeLoader that rejects duplicate keys instead of silently keeping the last."""
37
+
38
+ def get_single_data(self):
39
+ node = self.get_single_node()
40
+ if node is None:
41
+ return None
42
+ self._reject_duplicate_keys(node)
43
+ return self.construct_document(node)
44
+
45
+ def _reject_duplicate_keys(self, root: yaml.Node) -> None:
46
+ """Check every mapping in the document for repeated keys.
47
+
48
+ This runs on the raw node tree BEFORE PyYAML constructs anything, for two reasons:
49
+ PyYAML never constructs a "<<" merge source as a mapping of its own (it copies its
50
+ entries into the parent), and it rewrites nodes in place while flattening merges,
51
+ which would make a legitimate override look like a duplicate. Each mapping's own
52
+ explicit keys are compared only with each other, so an explicit key may still
53
+ override a merged one. Iterative, and each shared node is visited once.
54
+ """
55
+ visited: set[int] = set()
56
+ stack: list[yaml.Node] = [root]
57
+ while stack:
58
+ node = stack.pop()
59
+ if id(node) in visited:
60
+ continue
61
+ visited.add(id(node))
62
+
63
+ if isinstance(node, yaml.SequenceNode):
64
+ stack.extend(reversed(node.value)) # reversed: report the earliest first
65
+ elif isinstance(node, yaml.MappingNode):
66
+ seen: set[Hashable] = set()
67
+ children: list[yaml.Node] = []
68
+ for key_node, value_node in node.value:
69
+ children.append(value_node) # merge sources are checked too
70
+ if key_node.tag == _MERGE_TAG:
71
+ continue # a merge key is not a regular key
72
+ key = self.construct_object(key_node, deep=True)
73
+ if not isinstance(key, Hashable):
74
+ continue # PyYAML reports unhashable keys itself
75
+ if key in seen:
76
+ mark = key_node.start_mark
77
+ raise _DuplicateKeyError(mark.line + 1, mark.column + 1)
78
+ seen.add(key)
79
+ stack.extend(reversed(children))
80
+
81
+
82
+ def load_yaml(text: str) -> Any:
83
+ """Parse YAML text safely. Raises YamlSyntaxError with a position-only message."""
84
+ try:
85
+ # A SafeLoader subclass: never builds arbitrary Python objects,
86
+ # and rejects duplicate keys at every level, including inside merge sources.
87
+ return yaml.load(text, Loader=_UniqueKeyLoader) # noqa: S506
88
+ except _DuplicateKeyError as exc:
89
+ raise YamlSyntaxError(
90
+ f"invalid YAML: duplicate key at line {exc.line}, column {exc.column}"
91
+ ) from None
92
+ except yaml.YAMLError as exc:
93
+ raise YamlSyntaxError(_describe_syntax_error(exc)) from None
94
+ except (ValueError, TypeError, OverflowError, RecursionError, MemoryError):
95
+ # A scalar that looks like a typed value but isn't one (for example the date
96
+ # 2020-13-45), or a document too deeply nested to read. The original message is
97
+ # deliberately dropped: it is not part of our contract and could carry file text.
98
+ raise YamlSyntaxError(
99
+ "invalid YAML: a value could not be read "
100
+ "(for example an impossible date, or nesting that is too deep)"
101
+ ) from None
@@ -0,0 +1,273 @@
1
+ Metadata-Version: 2.5
2
+ Name: envkeep
3
+ Version: 0.1.1
4
+ Summary: Check, sync, and document your .env files against .env.example
5
+ Project-URL: Homepage, https://github.com/Avishka14/envkeep
6
+ Project-URL: Issues, https://github.com/Avishka14/envkeep/issues
7
+ Project-URL: Changelog, https://github.com/Avishka14/envkeep/blob/main/CHANGELOG.md
8
+ Author: Avishka Chamod
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: cli,devops,docker,docker-compose,dotenv,env,environment-variables
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
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 :: Quality Assurance
22
+ Classifier: Topic :: Utilities
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: python-dotenv>=1.0
25
+ Requires-Dist: pyyaml>=6
26
+ Requires-Dist: rich>=13
27
+ Requires-Dist: typer>=0.12
28
+ Provides-Extra: dev
29
+ Requires-Dist: build; extra == 'dev'
30
+ Requires-Dist: pytest; extra == 'dev'
31
+ Requires-Dist: ruff; extra == 'dev'
32
+ Requires-Dist: twine; extra == 'dev'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # envkeep
36
+
37
+ [![CI](https://github.com/Avishka14/envkeep/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/Avishka14/envkeep/actions/workflows/ci.yml)
38
+ [![PyPI](https://img.shields.io/pypi/v/envkeep)](https://pypi.org/project/envkeep/)
39
+ [![Python](https://img.shields.io/pypi/pyversions/envkeep)](https://pypi.org/project/envkeep/)
40
+ [![License: MIT](https://img.shields.io/github/license/Avishka14/envkeep)](https://github.com/Avishka14/envkeep/blob/main/LICENSE)
41
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
42
+
43
+ **Keep your `.env` files in sync with `.env.example`, and catch undefined Docker Compose variables before they break your deploy.**
44
+
45
+ envkeep treats your `.env.example` (or a small schema file) as the source of truth. It checks your real `.env` for missing, empty, and invalid variables, syncs and generates example files without touching your existing values, compares environments, and scans `docker-compose.yml` for `${VAR}` references that are never defined. Every command uses exit codes, so it drops straight into CI and pre-commit hooks.
46
+
47
+ ## Contents
48
+
49
+ - [Install](#install)
50
+ - [Quick start](#quick-start)
51
+ - [Commands](#commands)
52
+ - [Schema file](#schema-file)
53
+ - [Exit codes](#exit-codes)
54
+ - [Use it in CI](#use-it-in-ci)
55
+ - [Privacy](#privacy)
56
+ - [Development](#development)
57
+ - [License](#license)
58
+
59
+ ## Install
60
+
61
+ Requires Python 3.10 or newer. This installs the `envkeep` command.
62
+
63
+ ```bash
64
+ pip install envkeep
65
+ ```
66
+
67
+ Or, to keep it out of your project's environment:
68
+
69
+ ```bash
70
+ pipx install envkeep
71
+ ```
72
+
73
+ From source:
74
+
75
+ ```bash
76
+ pip install git+https://github.com/Avishka14/envkeep.git
77
+ ```
78
+
79
+ ## Quick start
80
+
81
+ ```bash
82
+ envkeep check # compare .env against .env.example
83
+ envkeep sync # add any missing variables to .env
84
+ envkeep compose # find undefined variables in docker-compose.yml
85
+ ```
86
+
87
+ ## Commands
88
+
89
+ | Command | What it does |
90
+ |---|---|
91
+ | `envkeep check` | Compares `.env` to `.env.example` (or an `envkeep.yml` schema). Reports missing, empty, invalid, and extra variables. |
92
+ | `envkeep generate` | Builds `.env.example` from `.env`, stripping values and keeping comments. |
93
+ | `envkeep sync` | Adds variables that exist in `.env.example` but not in `.env`. Never changes existing values. |
94
+ | `envkeep diff A B` | Shows differences between two env files, for example dev and staging. |
95
+ | `envkeep compose` | Finds `${VAR}` references and `env_file:` entries in a Compose file that are undefined or missing. |
96
+
97
+ Run `envkeep <command> --help` for every option.
98
+
99
+ ### check
100
+
101
+ ```bash
102
+ envkeep check --env .env --example .env.example
103
+ envkeep check --env .env --schema envkeep.yml
104
+ ```
105
+
106
+ ```text
107
+ tests/fixtures/dev.env vs tests/fixtures/example.env
108
+ ┏━━━━━━━━━┳━━━━━━━━━━━━┓
109
+ ┃ Status ┃ Variable ┃
110
+ ┡━━━━━━━━━╇━━━━━━━━━━━━┩
111
+ │ missing │ SECRET_KEY │
112
+ │ empty │ PORT │
113
+ │ extra │ REDIS_URL │
114
+ └─────────┴────────────┘
115
+ FAILED 1 missing, 1 empty, 1 extra
116
+ ```
117
+
118
+ Missing and empty variables fail the check. Extra variables (in `.env` but not in the example) are warnings only.
119
+
120
+ ### generate
121
+
122
+ ```bash
123
+ envkeep generate --env .env --output .env.example
124
+ ```
125
+
126
+ Keeps comments, blank lines, key order, and `export` prefixes. Values are removed, or replaced with `--placeholder`. It refuses to overwrite an existing file without `--force`, and refuses outright if the input and output are the same file.
127
+
128
+ ### sync
129
+
130
+ ```bash
131
+ envkeep sync --dry-run # show what would be added
132
+ envkeep sync # add it
133
+ ```
134
+
135
+ `sync` only appends, so existing lines, comments, and values are never modified. Line endings (LF or CRLF) are preserved, and the file is replaced atomically, so a failed write can't leave a half-written `.env`.
136
+
137
+ ### diff
138
+
139
+ ```bash
140
+ envkeep diff dev.env staging.env
141
+ envkeep diff dev.env staging.env --keys-only
142
+ ```
143
+
144
+ Values are hidden by default because they may be secrets. Use `--show-values` to see them, or `--keys-only` to compare just which variables exist.
145
+
146
+ ### compose
147
+
148
+ ```bash
149
+ envkeep compose # finds compose.yaml / docker-compose.yml
150
+ envkeep compose docker-compose.yml --env .env.production
151
+ envkeep compose --shell-env # also count variables set in your shell
152
+ ```
153
+
154
+ ```text
155
+ examples/compose.yaml
156
+ ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
157
+ ┃ Status ┃ Name ┃ Where ┃
158
+ ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
159
+ │ undefined │ DB_PASSWORD │ services.db.environment.POSTGRES_… │
160
+ │ empty │ SECRET_KEY │ services.web.environment.SECRET_KEY │
161
+ │ missing file │ ./secrets.env │ services.db.env_file │
162
+ │ missing file │ ./web.env │ services.web.env_file │
163
+ └──────────────┴───────────────┴─────────────────────────────────────┘
164
+ FAILED 1 undefined, 1 empty, 2 missing env_file (1 with defaults)
165
+ ```
166
+
167
+ envkeep follows Compose's interpolation rules:
168
+
169
+ | Syntax | Reported when |
170
+ |---|---|
171
+ | `$VAR`, `${VAR}` | The variable is undefined |
172
+ | `${VAR:?msg}` | Undefined, or defined but empty |
173
+ | `${VAR?msg}` | Undefined (empty is accepted) |
174
+ | `${VAR:-x}`, `${VAR-x}`, `${VAR:+x}`, `${VAR+x}` | Never (counted as optional) |
175
+ | `env_file:` entry | The file is missing (unless `required: false`) |
176
+
177
+ Variables in an `env_file` path are expanded first. If one is undefined, that variable is reported instead of the file. Nested expressions such as `${IMAGE:-${FALLBACK:?set FALLBACK}}` are evaluated only when their branch is active. Values are never printed.
178
+
179
+ ## Schema file
180
+
181
+ A schema adds types and rules. Pass it with `--schema`:
182
+
183
+ ```yaml
184
+ # envkeep.yml
185
+ variables:
186
+ DATABASE_URL:
187
+ type: url # str (default), int, float, bool, url
188
+ PORT:
189
+ type: int
190
+ default: 8000 # has a default, so it may be missing or empty
191
+ DEBUG:
192
+ type: bool
193
+ default: false
194
+ SECRET_KEY: # no rules: a required string
195
+ REDIS_URL:
196
+ type: url
197
+ required: false # optional: may be missing or empty
198
+ ```
199
+
200
+ A variable is required unless it has a `default` or `required: false`. Typos in rule names, unknown types, duplicate keys, and contradictory rules are rejected with a clear message.
201
+
202
+ ## Exit codes
203
+
204
+ | Code | Meaning |
205
+ |---|---|
206
+ | 0 | Everything is fine |
207
+ | 1 | A check failed: missing, empty, or invalid variables, files that differ, or undefined Compose variables |
208
+ | 2 | Usage error: a file is missing or unreadable, a file can't be parsed, or the output would overwrite something |
209
+
210
+ ## Use it in CI
211
+
212
+ Save this as `.github/workflows/env.yml` in your project:
213
+
214
+ ```yaml
215
+ name: env
216
+
217
+ on:
218
+ push:
219
+ pull_request:
220
+
221
+ permissions:
222
+ contents: read
223
+
224
+ jobs:
225
+ check:
226
+ runs-on: ubuntu-latest
227
+ steps:
228
+ - uses: actions/checkout@v4
229
+ - uses: actions/setup-python@v5
230
+ with:
231
+ python-version: "3.13"
232
+ - run: pip install envkeep
233
+ - run: envkeep check --env .env.ci --example .env.example
234
+ - run: envkeep compose docker-compose.yml --env .env.ci
235
+ ```
236
+
237
+ `.env.ci` is a committed env file with safe, non-secret values for CI. Never commit a real `.env`.
238
+ The job fails when a variable is missing, empty, or invalid, because envkeep exits with code 1.
239
+
240
+ ## Privacy
241
+
242
+ envkeep never prints variable values by default, in `check`, `diff`, `compose`, or error messages. YAML errors report a line and column, never the source text.
243
+
244
+ ## Development
245
+
246
+ ```bash
247
+ git clone https://github.com/Avishka14/envkeep
248
+ cd envkeep
249
+ python -m venv .venv
250
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
251
+ pip install -e ".[dev]"
252
+ pytest
253
+ ruff check . && ruff format --check .
254
+ ```
255
+
256
+ CI runs the tests on Linux and Windows (Python 3.10 to 3.13), the linter, a package build check, and a run against the oldest supported dependency versions.
257
+
258
+ ### Releasing
259
+
260
+ 1. Bump `version` in `pyproject.toml` and add an entry to `CHANGELOG.md`.
261
+ 2. Merge the change into `main`.
262
+ 3. Tag the release from `main` and push the tag:
263
+
264
+ ```bash
265
+ git tag -a v0.1.1 -m "envkeep 0.1.1"
266
+ git push origin v0.1.1
267
+ ```
268
+
269
+ The release workflow checks that the tag matches the version, builds the package, publishes it to TestPyPI, waits for a maintainer's approval, publishes it to PyPI, and then creates the GitHub release. Publishing uses PyPI trusted publishing, so no API token is stored anywhere.
270
+
271
+ ## License
272
+
273
+ MIT. See [LICENSE](https://github.com/Avishka14/envkeep/blob/main/LICENSE).
@@ -0,0 +1,21 @@
1
+ envkeep/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ envkeep/checks.py,sha256=ZOQkZ15gfKp6iOfs5spU9nWKkJz1_bKj-RhgbX_eNzE,1661
3
+ envkeep/cli.py,sha256=VTUz8fHVJEKhI_TCm4ZmMMrJ06ZT3ZPeoAI_Gre1uEw,9626
4
+ envkeep/compare.py,sha256=cLLCwjst8Zc7OnAZg-WnNJOWS0O-p28GcA5bt_CAoHc,445
5
+ envkeep/compose.py,sha256=M3BdzAP8UQuDLe1ypjmFJQvLHVIBk-9_AAgN9BlLEGw,6114
6
+ envkeep/differ.py,sha256=VPFvCTHTI5Bw3OercEs3viS5Uj-Jws0eqAOcg8YejEk,880
7
+ envkeep/fileio.py,sha256=GQdYUUn3k4sAVQjpSUrH2YfhgCSZ6IIPw7k7B1Fgphg,1233
8
+ envkeep/generator.py,sha256=6uSIqr94LjhkGWDyGgUWVGjcGI8zifYy3DyUCV0go-g,863
9
+ envkeep/interpolate.py,sha256=y5o5sHKUu_CiG8pzS-jBBpFyaD0D-zQb8w01n1VfdpI,4806
10
+ envkeep/models.py,sha256=9fh6S8i5tQJD72h-ng8Uy3cwELSnj9m4LRRDkCIDU_4,585
11
+ envkeep/output.py,sha256=QCwP3S5WCWkQmnQi138LHY6u5Ykzo4u7tIfq-hu4OQM,6025
12
+ envkeep/parser.py,sha256=uC2ESUEFtf86lYL6IlIMLSwZk7j44AkUx6P_oXExkGQ,4041
13
+ envkeep/schema.py,sha256=BAnMbfqT9kPHWdViQ0GG-cjXFcxzDDZr8-ZlX33dTVY,4460
14
+ envkeep/syncer.py,sha256=sF9GrYf-LBA4zj7GkoBy0tc6k8WFqKHo-PvlVdV0NWk,1531
15
+ envkeep/validate.py,sha256=lKPnqLDh0rv8Z6EtYg97wThCtaYxfN3wiqVIfUsNdcI,1263
16
+ envkeep/yamlutil.py,sha256=_vMsjq20Qsv51koAaHbAvl0j-QuhNWgSAMzynzejl5g,4382
17
+ envkeep-0.1.1.dist-info/METADATA,sha256=Cqzl7gAQ52I-c-eXdY3Z-S7Zvep2EpLu4tEbGZWK1cI,10447
18
+ envkeep-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
19
+ envkeep-0.1.1.dist-info/entry_points.txt,sha256=Z55IYwlG0FEriM0Hc9CL6WrSJsPfpZB4uzcUl80aNqk,44
20
+ envkeep-0.1.1.dist-info/licenses/LICENSE,sha256=9cA-amp_5IsfwPwzJpTQ2suijXl45N7df8TBq6mZFRA,1070
21
+ envkeep-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ envkeep = envkeep.cli:app
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Avishka Chamod
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.