💻 .env Detective Script
Find and fix .env configuration errors before they break your deployment.
#!/usr/bin/env python3
"""
.env Detective - Finds common .env file mistakes
"""
import os
import re
from pathlib import Path
def validate_env_file(filepath='.env'):
"""
Validates .env file for common issues
"""
issues = []
try:
with open(filepath, 'r') as f:
lines = f.readlines()
except FileNotFoundError:
return [f"❌ File '{filepath}' not found"]
for i, line in enumerate(lines, 1):
line = line.strip()
# Skip empty lines and comments
if not line or line.startswith('#'):
continue
# Check for proper KEY=VALUE format
if '=' not in line:
issues.append(f"Line {i}: Missing '=' in assignment")
continue
key, value = line.split('=', 1)
# Check key naming
if not re.match(r'^[A-Z_][A-Z0-9_]*$', key):
issues.append(f"Line {i}: Key '{key}' should be UPPERCASE_WITH_UNDERSCORES")
# Check for empty values
if not value:
issues.append(f"Line {i}: Key '{key}' has empty value")
# Check for spaces around =
if ' =' in line or '= ' in line:
issues.append(f"Line {i}: Remove spaces around '='")
return issues
# Usage example
if __name__ == '__main__':
print("🔍 .env Detective Report")
print("=" * 30)
issues = validate_env_file()
if not issues:
print("✅ No issues found!")
else:
for issue in issues:
print(f"• {issue}")
The Problem: When Your Configuration Files Develop a Personality Disorder
Let's be honest: environment variables are the digital equivalent of that one friend who's great in person but becomes a completely different person over text. They work perfectly on your machine—your local development environment where you've carefully curated the perfect conditions, like a fussy orchid that only blooms when you play classical music and whisper sweet nothings about Kubernetes.
Then you deploy to production, and suddenly your API keys have gone on vacation, your database connections are having an existential crisis, and your entire application is throwing errors like a toddler throwing spaghetti at the wall. The worst part? The error messages are about as helpful as a GPS that just says "you're somewhere."
Here's what usually happens: you've got a .env file that looks perfectly innocent:
API_KEY=super_secret_123
DB_HOST=localhost
# This is my database
DB_PORT=5432 # default postgresLooks fine, right? WRONG. That comment on the same line as DB_PORT? Some parsers will include "# default postgres" as part of the value. That innocent-looking space after the equals sign? Might work with dotenv in Node.js but fail spectacularly with python-dotenv. And don't even get me started on Windows vs Unix line endings—it's like the digital equivalent of the metric vs imperial system debate, except with more swearing.
You spend hours: checking your code, checking your deployment, checking your permissions, checking your sanity. You start questioning reality. "Maybe the variable just doesn't want to be loaded today. Maybe it's taking a mental health day. Maybe I should take a mental health day."
The Solution: Introducing Your Configuration Therapist
I built .env Detective because I got tired of playing "find the invisible syntax error" every time I deployed something. This tool doesn't just point out problems—it explains them in plain English, suggests specific fixes, and validates against multiple parsers so you know exactly what's going to break before it breaks.
Think of it as a therapist for your configuration files. Instead of you screaming "WHY AREN'T YOU WORKING?!" at your terminal, .env Detective calmly says, "I see you have a space after the equals sign on line 3. Some parsers interpret that as part of the value. Would you like me to fix that for you?"
The beauty of this tool is that it's not just checking syntax—it's checking semantics. It understands that different environments (Node.js, Python, Docker) might parse your .env file differently, and it gives you the heads-up before your production deployment becomes a production disaster.
How to Use It: Because Reading Documentation Shouldn't Be Harder Than Using the Tool
Installation is the kind of simple that makes you wonder why you didn't build this yourself:
npm install -g env-file-fixer
# or if you're fancy
pip install env-file-fixerBasic usage is even simpler:
env-detective check .env
# or if you want it to fix things for you
env-detective fix .envHere's what the core checking logic looks like (simplified from the actual source):
def check_env_file(file_path):
"""The main detective work happens here"""
issues = []
with open(file_path, 'r') as f:
for line_num, line in enumerate(f, 1):
# Check for spaces around equals
if ' = ' in line:
issues.append({
'line': line_num,
'type': 'space_around_equals',
'message': 'Spaces around equals can cause parsing issues'
})
# Check for inline comments
if '#' in line and line.split('#')[0].strip():
var_part = line.split('#')[0]
if '=' in var_part and line.strip().endswith('#'):
issues.append({
'line': line_num,
'type': 'inline_comment',
'message': 'Inline comments may be included in value'
})
return issuesCheck out the full source code on GitHub to see all the detective work happening behind the scenes.
Key Features: What Makes This Tool Actually Useful (Besides Saving Your Sanity)
- Detects Common .env File Mistakes: Missing quotes, spaces around equals signs, comments on the same line as variables—all the little things that cause big problems.
- Shows Which Variables Are Actually Being Loaded: Compare what's in your file vs. what your application actually sees. Spoiler: they're often different.
- Suggests Specific Fixes with Explanations: Not just "this is wrong" but "this is wrong because X, and here's how to fix it."
- Validates Against Different .env Parsers: Checks how dotenv, python-dotenv, and other popular parsers will interpret your file, because consistency is apparently too much to ask for.
- Highlights Platform-Specific Issues: Windows vs Unix line endings, case sensitivity issues, and other cross-platform nightmares.
- Auto-Fix Mode: Because sometimes you just want the tool to fix things while you go get another coffee.
Conclusion: Stop Debugging, Start Developing
Here's the reality: debugging environment variables is the programming equivalent of checking if your refrigerator is plugged in when the light won't turn on. It's basic, it's frustrating, and it's almost always something stupid that you should have caught immediately. But when you're deep in code, staring at complex logic, the simple things become invisible.
.env Detective makes those invisible problems visible. It saves you hours of frustration, prevents production outages, and most importantly, preserves what little remains of your sanity after a long day of coding.
Try it out: https://github.com/BoopyCode/env-file-fixer
Because life is too short to spend it debugging configuration files. Unless you're into that sort of thing—no judgment here.
Quick Summary
- What: .env Detective is a CLI tool that finds and fixes common .env file mistakes before they ruin your day.
💬 Discussion
Add a Comment