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/__init__.py ADDED
File without changes
envkeep/checks.py ADDED
@@ -0,0 +1,64 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from urllib.parse import urlsplit
5
+
6
+ _INT = re.compile(r"[+-]?[0-9]+")
7
+ _FLOAT = re.compile(r"[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?")
8
+ _BOOLS = {"true", "false", "yes", "no", "on", "off", "1", "0"}
9
+
10
+
11
+ def _is_str(value: str) -> bool:
12
+ return True
13
+
14
+
15
+ def _is_int(value: str) -> bool:
16
+ return _INT.fullmatch(value) is not None
17
+
18
+
19
+ def _is_float(value: str) -> bool:
20
+ return _FLOAT.fullmatch(value) is not None
21
+
22
+
23
+ def _is_bool(value: str) -> bool:
24
+ return value.lower() in _BOOLS
25
+
26
+
27
+ def _is_url(value: str) -> bool:
28
+ if any(char.isspace() for char in value):
29
+ return False
30
+ try:
31
+ parts = urlsplit(value)
32
+ _ = parts.port # raises ValueError for a non-numeric or out-of-range port
33
+ hostname = parts.hostname # None when the host part is empty, e.g. "http://:80"
34
+ except ValueError:
35
+ return False
36
+ return bool(parts.scheme and hostname)
37
+
38
+
39
+ _CHECKS = {
40
+ "str": _is_str,
41
+ "int": _is_int,
42
+ "float": _is_float,
43
+ "bool": _is_bool,
44
+ "url": _is_url,
45
+ }
46
+
47
+ _MESSAGES = {
48
+ "int": "expected an integer",
49
+ "float": "expected a number",
50
+ "bool": "expected a boolean (true/false, yes/no, on/off, 1/0)",
51
+ "url": "expected a URL such as scheme://host",
52
+ }
53
+
54
+ TYPES = tuple(_CHECKS) # ("str", "int", "float", "bool", "url")
55
+
56
+
57
+ def check_type(type_name: str, value: str) -> str | None:
58
+ """Return None if the value suits the type, otherwise a short problem description.
59
+
60
+ The description never contains the value itself, because it might be a secret.
61
+ """
62
+ if _CHECKS[type_name](value):
63
+ return None
64
+ return _MESSAGES[type_name]
envkeep/cli.py ADDED
@@ -0,0 +1,298 @@
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Annotated, Optional
4
+
5
+ import typer
6
+
7
+ from envkeep.compare import compare
8
+ from envkeep.compose import ComposeError, analyze_compose, load_compose_text
9
+ from envkeep.differ import diff_envs
10
+ from envkeep.fileio import atomic_write_text
11
+ from envkeep.generator import generate_example
12
+ from envkeep.output import (
13
+ print_check_result,
14
+ print_compose_result,
15
+ print_diff_result,
16
+ print_error,
17
+ print_success,
18
+ print_sync_result,
19
+ )
20
+ from envkeep.parser import EnvSyntaxError, parse_env_text
21
+ from envkeep.schema import SchemaError, VarRule, load_schema
22
+ from envkeep.syncer import sync_env
23
+ from envkeep.validate import validate_env
24
+
25
+ DEFAULT_ENV = Path(".env")
26
+ DEFAULT_EXAMPLE = Path(".env.example")
27
+ COMPOSE_NAMES = (
28
+ "compose.yaml",
29
+ "compose.yml",
30
+ "docker-compose.yml",
31
+ "docker-compose.yaml",
32
+ )
33
+
34
+ app = typer.Typer(
35
+ help="Keep your .env files in sync with .env.example.",
36
+ no_args_is_help=True,
37
+ )
38
+
39
+
40
+ def _require_files(*paths: Path) -> None:
41
+ """Exit with code 2 if any of the given files doesn't exist."""
42
+ for path in paths:
43
+ if not path.is_file():
44
+ print_error(f"file not found: {path}")
45
+ raise typer.Exit(code=2)
46
+
47
+
48
+ def _is_same_file(a: Path, b: Path) -> bool:
49
+ """True if both paths point at the same file, including hard links and symlinks."""
50
+ # Same path after resolving symlinks (works even if b doesn't exist yet).
51
+ if a.resolve() == b.resolve():
52
+ return True
53
+ # Same file under different names, for example a hard link.
54
+ return b.exists() and a.samefile(b)
55
+
56
+
57
+ def _read_text(path: Path, *, keep_newlines: bool = False) -> str:
58
+ """Read a UTF-8 file. Unreadable or non-UTF-8 files exit with code 2, no traceback.
59
+
60
+ With keep_newlines, line endings are returned exactly as stored (no translation).
61
+ """
62
+ try:
63
+ with path.open(encoding="utf-8", newline="" if keep_newlines else None) as handle:
64
+ return handle.read()
65
+ except UnicodeDecodeError:
66
+ print_error(f"{path}: the file is not valid UTF-8")
67
+ raise typer.Exit(code=2) from None
68
+ except OSError as exc:
69
+ print_error(f"could not read {path}: {exc.strerror or 'unknown error'}")
70
+ raise typer.Exit(code=2) from exc
71
+
72
+
73
+ def _read_env(path: Path) -> dict[str, str]:
74
+ """Parse an env file, turning any read or syntax problem into exit code 2."""
75
+ text = _read_text(path)
76
+ try:
77
+ return parse_env_text(text)
78
+ except EnvSyntaxError as exc:
79
+ print_error(f"{path}: {exc}")
80
+ raise typer.Exit(code=2) from exc
81
+
82
+
83
+ def _load_schema(path: Path) -> dict[str, VarRule]:
84
+ """Load a schema, turning every problem into a clean message and exit code 2."""
85
+ try:
86
+ return load_schema(path)
87
+ except SchemaError as exc:
88
+ for problem in exc.problems:
89
+ print_error(f"{path}: {problem}")
90
+ raise typer.Exit(code=2) from exc
91
+
92
+
93
+ def _find_compose_file() -> Path:
94
+ """Find a compose file in the current folder, using Compose's own lookup order."""
95
+ for name in COMPOSE_NAMES:
96
+ if Path(name).is_file():
97
+ return Path(name)
98
+ print_error(f"no compose file found here (looked for {', '.join(COMPOSE_NAMES)})")
99
+ raise typer.Exit(code=2)
100
+
101
+
102
+ @app.callback()
103
+ def main() -> None:
104
+ """Keep your .env files in sync with .env.example."""
105
+
106
+
107
+ @app.command()
108
+ def check(
109
+ env: Annotated[Path, typer.Option("--env", "-e", help="The .env file to check.")] = DEFAULT_ENV,
110
+ example: Annotated[
111
+ Path,
112
+ typer.Option("--example", "-x", help="The file used as the source of truth."),
113
+ ] = DEFAULT_EXAMPLE,
114
+ schema: Annotated[
115
+ Optional[Path],
116
+ typer.Option(
117
+ "--schema",
118
+ "-s",
119
+ help="An envkeep.yml schema to validate against. When given, it replaces --example.",
120
+ ),
121
+ ] = None,
122
+ ) -> None:
123
+ """Check a .env file against .env.example or an envkeep.yml schema.
124
+
125
+ Exits with code 1 if variables are missing, empty, or invalid, so it works in CI.
126
+ """
127
+ if schema is not None:
128
+ _require_files(env, schema)
129
+ result = validate_env(_load_schema(schema), _read_env(env))
130
+ print_check_result(result, env, schema)
131
+ else:
132
+ _require_files(env, example)
133
+ result = compare(_read_env(example), _read_env(env))
134
+ print_check_result(result, env, example)
135
+
136
+ if not result.ok:
137
+ raise typer.Exit(code=1)
138
+
139
+
140
+ @app.command()
141
+ def generate(
142
+ env: Annotated[Path, typer.Option("--env", "-e", help="The .env file to read.")] = DEFAULT_ENV,
143
+ output: Annotated[
144
+ Path,
145
+ typer.Option("--output", "-o", help="Where to write the example file."),
146
+ ] = DEFAULT_EXAMPLE,
147
+ placeholder: Annotated[
148
+ str, typer.Option("--placeholder", "-p", help="Value to put after each key.")
149
+ ] = "",
150
+ force: Annotated[
151
+ bool,
152
+ typer.Option("--force", "-f", help="Overwrite the output file if it already exists."),
153
+ ] = False,
154
+ ) -> None:
155
+ """Build .env.example from .env, stripping the values but keeping comments."""
156
+ _require_files(env)
157
+ if _is_same_file(env, output):
158
+ print_error("--env and --output are the same file; refusing to overwrite your values")
159
+ raise typer.Exit(code=2)
160
+ if output.exists() and not force:
161
+ print_error(f"{output} already exists (use --force to overwrite)")
162
+ raise typer.Exit(code=2)
163
+
164
+ text = _read_text(env)
165
+ try:
166
+ content = generate_example(text, placeholder)
167
+ except EnvSyntaxError as exc:
168
+ print_error(f"{env}: {exc}")
169
+ raise typer.Exit(code=2) from exc
170
+
171
+ output.write_text(content, encoding="utf-8")
172
+ print_success(f"wrote {len(parse_env_text(text))} variables to {output}")
173
+
174
+
175
+ @app.command()
176
+ def sync(
177
+ env: Annotated[
178
+ Path, typer.Option("--env", "-e", help="The .env file to update.")
179
+ ] = DEFAULT_ENV,
180
+ example: Annotated[
181
+ Path,
182
+ typer.Option("--example", "-x", help="The file used as the source of truth."),
183
+ ] = DEFAULT_EXAMPLE,
184
+ dry_run: Annotated[
185
+ bool,
186
+ typer.Option("--dry-run", help="Show what would be added without writing anything."),
187
+ ] = False,
188
+ ) -> None:
189
+ """Add variables that are in .env.example but missing from .env.
190
+
191
+ Existing variables and values are never changed.
192
+ """
193
+ _require_files(env, example)
194
+
195
+ # keep_newlines: existing \r\n endings must survive untouched
196
+ env_text = _read_text(env, keep_newlines=True)
197
+ new_text, added = sync_env(_read_env(example), env_text, _read_env(env))
198
+
199
+ if added and not dry_run:
200
+ try:
201
+ atomic_write_text(env, new_text)
202
+ except OSError as exc:
203
+ print_error(f"could not write {env}: {exc}")
204
+ raise typer.Exit(code=2) from exc
205
+ print_sync_result(added, env, dry_run)
206
+
207
+
208
+ @app.command()
209
+ def diff(
210
+ first: Annotated[Path, typer.Argument(help="The first env file (A).")],
211
+ second: Annotated[Path, typer.Argument(help="The second env file (B).")],
212
+ show_values: Annotated[
213
+ bool,
214
+ typer.Option(
215
+ "--show-values",
216
+ help="Show the values too. They may be secrets, so they are hidden by default.",
217
+ ),
218
+ ] = False,
219
+ keys_only: Annotated[
220
+ bool,
221
+ typer.Option(
222
+ "--keys-only",
223
+ help="Compare only which variables exist, ignoring value differences.",
224
+ ),
225
+ ] = False,
226
+ ) -> None:
227
+ """Show the differences between two env files, for example dev vs staging.
228
+
229
+ Values are hidden by default. Exits with code 1 if the files differ.
230
+ """
231
+ _require_files(first, second)
232
+ first_values = _read_env(first)
233
+ second_values = _read_env(second)
234
+
235
+ result = diff_envs(first_values, second_values, keys_only=keys_only)
236
+ print_diff_result(
237
+ result,
238
+ first,
239
+ second,
240
+ first_values,
241
+ second_values,
242
+ show_values=show_values,
243
+ keys_only=keys_only,
244
+ )
245
+ if not result.identical:
246
+ raise typer.Exit(code=1)
247
+
248
+
249
+ @app.command()
250
+ def compose(
251
+ compose_file: Annotated[
252
+ Optional[Path],
253
+ typer.Argument(
254
+ help="The compose file. Defaults to the first of compose.yaml, "
255
+ "compose.yml, docker-compose.yml, docker-compose.yaml in this folder."
256
+ ),
257
+ ] = None,
258
+ env: Annotated[
259
+ Optional[Path],
260
+ typer.Option(
261
+ "--env",
262
+ "-e",
263
+ help="The env file that supplies ${VAR} values. "
264
+ "Defaults to .env next to the compose file, if there is one.",
265
+ ),
266
+ ] = None,
267
+ shell_env: Annotated[
268
+ bool,
269
+ typer.Option(
270
+ "--shell-env",
271
+ help="Also count variables set in your current shell as defined.",
272
+ ),
273
+ ] = False,
274
+ ) -> None:
275
+ """Find ${VAR} references and env_file entries in a compose file that are undefined.
276
+
277
+ Values are never printed. Exits with code 1 if something is undefined.
278
+ """
279
+ path = compose_file if compose_file is not None else _find_compose_file()
280
+ _require_files(path)
281
+
282
+ if env is not None:
283
+ _require_files(env)
284
+ values = _read_env(env)
285
+ else:
286
+ default_env = path.parent / ".env"
287
+ values = _read_env(default_env) if default_env.is_file() else {}
288
+
289
+ try:
290
+ data = load_compose_text(_read_text(path))
291
+ except ComposeError as exc:
292
+ print_error(f"{path}: {exc}")
293
+ raise typer.Exit(code=2) from exc
294
+
295
+ result = analyze_compose(data, values, path.parent, dict(os.environ) if shell_env else None)
296
+ print_compose_result(result, path)
297
+ if not result.ok:
298
+ raise typer.Exit(code=1)
envkeep/compare.py ADDED
@@ -0,0 +1,13 @@
1
+ from envkeep.models import CheckResult
2
+
3
+
4
+ def compare(example: dict[str, str], env: dict[str, str]) -> CheckResult:
5
+ """Compare parsed env values against the example (source of truth)."""
6
+ example_keys = set(example)
7
+ env_keys = set(env)
8
+
9
+ return CheckResult(
10
+ missing=sorted(example_keys - env_keys),
11
+ extra=sorted(env_keys - example_keys),
12
+ empty=sorted(key for key, value in env.items() if value == ""),
13
+ )
envkeep/compose.py ADDED
@@ -0,0 +1,170 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterator, Mapping
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from envkeep.interpolate import expand, find_references
9
+ from envkeep.yamlutil import YamlSyntaxError, load_yaml
10
+
11
+
12
+ class ComposeError(ValueError):
13
+ """The compose file can't be used. The message never contains file contents."""
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class EnvFileRef:
18
+ """An env_file entry of one service."""
19
+
20
+ service: str
21
+ path: str
22
+ required: bool = True
23
+
24
+
25
+ @dataclass
26
+ class ComposeResult:
27
+ """What is wrong with a compose file. Holds names and locations, never values."""
28
+
29
+ undefined: dict[str, list[str]] = field(default_factory=dict) # name -> locations
30
+ empty: dict[str, list[str]] = field(default_factory=dict) # ${VAR:?} but blank
31
+ optional: list[str] = field(default_factory=list) # names that have a default
32
+ missing_env_files: list[EnvFileRef] = field(default_factory=list)
33
+
34
+ @property
35
+ def ok(self) -> bool:
36
+ return not (self.undefined or self.empty or self.missing_env_files)
37
+
38
+
39
+ def load_compose_text(text: str) -> Any:
40
+ """Parse compose file text. Raises ComposeError if it can't be used."""
41
+ try:
42
+ data = load_yaml(text)
43
+ except YamlSyntaxError as exc:
44
+ raise ComposeError(str(exc)) from None
45
+ if not isinstance(data, dict):
46
+ raise ComposeError("expected a mapping at the top level; is this a compose file?")
47
+ return data
48
+
49
+
50
+ def _iter_strings(root: Any) -> Iterator[tuple[str, str]]:
51
+ """Yield (location, text) for every string value in the document.
52
+
53
+ Iterative, and each list or mapping is visited once, so deep nesting and shared
54
+ YAML aliases can't cause a crash or a blow-up.
55
+ """
56
+ seen: set[int] = set()
57
+ stack: list[tuple[str, Any]] = [("", root)]
58
+ while stack:
59
+ path, node = stack.pop()
60
+ if isinstance(node, str):
61
+ yield path, node
62
+ elif isinstance(node, dict):
63
+ if id(node) in seen:
64
+ continue
65
+ seen.add(id(node))
66
+ for key, value in node.items():
67
+ stack.append((f"{path}.{key}" if path else str(key), value))
68
+ elif isinstance(node, list):
69
+ if id(node) in seen:
70
+ continue
71
+ seen.add(id(node))
72
+ for index, value in enumerate(node):
73
+ stack.append((f"{path}[{index}]", value))
74
+
75
+
76
+ def _env_file_refs(data: dict) -> list[EnvFileRef]:
77
+ """Collect env_file entries: a string, a list of strings, or {path, required}."""
78
+ services = data.get("services")
79
+ if not isinstance(services, dict):
80
+ return []
81
+
82
+ refs: list[EnvFileRef] = []
83
+ for service, spec in services.items():
84
+ if not isinstance(spec, dict):
85
+ continue
86
+ value = spec.get("env_file")
87
+ for item in value if isinstance(value, list) else [value]:
88
+ if isinstance(item, str):
89
+ refs.append(EnvFileRef(str(service), item))
90
+ elif isinstance(item, dict) and isinstance(item.get("path"), str):
91
+ required = item.get("required", True) is not False
92
+ refs.append(EnvFileRef(str(service), item["path"], required))
93
+ return refs
94
+
95
+
96
+ _MAX_NESTING = 32 # deeper nesting is ignored, which keeps pathological files fast
97
+
98
+
99
+ def _evaluate(
100
+ text: str,
101
+ location: str,
102
+ values: Mapping[str, str],
103
+ undefined: dict[str, set[str]],
104
+ empty: dict[str, set[str]],
105
+ optional: set[str],
106
+ ) -> None:
107
+ """Record every variable problem in one string, following only the active branches.
108
+
109
+ A nested expression such as the fallback in ${A:-${B:?need B}} is evaluated only
110
+ when Compose would evaluate it, given the effective values. Iterative, so deep
111
+ nesting can't cause a RecursionError.
112
+ """
113
+ stack = [(text, 0)]
114
+ while stack:
115
+ current, depth = stack.pop()
116
+ for ref in find_references(current):
117
+ value = values.get(ref.name)
118
+ unset = value is None or (ref.treat_empty_as_unset and value == "")
119
+
120
+ if ref.kind in ("plain", "required"):
121
+ if value is None:
122
+ undefined.setdefault(ref.name, set()).add(location)
123
+ elif ref.kind == "required" and unset:
124
+ empty.setdefault(ref.name, set()).add(location)
125
+ continue
126
+
127
+ optional.add(ref.name)
128
+ active = unset if ref.kind == "default" else not unset
129
+ if active and ref.body and depth < _MAX_NESTING:
130
+ stack.append((ref.body, depth + 1))
131
+
132
+
133
+ def analyze_compose(
134
+ data: dict,
135
+ env: Mapping[str, str],
136
+ base_dir: Path,
137
+ shell_env: Mapping[str, str] | None = None,
138
+ ) -> ComposeResult:
139
+ """Find undefined variables and missing env_file entries.
140
+
141
+ env holds the values Compose would read from the project's .env file. shell_env,
142
+ when given, also counts, and wins over env, as it does in Compose.
143
+ """
144
+ values = {**env, **(shell_env or {})}
145
+ undefined: dict[str, set[str]] = {}
146
+ empty: dict[str, set[str]] = {}
147
+ optional: set[str] = set()
148
+
149
+ for location, text in _iter_strings(data):
150
+ _evaluate(text, location, values, undefined, empty, optional)
151
+
152
+ missing: list[EnvFileRef] = []
153
+ for ref in _env_file_refs(data):
154
+ if not ref.required:
155
+ continue
156
+ # Expand ${VAR} in the path the way Compose does. If a variable it needs is
157
+ # undefined, the real path is unknown: skip the check (that variable is
158
+ # already reported where the path is written).
159
+ resolved = expand(ref.path, values)
160
+ if not resolved:
161
+ continue
162
+ if not (base_dir / resolved).is_file():
163
+ missing.append(ref) # reported as written, never with expanded values
164
+
165
+ return ComposeResult(
166
+ undefined={name: sorted(locs) for name, locs in sorted(undefined.items())},
167
+ empty={name: sorted(locs) for name, locs in sorted(empty.items())},
168
+ optional=sorted(optional),
169
+ missing_env_files=sorted(missing, key=lambda ref: (ref.service, ref.path)),
170
+ )
envkeep/differ.py ADDED
@@ -0,0 +1,25 @@
1
+ from dataclasses import dataclass, field
2
+
3
+
4
+ @dataclass
5
+ class DiffResult:
6
+ """Differences between two env files, A and B."""
7
+
8
+ only_in_a: list[str] = field(default_factory=list)
9
+ only_in_b: list[str] = field(default_factory=list)
10
+ changed: list[str] = field(default_factory=list) # in both, different values
11
+
12
+ @property
13
+ def identical(self) -> bool:
14
+ return not (self.only_in_a or self.only_in_b or self.changed)
15
+
16
+
17
+ def diff_envs(a: dict[str, str], b: dict[str, str], keys_only: bool = False) -> DiffResult:
18
+ """Compare two parsed env files. With keys_only, value differences are ignored."""
19
+ keys_a, keys_b = set(a), set(b)
20
+ changed = [] if keys_only else sorted(k for k in keys_a & keys_b if a[k] != b[k])
21
+ return DiffResult(
22
+ only_in_a=sorted(keys_a - keys_b),
23
+ only_in_b=sorted(keys_b - keys_a),
24
+ changed=changed,
25
+ )
envkeep/fileio.py ADDED
@@ -0,0 +1,28 @@
1
+ import os
2
+ import shutil
3
+ import tempfile
4
+ from pathlib import Path
5
+
6
+
7
+ def atomic_write_text(path: Path, text: str) -> None:
8
+ """Replace the contents of an existing file without ever leaving it half-written.
9
+
10
+ The text goes into a temporary file in the same directory first. The original
11
+ is replaced only after that write has been flushed to disk. If anything fails,
12
+ the temporary file is removed and the original is left as it was.
13
+ Newlines are written exactly as given (no translation).
14
+ """
15
+ target = path.resolve() # follow symlinks, so we replace the real file, not the link
16
+ fd, tmp_name = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.", suffix=".tmp")
17
+ tmp_path = Path(tmp_name)
18
+ try:
19
+ with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle:
20
+ handle.write(text)
21
+ handle.flush()
22
+ os.fsync(handle.fileno()) # make sure the bytes are on disk before swapping
23
+ if target.exists():
24
+ shutil.copymode(target, tmp_path) # mkstemp creates 0600; restore the original mode
25
+ os.replace(tmp_path, target) # atomic on the same filesystem
26
+ except BaseException:
27
+ tmp_path.unlink(missing_ok=True)
28
+ raise
envkeep/generator.py ADDED
@@ -0,0 +1,21 @@
1
+ from envkeep.parser import scan
2
+
3
+
4
+ def generate_example(text: str, placeholder: str = "") -> str:
5
+ """Turn the text of a .env file into .env.example text.
6
+
7
+ Genuine comments, blank lines, key order, and `export` prefixes are kept.
8
+ Every value (including multiline quoted ones) is replaced by the placeholder.
9
+ Lines that aren't comments or assignments are dropped, since they could
10
+ contain a stray secret.
11
+
12
+ Raises EnvSyntaxError for an unterminated quoted value, so nothing is written
13
+ when we can't tell where a secret ends.
14
+ """
15
+ out_lines: list[str] = []
16
+ for entry in scan(text):
17
+ if entry.kind == "raw":
18
+ out_lines.append(entry.line)
19
+ elif entry.kind == "assignment":
20
+ out_lines.append(f"{entry.prefix}{entry.key}={placeholder}")
21
+ return "\n".join(out_lines) + "\n" if out_lines else ""