diff --git a/src/commands/migrate.ts b/src/commands/migrate.ts new file mode 100644 index 0000000..f6acd1d --- /dev/null +++ b/src/commands/migrate.ts @@ -0,0 +1,45 @@ +import { Command } from 'commander'; +import * as fs from 'fs'; +import * as path from 'path'; +import * as prettier from 'prettier'; +import { parseEnvFile } from '../core/parser'; +import { parseSchemaFromEnv } from '../core/validator'; + +export function createMigrateCommand(): Command { + const cmd = new Command('migrate'); + + cmd + .description('Generate schema.json from existing .env file') + .option('-e, --env ', 'Path to .env file', '.env') + .option('-o, --output ', 'Output file path (schema.json if not specified)') + .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); + const schema = parseSchemaFromEnv(parsedEnv.flat); + + const schemaJson = JSON.stringify(schema, null, 2); + const formattedJson = await prettier.format(schemaJson, { parser: 'json' }); + + const outputPath = options.output + ? path.resolve(options.output) + : path.join(process.cwd(), 'schema.json'); + + fs.writeFileSync(outputPath, formattedJson); + console.log(`✓ Schema generated at ${outputPath}`); + console.log('\nGenerated schema:'); + console.log(formattedJson); + } catch (error) { + console.error('Error during migration:', (error as Error).message); + process.exit(1); + } + }); + + return cmd; +}