|
| 1 | +#!/usr/bin/env python |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import argparse |
| 5 | +import os |
| 6 | +import re |
| 7 | +import sys |
| 8 | +import tempfile |
| 9 | +from collections.abc import Iterable |
| 10 | +from collections.abc import Sequence |
| 11 | + |
| 12 | +# Defaults / constants |
| 13 | +DEFAULT_ENV_FILE = '.env' |
| 14 | +DEFAULT_GITIGNORE_FILE = '.gitignore' |
| 15 | +DEFAULT_EXAMPLE_ENV_FILE = '.env.example' |
| 16 | +GITIGNORE_BANNER = '# Added by pre-commit hook to prevent committing secrets' |
| 17 | + |
| 18 | +_KEY_REGEX = re.compile(r'^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=') |
| 19 | + |
| 20 | + |
| 21 | +def _atomic_write(path: str, data: str) -> None: |
| 22 | + """Atomically (best-effort) write text. |
| 23 | +
|
| 24 | + Writes to a same-directory temporary file then replaces the target with |
| 25 | + os.replace(). This is a slight divergence from most existing hooks which |
| 26 | + write directly, but here we intentionally reduce the (small) risk of |
| 27 | + partially-written files because the hook may be invoked rapidly / in |
| 28 | + parallel (tests exercise concurrent normalization). Keeping this helper |
| 29 | + local avoids adding any dependency. |
| 30 | + """ |
| 31 | + fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(path) or '.') |
| 32 | + try: |
| 33 | + with os.fdopen(fd, 'w', encoding='utf-8', newline='') as tmp_f: |
| 34 | + tmp_f.write(data) |
| 35 | + os.replace(tmp_path, path) |
| 36 | + finally: # Clean up if replace failed |
| 37 | + if os.path.exists(tmp_path): # (rare failure case) |
| 38 | + try: |
| 39 | + os.remove(tmp_path) |
| 40 | + except OSError: |
| 41 | + pass |
| 42 | + |
| 43 | + |
| 44 | +def _read_gitignore(gitignore_file: str) -> tuple[str, list[str]]: |
| 45 | + """Read and parse .gitignore file content.""" |
| 46 | + try: |
| 47 | + if os.path.exists(gitignore_file): |
| 48 | + with open(gitignore_file, encoding='utf-8') as f: |
| 49 | + original_text = f.read() |
| 50 | + lines = original_text.splitlines() |
| 51 | + else: |
| 52 | + original_text = '' |
| 53 | + lines = [] |
| 54 | + except OSError as exc: |
| 55 | + print( |
| 56 | + f"ERROR: unable to read {gitignore_file}: {exc}", |
| 57 | + file=sys.stderr, |
| 58 | + ) |
| 59 | + raise |
| 60 | + return original_text, lines |
| 61 | + |
| 62 | + |
| 63 | +def _normalize_gitignore_lines( |
| 64 | + lines: list[str], |
| 65 | + env_file: str, |
| 66 | + banner: str, |
| 67 | +) -> list[str]: |
| 68 | + """Normalize .gitignore lines by removing duplicates and canonical tail.""" |
| 69 | + # Trim trailing blank lines |
| 70 | + while lines and not lines[-1].strip(): |
| 71 | + lines.pop() |
| 72 | + |
| 73 | + # Remove existing occurrences |
| 74 | + filtered: list[str] = [ |
| 75 | + ln for ln in lines if ln.strip() not in {env_file, banner} |
| 76 | + ] |
| 77 | + |
| 78 | + if filtered and filtered[-1].strip(): |
| 79 | + filtered.append('') # ensure single blank before banner |
| 80 | + elif not filtered: # empty file -> still separate section visually |
| 81 | + filtered.append('') |
| 82 | + |
| 83 | + filtered.append(banner) |
| 84 | + filtered.append(env_file) |
| 85 | + return filtered |
| 86 | + |
| 87 | + |
| 88 | +def ensure_env_in_gitignore( |
| 89 | + env_file: str, |
| 90 | + gitignore_file: str, |
| 91 | + banner: str, |
| 92 | +) -> bool: |
| 93 | + """Ensure canonical banner + env tail in .gitignore. |
| 94 | +
|
| 95 | + Returns True only when the file content was changed. Returns False both |
| 96 | + when unchanged and on IO errors (we intentionally conflate for the simple |
| 97 | + hook contract; errors are still surfaced via stderr output). |
| 98 | + """ |
| 99 | + try: |
| 100 | + original_content_str, lines = _read_gitignore(gitignore_file) |
| 101 | + except OSError: |
| 102 | + return False |
| 103 | + |
| 104 | + filtered = _normalize_gitignore_lines(lines, env_file, banner) |
| 105 | + new_content = '\n'.join(filtered) + '\n' |
| 106 | + |
| 107 | + # Normalize original content to a single trailing newline for comparison |
| 108 | + normalized_original = original_content_str |
| 109 | + if normalized_original and not normalized_original.endswith('\n'): |
| 110 | + normalized_original += '\n' |
| 111 | + if new_content == normalized_original: |
| 112 | + return False |
| 113 | + |
| 114 | + try: |
| 115 | + _atomic_write(gitignore_file, new_content) |
| 116 | + return True |
| 117 | + except OSError as exc: |
| 118 | + print( |
| 119 | + f"ERROR: unable to write {gitignore_file}: {exc}", |
| 120 | + file=sys.stderr, |
| 121 | + ) |
| 122 | + return False |
| 123 | + |
| 124 | + |
| 125 | +def create_example_env(src_env: str, example_file: str) -> bool: |
| 126 | + """Generate .env.example with unique KEY= lines (no values).""" |
| 127 | + try: |
| 128 | + with open(src_env, encoding='utf-8') as f_env: |
| 129 | + lines = f_env.readlines() |
| 130 | + except OSError as exc: |
| 131 | + print(f"ERROR: unable to read {src_env}: {exc}", file=sys.stderr) |
| 132 | + return False |
| 133 | + |
| 134 | + seen: set[str] = set() |
| 135 | + keys: list[str] = [] |
| 136 | + for line in lines: |
| 137 | + stripped = line.strip() |
| 138 | + if not stripped or stripped.startswith('#'): |
| 139 | + continue |
| 140 | + m = _KEY_REGEX.match(stripped) |
| 141 | + if not m: |
| 142 | + continue |
| 143 | + key = m.group(1) |
| 144 | + if key not in seen: |
| 145 | + seen.add(key) |
| 146 | + keys.append(key) |
| 147 | + |
| 148 | + header = [ |
| 149 | + '# Generated by catch-dotenv hook.', |
| 150 | + '# Variable names only – fill in sample values as needed.', |
| 151 | + '', |
| 152 | + ] |
| 153 | + body = [f"{k}=" for k in keys] |
| 154 | + try: |
| 155 | + _atomic_write(example_file, '\n'.join(header + body) + '\n') |
| 156 | + return True |
| 157 | + except OSError as exc: # pragma: no cover |
| 158 | + print( |
| 159 | + f"ERROR: unable to write '{example_file}': {exc}", |
| 160 | + file=sys.stderr, |
| 161 | + ) |
| 162 | + return False |
| 163 | + |
| 164 | + |
| 165 | +def _has_env(filenames: Iterable[str], env_file: str) -> bool: |
| 166 | + """Return True if any staged path refers to target env file by basename.""" |
| 167 | + return any(os.path.basename(name) == env_file for name in filenames) |
| 168 | + |
| 169 | + |
| 170 | +def _print_failure( |
| 171 | + env_file: str, |
| 172 | + gitignore_file: str, |
| 173 | + example_created: bool, |
| 174 | + gitignore_modified: bool, |
| 175 | +) -> None: |
| 176 | + # Match typical hook output style: one short line per action. |
| 177 | + print(f"Blocked committing {env_file}.") |
| 178 | + if gitignore_modified: |
| 179 | + print(f"Updated {gitignore_file}.") |
| 180 | + if example_created: |
| 181 | + print('Generated .env.example.') |
| 182 | + print(f"Remove {env_file} from the commit and retry.") |
| 183 | + |
| 184 | + |
| 185 | +def main(argv: Sequence[str] | None = None) -> int: |
| 186 | + """Hook entry-point.""" |
| 187 | + parser = argparse.ArgumentParser( |
| 188 | + description='Blocks committing .env files.', |
| 189 | + ) |
| 190 | + parser.add_argument( |
| 191 | + 'filenames', |
| 192 | + nargs='*', |
| 193 | + help='Staged filenames (supplied by pre-commit).', |
| 194 | + ) |
| 195 | + parser.add_argument( |
| 196 | + '--create-example', |
| 197 | + action='store_true', |
| 198 | + help='Generate example env file (.env.example).', |
| 199 | + ) |
| 200 | + args = parser.parse_args(argv) |
| 201 | + env_file = DEFAULT_ENV_FILE |
| 202 | + # Use current working directory as repository root (pre-commit executes |
| 203 | + # hooks from the repo root). |
| 204 | + repo_root = os.getcwd() |
| 205 | + gitignore_file = os.path.join(repo_root, DEFAULT_GITIGNORE_FILE) |
| 206 | + example_file = os.path.join(repo_root, DEFAULT_EXAMPLE_ENV_FILE) |
| 207 | + env_abspath = os.path.join(repo_root, env_file) |
| 208 | + |
| 209 | + if not _has_env(args.filenames, env_file): |
| 210 | + return 0 |
| 211 | + |
| 212 | + gitignore_modified = ensure_env_in_gitignore( |
| 213 | + env_file, |
| 214 | + gitignore_file, |
| 215 | + GITIGNORE_BANNER, |
| 216 | + ) |
| 217 | + example_created = False |
| 218 | + if args.create_example: |
| 219 | + # Source env is always looked up relative to repo root |
| 220 | + if os.path.exists(env_abspath): |
| 221 | + example_created = create_example_env( |
| 222 | + env_abspath, |
| 223 | + example_file, |
| 224 | + ) |
| 225 | + |
| 226 | + _print_failure( |
| 227 | + env_file, |
| 228 | + gitignore_file, |
| 229 | + example_created, |
| 230 | + gitignore_modified, |
| 231 | + ) |
| 232 | + return 1 # Block commit |
| 233 | + |
| 234 | + |
| 235 | +if __name__ == '__main__': |
| 236 | + raise SystemExit(main()) |
0 commit comments