env-compare
v2.1.0
Published
A professional-grade CLI utility to manage, compare, and synchronize multiple .env files without losing comments or formatting
Maintainers
Readme
env-compare
A professional-grade CLI utility for developers to manage, compare, validate, and synchronize multiple
.envfiles simultaneously without losing comments or formatting.
Features
- GCP Secret Manager Integration: Pull, push, sync, and list secrets directly from Google Cloud
- Multi-Format Export: Convert
.envfiles to Docker Compose, Kubernetes (ConfigMap/Secret), JSON, YAML, and Terraform formats - Multi-File Comparison: Compare unlimited
.envfiles side-by-side in a beautiful matrix table - Comment-Safe Operations: Preserves all comments, empty lines, and formatting during sync operations
- Security-First: Auto-masks sensitive values containing SECRET, KEY, TOKEN, or PASS
- Beautiful CLI UI: Color-coded output with intuitive symbols
- Interactive Sync: "Make Same" engine to synchronize files with granular control
- Smart Discovery: Auto-detect all
.env*files or specify custom file lists - Schema Validation: Validate .env files against JSON or YAML schemas
- Diff Mode: Show only differences between files, hiding matching keys
- Search/Filter: Filter comparison results by key name patterns
- Watch Mode: Live monitoring with auto-refresh on file changes
- Interactive Merge: Merge multiple .env files with conflict resolution
- Zero Config: Works out of the box with sensible defaults
Installation
Global Installation (Recommended)
npm install -g env-compareLocal Development Installation
# Clone or navigate to the project directory
cd env-compare
# Install dependencies
npm install
# Build the project
npm run build
# Link for local development
npm link
# Now you can use 'env-compare' from anywhereUnlink
npm unlink -g env-compareQuick Start
Compare .env Files
Auto-discover all .env files in current directory:
env-compareCompare specific files:
env-compare .env .env.production .env.stagingOutput Example:
┌─────────────────────────┬──────────────────────────────┬──────────────────────────────┐
│ Key │ .env │ .env.production │
├─────────────────────────┼──────────────────────────────┼──────────────────────────────┤
│ DATABASE_URL │ OK postgres://localhost │ OK postgres://localhost │
│ API_SECRET_KEY │ OK sk_l***** │ DIFF sk_p***** │
│ DEBUG │ OK true │ MISSING │
└─────────────────────────┴──────────────────────────────┴──────────────────────────────┘
Summary:
Matching: 1
Mismatched: 1
Missing: 1
Total Keys: 3Commands
env-compare [files...]
Compare multiple .env files and display differences in a matrix table.
Arguments:
[files...]- Optional list of files to compare. If omitted, auto-discovers all.env*files.
Options:
-f, --filter <term>- Filter keys by search term (case-insensitive)
env-compare export <envFile>
Export a .env file to various formats for Docker, Kubernetes, Terraform, and more.
Arguments:
<envFile>- The .env file to export (required)
Options:
--format <format>- Output format (Required:docker-compose,k8s-config,k8s-secret,json,yaml,terraform)-o, --output <file>- Output file path (if omitted, prints to console)--name <name>- Resource name for export (e.g., ConfigMap name)--namespace <namespace>- Kubernetes namespace
Examples:
# Auto-discover mode
env-compare
# Specific files
env-compare .env .env.local .env.production
# Filter by key name
env-compare --filter DATABASE .env .env.production
# Custom named files
env-compare config/.env.dev config/.env.prod
# Export to Docker Compose
env-compare export .env --format docker-compose
# Export to Kubernetes Secret (auto base64-encoded)
env-compare export .env --format k8s-secret --name my-app-secret -o secret.yaml
# Export to Terraform variables
env-compare export .env --format terraform -o terraform.tfvarsenv-compare gcp-pull
Pull secrets from Google Cloud Secret Manager and convert them to .env format.
Options:
--project-id <id>- GCP Project ID (required)--key-file <path>- Path to service account key file--filter <prefix>- Filter secrets by name prefix-o, --output <file>- Output file (default:.env.gcp)
Example:
env-compare gcp-pull --project-id my-project -o .env.productionenv-compare gcp-push <envFile>
Push local .env values to GCP Secret Manager. Creates new secrets or adds new versions to existing ones.
Arguments:
<envFile>- Local .env file to push
Options:
--project-id <id>- GCP Project ID (required)--key-file <path>- Path to service account key file--dry-run- Show what would change without making changes
Example:
env-compare gcp-push .env.production --project-id my-project --dry-runenv-compare gcp-sync <envFile>
Check for synchronization drift between your local .env and GCP Secret Manager.
Example:
env-compare gcp-sync .env --project-id my-projectenv-compare sync [files...]
Interactive synchronization tool to make all .env files consistent.
How it works:
- Choose Master: Select which file is the "Source of Truth"
- Detect Differences: Identifies missing keys in other files
- Granular Control: Prompts for each missing key individually
- Safe Writes: Appends keys without modifying existing content or comments
Arguments:
[files...]- Optional list of files to sync. If omitted, auto-discovers all.env*files.
Example Session:
$ env-compare sync
Discovered .env files:
1. .env
2. .env.production
? Select the Source of Truth (Master) file: .env
Master file selected: .env
.env.production is missing 2 key(s):
? Add DEBUG="true" to .env.production? Yes
Added DEBUG to .env.production
? Add NEW_FEATURE="enabled" to .env.production? No
Skipped NEW_FEATURE
==================================================
Sync complete! Added 1 key(s) in total.env-compare diff [files...]
Show only the differences between .env files, hiding keys that match across all files.
Arguments:
[files...]- Optional list of files to compare. If omitted, auto-discovers all.env*files.
Examples:
# Show only differences
env-compare diff .env .env.production
# Auto-discover and diff
env-compare diffUse Case: Quickly identify configuration drift between environments without seeing all the matching keys.
env-compare validate <envFile>
Validate a .env file against a JSON or YAML schema. Checks for required keys, type validation, and pattern matching.
Arguments:
<envFile>- The .env file to validate (required)
Options:
-s, --schema <file>- Schema file path (default:.env.schema.json)
Examples:
# Validate using default schema
env-compare validate .env
# Validate using custom JSON schema
env-compare validate .env -s .env.schema.json
# Validate using YAML schema
env-compare validate .env.production -s schemas/production.yamlExample Schema (JSON):
{
"type": "object",
"required": ["APP_NAME", "DATABASE_URL"],
"properties": {
"APP_NAME": {
"type": "string"
},
"APP_ENV": {
"type": "string",
"pattern": "^(development|production|staging)$"
},
"DATABASE_URL": {
"type": "string",
"pattern": "^postgres://"
},
"PORT": {
"type": "string"
}
}
}Example Schema (YAML):
type: object
required:
- APP_NAME
- DATABASE_URL
properties:
APP_NAME:
type: string
APP_ENV:
type: string
pattern: "^(development|production|staging)$"
DATABASE_URL:
type: string
pattern: "^postgres://"env-compare watch [files...]
Watch .env files for changes and automatically refresh the comparison table. Perfect for development workflows.
Arguments:
[files...]- Optional list of files to watch. If omitted, auto-discovers all.env*files.
Examples:
# Watch all discovered files
env-compare watch
# Watch specific files
env-compare watch .env .env.local
# Press Ctrl+C to stop watchingUse Case: Keep a terminal open to monitor configuration changes in real-time during development.
env-compare merge <files...>
Interactively merge multiple .env files into a single file. Automatically detects conflicts and prompts for resolution.
Arguments:
<files...>- Two or more .env files to merge (required)
Options:
-o, --output <file>- Output file path (default:.env.merged)
Examples:
# Merge two files
env-compare merge .env .env.local
# Merge multiple files with custom output
env-compare merge .env .env.dev .env.staging -o .env.combined
# Interactive conflict resolution
# When values differ, you'll be prompted to choose:
# 1. Value from file A
# 2. Value from file B
# 3. Enter custom valueUse Case: Create a consolidated configuration file from multiple sources, with control over conflict resolution.
env-compare init
Generate a sanitized .env.example file by stripping all values while preserving structure and comments.
Options:
-i, --input <file>- Input file (default:.env)-o, --output <file>- Output file (default:.env.example)
Examples:
# Default: .env → .env.example
env-compare init
# Custom input/output
env-compare init -i .env.production -o .env.production.exampleBefore (.env):
# Database Configuration
DATABASE_URL=postgres://user:pass@localhost/db
DATABASE_POOL_SIZE=10
# API Keys
API_SECRET_KEY=sk_live_abc123xyzAfter (.env.example):
# Database Configuration
DATABASE_URL=
DATABASE_POOL_SIZE=
# API Keys
API_SECRET_KEY=Architecture
Comment-Safe Parser
Unlike standard dotenv parsers, env-compare uses a line-by-line parser that treats each line as a structured object:
{
type: 'key' | 'comment' | 'empty',
key?: string,
value?: string,
raw: string,
hasExport: boolean,
lineNumber: number
}This architecture enables:
- Preserving comments during sync operations
- Maintaining exact formatting and whitespace
- Supporting both
KEY=VALUEandexport KEY=VALUEformats - Handling inline comments (e.g.,
KEY=VALUE # comment)
Security Masking
Values are automatically masked when their key contains:
SECRETKEYTOKENPASS/PASSWORDAPI_KEYPRIVATE
Masking Algorithm:
- Shows first ~20% of characters (max 4)
- Replaces rest with
***** - Example:
sk_live_abc123xyz789→sk_l*****
Technical Stack
- Runtime: Node.js ≥16
- Language: TypeScript (ESM)
- GCP SDK:
@google-cloud/secret-manager - Validation:
ajv - Interactive:
inquirer - CLI Core:
commander
Project Structure
env-compare/
├── src/
│ ├── index.ts # CLI entry point
│ ├── lib/
│ │ ├── cloud/ # GCP & Cloud logic
│ │ ├── parser.ts # Comment-safe parser
│ │ ├── compare.ts # Comparison engine
│ │ ├── export.ts # Format exporters
│ │ └── ui.ts # Terminal UI logic
│ └── types/ # TypeScript interfaces
├── dist/ # Compiled JavaScript output
└── README.md # DocumentationExample Use Cases
Use Case 1: Onboarding New Developers
# Generate template for new developers
env-compare init
# New dev fills in .env.local
# Compare to ensure they have all keys
env-compare .env.example .env.localUse Case 2: Pre-Deployment Checks
# Ensure production has all required keys
env-compare .env .env.production
# Sync any missing keys interactively
env-compare sync .env .env.productionUse Case 3: Multi-Environment Management
# Compare all environments at once
env-compare .env.dev .env.staging .env.production
# Show only differences
env-compare diff .env.dev .env.staging .env.production
# Quickly identify configuration driftUse Case 4: CI/CD Integration
# Validate production config before deployment
env-compare validate .env.production -s .env.schema.json
# Exit code 1 if validation fails, perfect for CI pipelinesUse Case 5: Development Workflow
# Watch for changes during development
env-compare watch .env .env.local
# Filter to monitor specific keys
env-compare --filter API .env .env.localAPI / Programmatic Usage
While env-compare is primarily a CLI tool, you can also use its modules programmatically:
import { parseEnvFile, extractKeyValues } from "env-compare/lib/parser.js";
import { compareEnvFiles } from "env-compare/lib/compare.js";
// Parse a .env file
const parsed = parseEnvFile(".env");
const keyValues = extractKeyValues(parsed);
// Compare multiple files
const comparison = compareEnvFiles([".env", ".env.production"]);
console.log(comparison.keys); // All unique keys
console.log(comparison.matrix); // Comparison matrixContributing
Contributions are welcome! This is an open-source project.
Development Setup
# Clone the repository
git clone <your-repo-url>
cd env-compare
# Install dependencies
npm install
# Build
npm run build
# Link for local testing
npm link
# Make changes and test
env-compare --helpRoadmap
Future feature ideas:
- Export comparison results to JSON, HTML, or CSV
- Git integration for cross-branch comparisons
- Cloud secret manager integration (AWS Secrets Manager, Azure Key Vault)
- Encryption/decryption of .env files
- Configuration templates for popular frameworks
License
MIT License - feel free to use this in your projects!
Author
Manish Chhetri
Acknowledgments
Built for developers who manage complex multi-environment configurations.
Support
- Report bugs or request features via GitHub Issues
- Star the project if you find it useful
- Contributions are always welcome
Made by developers, for developers.
