envexample-guard 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The envexample-guard authors
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.
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.4
2
+ Name: envexample-guard
3
+ Version: 0.1.0
4
+ Summary: Detect drift between your .env and .env.example files. Zero dependencies, CI-friendly exit codes.
5
+ License-Expression: MIT
6
+ Keywords: dotenv,env,environment,config,ci,lint
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Environment :: Console
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Topic :: Software Development :: Quality Assurance
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: license-file
16
+
17
+ # envexample-guard
18
+
19
+ Catch the classic "works on my machine" bug: someone added `STRIPE_KEY` to
20
+ `.env.example`, but your `.env` never got it (or vice versa).
21
+
22
+ `envexample-guard` compares a `.env` file against its `.env.example` template and
23
+ reports **missing**, **extra**, and **empty** keys. It has zero dependencies and
24
+ returns non-zero exit codes, so it drops straight into CI or a pre-commit hook.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install envexample-guard
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ```bash
35
+ envexample-guard # compares ./.env against ./.env.example
36
+ envexample-guard --env .env.local --example .env.template
37
+ envexample-guard --strict # also fail on keys not in the example
38
+ envexample-guard --no-empty # also fail on required keys with empty values
39
+ envexample-guard --json # machine-readable output
40
+ envexample-guard --write-example # regenerate .env.example from .env (values stripped)
41
+ ```
42
+
43
+ Example output:
44
+
45
+ ```
46
+ ✗ missing (in .env.example, not in .env): DATABASE_URL, STRIPE_KEY
47
+ ! extra (in .env, not in .env.example): OLD_FLAG
48
+ ```
49
+
50
+ ### Exit codes
51
+
52
+ | code | meaning |
53
+ |------|---------|
54
+ | 0 | in sync |
55
+ | 1 | drift detected (missing keys; extra keys with `--strict`; empty values with `--no-empty`) |
56
+ | 2 | a file could not be read |
57
+
58
+ ### In CI (GitHub Actions)
59
+
60
+ ```yaml
61
+ - run: pip install envexample-guard
62
+ - run: envexample-guard --env .env.ci --example .env.example --strict
63
+ ```
64
+
65
+ ## Python API
66
+
67
+ ```python
68
+ from envexample_guard import parse_dotenv, compare
69
+
70
+ report = compare(parse_dotenv(".env"), parse_dotenv(".env.example"))
71
+ print(report.missing, report.extra, report.empty)
72
+ ```
73
+
74
+ ## Parsing rules
75
+
76
+ Supports `KEY=value`, `export KEY=value`, single/double quoted values (with
77
+ `\n` escapes in double quotes), multi-line quoted values, inline `# comments`
78
+ after unquoted values, blank lines and comment lines.
79
+
80
+ ## License
81
+
82
+ MIT
@@ -0,0 +1,66 @@
1
+ # envexample-guard
2
+
3
+ Catch the classic "works on my machine" bug: someone added `STRIPE_KEY` to
4
+ `.env.example`, but your `.env` never got it (or vice versa).
5
+
6
+ `envexample-guard` compares a `.env` file against its `.env.example` template and
7
+ reports **missing**, **extra**, and **empty** keys. It has zero dependencies and
8
+ returns non-zero exit codes, so it drops straight into CI or a pre-commit hook.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pip install envexample-guard
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ```bash
19
+ envexample-guard # compares ./.env against ./.env.example
20
+ envexample-guard --env .env.local --example .env.template
21
+ envexample-guard --strict # also fail on keys not in the example
22
+ envexample-guard --no-empty # also fail on required keys with empty values
23
+ envexample-guard --json # machine-readable output
24
+ envexample-guard --write-example # regenerate .env.example from .env (values stripped)
25
+ ```
26
+
27
+ Example output:
28
+
29
+ ```
30
+ ✗ missing (in .env.example, not in .env): DATABASE_URL, STRIPE_KEY
31
+ ! extra (in .env, not in .env.example): OLD_FLAG
32
+ ```
33
+
34
+ ### Exit codes
35
+
36
+ | code | meaning |
37
+ |------|---------|
38
+ | 0 | in sync |
39
+ | 1 | drift detected (missing keys; extra keys with `--strict`; empty values with `--no-empty`) |
40
+ | 2 | a file could not be read |
41
+
42
+ ### In CI (GitHub Actions)
43
+
44
+ ```yaml
45
+ - run: pip install envexample-guard
46
+ - run: envexample-guard --env .env.ci --example .env.example --strict
47
+ ```
48
+
49
+ ## Python API
50
+
51
+ ```python
52
+ from envexample_guard import parse_dotenv, compare
53
+
54
+ report = compare(parse_dotenv(".env"), parse_dotenv(".env.example"))
55
+ print(report.missing, report.extra, report.empty)
56
+ ```
57
+
58
+ ## Parsing rules
59
+
60
+ Supports `KEY=value`, `export KEY=value`, single/double quoted values (with
61
+ `\n` escapes in double quotes), multi-line quoted values, inline `# comments`
62
+ after unquoted values, blank lines and comment lines.
63
+
64
+ ## License
65
+
66
+ MIT
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "envexample-guard"
7
+ version = "0.1.0"
8
+ description = "Detect drift between your .env and .env.example files. Zero dependencies, CI-friendly exit codes."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ keywords = ["dotenv", "env", "environment", "config", "ci", "lint"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Developers",
18
+ "Topic :: Software Development :: Quality Assurance",
19
+ "Operating System :: OS Independent",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.scripts]
24
+ envexample-guard = "envexample_guard.cli:main"
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """Detect drift between .env and .env.example files."""
2
+
3
+ from .core import DriftReport, compare, parse_dotenv, parse_dotenv_text, render_example
4
+
5
+ __all__ = ["DriftReport", "compare", "parse_dotenv", "parse_dotenv_text", "render_example"]
6
+ __version__ = "0.1.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,68 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from typing import List, Optional
7
+
8
+ from . import __version__
9
+ from .core import compare, parse_dotenv, render_example
10
+
11
+
12
+ def main(argv: Optional[List[str]] = None) -> int:
13
+ p = argparse.ArgumentParser(
14
+ prog="envexample-guard",
15
+ description="Detect drift between a .env file and its .env.example template.",
16
+ )
17
+ p.add_argument("--env", default=".env", help="path to the .env file (default: .env)")
18
+ p.add_argument("--example", default=".env.example", help="path to the template (default: .env.example)")
19
+ p.add_argument("--strict", action="store_true", help="fail on keys present in .env but not in the example")
20
+ p.add_argument("--no-empty", action="store_true", help="fail on required keys that have empty values")
21
+ p.add_argument("--json", action="store_true", help="print a JSON report")
22
+ p.add_argument("--quiet", "-q", action="store_true", help="print nothing; rely on the exit code")
23
+ p.add_argument("--write-example", action="store_true",
24
+ help="write the example file from --env with values stripped, then exit")
25
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
26
+ args = p.parse_args(argv)
27
+
28
+ if args.write_example:
29
+ try:
30
+ with open(args.env, encoding="utf-8") as fh:
31
+ text = fh.read()
32
+ with open(args.example, "w", encoding="utf-8") as fh:
33
+ fh.write(render_example(text))
34
+ except OSError as e:
35
+ print(f"envexample-guard: {e}", file=sys.stderr)
36
+ return 2
37
+ if not args.quiet:
38
+ print(f"wrote {args.example} from {args.env}")
39
+ return 0
40
+
41
+ try:
42
+ env = parse_dotenv(args.env)
43
+ example = parse_dotenv(args.example)
44
+ except OSError as e:
45
+ print(f"envexample-guard: {e}", file=sys.stderr)
46
+ return 2
47
+
48
+ report = compare(env, example)
49
+ failed = report.has_drift(strict=args.strict, no_empty=args.no_empty)
50
+
51
+ if args.json:
52
+ print(json.dumps({**report.to_dict(), "ok": not failed}, indent=2))
53
+ elif not args.quiet:
54
+ if report.missing:
55
+ print(f"✗ missing (in {args.example}, not in {args.env}): {', '.join(report.missing)}")
56
+ if report.extra:
57
+ mark = "✗" if args.strict else "!"
58
+ print(f"{mark} extra (in {args.env}, not in {args.example}): {', '.join(report.extra)}")
59
+ if report.empty:
60
+ mark = "✗" if args.no_empty else "!"
61
+ print(f"{mark} empty (set but blank in {args.env}): {', '.join(report.empty)}")
62
+ if not (report.missing or report.extra or report.empty):
63
+ print(f"✓ {args.env} is in sync with {args.example}")
64
+ return 1 if failed else 0
65
+
66
+
67
+ if __name__ == "__main__": # pragma: no cover
68
+ sys.exit(main())
@@ -0,0 +1,114 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import re
5
+ from dataclasses import dataclass, field
6
+ from typing import Dict, List, Union
7
+
8
+ _KEY_RE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.\-]*)\s*=\s*(.*)$")
9
+ _ESCAPES = {"n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
10
+
11
+
12
+ def _unescape_double(s: str) -> str:
13
+ return re.sub(r"\\(.)", lambda m: _ESCAPES.get(m.group(1), "\\" + m.group(1)), s)
14
+
15
+
16
+ def _find_closing(s: str, quote: str) -> int:
17
+ """Index of the closing quote in s (which starts after the opening quote), or -1."""
18
+ i = 0
19
+ while i < len(s):
20
+ c = s[i]
21
+ if c == "\\" and quote == '"':
22
+ i += 2
23
+ continue
24
+ if c == quote:
25
+ return i
26
+ i += 1
27
+ return -1
28
+
29
+
30
+ def parse_dotenv_text(text: str) -> Dict[str, str]:
31
+ """Parse dotenv-formatted text into an ordered dict of key -> value."""
32
+ result: Dict[str, str] = {}
33
+ lines = text.splitlines()
34
+ i = 0
35
+ while i < len(lines):
36
+ line = lines[i]
37
+ i += 1
38
+ stripped = line.strip()
39
+ if not stripped or stripped.startswith("#"):
40
+ continue
41
+ m = _KEY_RE.match(line)
42
+ if not m:
43
+ continue
44
+ key, raw = m.group(1), m.group(2)
45
+ if raw[:1] in ("'", '"'):
46
+ quote = raw[0]
47
+ body = raw[1:]
48
+ end = _find_closing(body, quote)
49
+ # multi-line quoted value
50
+ while end == -1 and i < len(lines):
51
+ body += "\n" + lines[i]
52
+ i += 1
53
+ end = _find_closing(body, quote)
54
+ value = body if end == -1 else body[:end]
55
+ if quote == '"':
56
+ value = _unescape_double(value)
57
+ else:
58
+ value = re.split(r"\s+#", raw, maxsplit=1)[0].strip()
59
+ result[key] = value
60
+ return result
61
+
62
+
63
+ def parse_dotenv(path: Union[str, "os.PathLike[str]"]) -> Dict[str, str]:
64
+ with open(path, encoding="utf-8") as fh:
65
+ return parse_dotenv_text(fh.read())
66
+
67
+
68
+ @dataclass
69
+ class DriftReport:
70
+ missing: List[str] = field(default_factory=list)
71
+ extra: List[str] = field(default_factory=list)
72
+ empty: List[str] = field(default_factory=list)
73
+
74
+ def has_drift(self, strict: bool = False, no_empty: bool = False) -> bool:
75
+ return bool(self.missing or (strict and self.extra) or (no_empty and self.empty))
76
+
77
+ def to_dict(self) -> Dict[str, List[str]]:
78
+ return {"missing": self.missing, "extra": self.extra, "empty": self.empty}
79
+
80
+
81
+ def compare(env: Dict[str, str], example: Dict[str, str]) -> DriftReport:
82
+ """Compare a parsed .env against a parsed .env.example."""
83
+ return DriftReport(
84
+ missing=sorted(k for k in example if k not in env),
85
+ extra=sorted(k for k in env if k not in example),
86
+ empty=sorted(k for k in example if k in env and env[k] == ""),
87
+ )
88
+
89
+
90
+ def render_example(env_text: str) -> str:
91
+ """Produce .env.example content from .env text: keep comments/blank lines, strip values."""
92
+ out: List[str] = []
93
+ lines = env_text.splitlines()
94
+ i = 0
95
+ while i < len(lines):
96
+ line = lines[i]
97
+ i += 1
98
+ stripped = line.strip()
99
+ if not stripped or stripped.startswith("#"):
100
+ out.append(line)
101
+ continue
102
+ m = _KEY_RE.match(line)
103
+ if not m:
104
+ out.append(line)
105
+ continue
106
+ raw = m.group(2)
107
+ if raw[:1] in ("'", '"'):
108
+ quote, body = raw[0], raw[1:]
109
+ while _find_closing(body, quote) == -1 and i < len(lines):
110
+ body += "\n" + lines[i]
111
+ i += 1
112
+ prefix = "export " if stripped.startswith("export ") else ""
113
+ out.append(f"{prefix}{m.group(1)}=")
114
+ return "\n".join(out) + ("\n" if out else "")
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.4
2
+ Name: envexample-guard
3
+ Version: 0.1.0
4
+ Summary: Detect drift between your .env and .env.example files. Zero dependencies, CI-friendly exit codes.
5
+ License-Expression: MIT
6
+ Keywords: dotenv,env,environment,config,ci,lint
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Environment :: Console
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Topic :: Software Development :: Quality Assurance
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: license-file
16
+
17
+ # envexample-guard
18
+
19
+ Catch the classic "works on my machine" bug: someone added `STRIPE_KEY` to
20
+ `.env.example`, but your `.env` never got it (or vice versa).
21
+
22
+ `envexample-guard` compares a `.env` file against its `.env.example` template and
23
+ reports **missing**, **extra**, and **empty** keys. It has zero dependencies and
24
+ returns non-zero exit codes, so it drops straight into CI or a pre-commit hook.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install envexample-guard
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ```bash
35
+ envexample-guard # compares ./.env against ./.env.example
36
+ envexample-guard --env .env.local --example .env.template
37
+ envexample-guard --strict # also fail on keys not in the example
38
+ envexample-guard --no-empty # also fail on required keys with empty values
39
+ envexample-guard --json # machine-readable output
40
+ envexample-guard --write-example # regenerate .env.example from .env (values stripped)
41
+ ```
42
+
43
+ Example output:
44
+
45
+ ```
46
+ ✗ missing (in .env.example, not in .env): DATABASE_URL, STRIPE_KEY
47
+ ! extra (in .env, not in .env.example): OLD_FLAG
48
+ ```
49
+
50
+ ### Exit codes
51
+
52
+ | code | meaning |
53
+ |------|---------|
54
+ | 0 | in sync |
55
+ | 1 | drift detected (missing keys; extra keys with `--strict`; empty values with `--no-empty`) |
56
+ | 2 | a file could not be read |
57
+
58
+ ### In CI (GitHub Actions)
59
+
60
+ ```yaml
61
+ - run: pip install envexample-guard
62
+ - run: envexample-guard --env .env.ci --example .env.example --strict
63
+ ```
64
+
65
+ ## Python API
66
+
67
+ ```python
68
+ from envexample_guard import parse_dotenv, compare
69
+
70
+ report = compare(parse_dotenv(".env"), parse_dotenv(".env.example"))
71
+ print(report.missing, report.extra, report.empty)
72
+ ```
73
+
74
+ ## Parsing rules
75
+
76
+ Supports `KEY=value`, `export KEY=value`, single/double quoted values (with
77
+ `\n` escapes in double quotes), multi-line quoted values, inline `# comments`
78
+ after unquoted values, blank lines and comment lines.
79
+
80
+ ## License
81
+
82
+ MIT
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/envexample_guard/__init__.py
5
+ src/envexample_guard/__main__.py
6
+ src/envexample_guard/cli.py
7
+ src/envexample_guard/core.py
8
+ src/envexample_guard.egg-info/PKG-INFO
9
+ src/envexample_guard.egg-info/SOURCES.txt
10
+ src/envexample_guard.egg-info/dependency_links.txt
11
+ src/envexample_guard.egg-info/entry_points.txt
12
+ src/envexample_guard.egg-info/top_level.txt
13
+ tests/test_envexample_guard.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ envexample-guard = envexample_guard.cli:main
@@ -0,0 +1 @@
1
+ envexample_guard
@@ -0,0 +1,76 @@
1
+ import json
2
+
3
+ from envexample_guard import compare, parse_dotenv_text, render_example
4
+ from envexample_guard.cli import main
5
+
6
+ SAMPLE = '''
7
+ # comment
8
+ export A=1
9
+ B = two # inline comment
10
+ C="quoted # not a comment"
11
+ D='single $notexpanded'
12
+ E="line1\\nline2"
13
+ F="multi
14
+ line"
15
+ G=
16
+ H=url#fragment
17
+ '''
18
+
19
+
20
+ def test_parse():
21
+ d = parse_dotenv_text(SAMPLE)
22
+ assert d == {
23
+ "A": "1",
24
+ "B": "two",
25
+ "C": "quoted # not a comment",
26
+ "D": "single $notexpanded",
27
+ "E": "line1\nline2",
28
+ "F": "multi\nline",
29
+ "G": "",
30
+ "H": "url#fragment",
31
+ }
32
+
33
+
34
+ def test_compare():
35
+ r = compare({"A": "1", "X": "", "Z": "9"}, {"A": "", "X": "", "Y": ""})
36
+ assert r.missing == ["Y"]
37
+ assert r.extra == ["Z"]
38
+ assert r.empty == ["X"]
39
+ assert r.has_drift()
40
+ assert compare({"A": "1"}, {"A": ""}).has_drift() is False
41
+ assert compare({"A": "1", "B": "2"}, {"A": ""}).has_drift(strict=True) is True
42
+
43
+
44
+ def test_render_example():
45
+ out = render_example('# hi\nexport A=1\nB="x\ny"\n\nC=3\n')
46
+ assert out == "# hi\nexport A=\nB=\n\nC=\n"
47
+
48
+
49
+ def _write(tmp_path, env, example):
50
+ (tmp_path / ".env").write_text(env)
51
+ (tmp_path / ".env.example").write_text(example)
52
+ return ["--env", str(tmp_path / ".env"), "--example", str(tmp_path / ".env.example")]
53
+
54
+
55
+ def test_cli_exit_codes(tmp_path, capsys):
56
+ args = _write(tmp_path, "A=1\nEXTRA=1\nE=\n", "A=\nE=\n")
57
+ assert main(args) == 0
58
+ assert main(args + ["--strict"]) == 1
59
+ assert main(args + ["--no-empty"]) == 1
60
+ args = _write(tmp_path, "A=1\n", "A=\nB=\n")
61
+ assert main(args) == 1
62
+ assert main(["--env", str(tmp_path / "nope"), "--example", str(tmp_path / ".env.example")]) == 2
63
+
64
+
65
+ def test_cli_json(tmp_path, capsys):
66
+ args = _write(tmp_path, "A=1\n", "A=\nB=\n")
67
+ capsys.readouterr()
68
+ main(args + ["--json"])
69
+ data = json.loads(capsys.readouterr().out)
70
+ assert data == {"missing": ["B"], "extra": [], "empty": [], "ok": False}
71
+
72
+
73
+ def test_cli_write_example(tmp_path):
74
+ args = _write(tmp_path, "SECRET=hunter2\n", "")
75
+ assert main(args + ["--write-example", "-q"]) == 0
76
+ assert (tmp_path / ".env.example").read_text() == "SECRET=\n"