diff --git a/src/commands/validate.ts b/src/commands/validate.ts new file mode 100644 index 0000000..cf7618f --- /dev/null +++ b/src/commands/validate.ts @@ -0,0 +1,58 @@ +import { Command } from 'commander'; +import * as fs from 'fs'; +import * as path from 'path'; +import { parseEnvFile } from '../core/parser'; +import { validateEnv, parseSchemaFromEnv } from '../core/validator'; +import { EnvSchema } from '../core/types'; + +export function createValidateCommand(): Command { + const cmd = new Command('validate'); + + cmd + .description('Validate .env files against a schema') + .option('-e, --env ', 'Path to .env file', '.env') + .option('-s, --schema ', 'Path to schema.json file') + .action(async (options) => { + try { + const envPath = path.resolve(options.env); + + if (!fs.existsSync(envPath)) { + console.error(`Error: .env file not found at ${envPath}`); + process.exit(1); + } + + const parsedEnv = parseEnvFile(envPath); + let schema: EnvSchema; + + if (options.schema) { + const schemaPath = path.resolve(options.schema); + if (!fs.existsSync(schemaPath)) { + console.error(`Error: Schema file not found at ${schemaPath}`); + process.exit(1); + } + const schemaContent = fs.readFileSync(schemaPath, 'utf-8'); + schema = JSON.parse(schemaContent); + } else { + schema = parseSchemaFromEnv(parsedEnv.flat); + } + + const result = validateEnv(parsedEnv.flat, schema); + + if (result.valid) { + console.log('✓ Validation passed successfully!'); + process.exit(0); + } else { + console.error('✗ Validation failed:'); + for (const error of result.errors) { + console.error(` - ${error.field}: ${error.message}`); + } + process.exit(1); + } + } catch (error) { + console.error('Error during validation:', (error as Error).message); + process.exit(1); + } + }); + + return cmd; +}