This commit is contained in:
59
src/commands/generate.ts
Normal file
59
src/commands/generate.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { Command } from 'commander';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { parseEnvFile } from '../core/parser';
|
||||
import { parseSchemaFromEnv } from '../core/validator';
|
||||
import { generateTypeScriptInterface, formatCode } from '../utils/typeGenerator';
|
||||
import { EnvSchema } from '../core/types';
|
||||
|
||||
export function createGenerateCommand(): Command {
|
||||
const cmd = new Command('generate');
|
||||
|
||||
cmd
|
||||
.description('Generate TypeScript interfaces from .env files')
|
||||
.option('-e, --env <path>', 'Path to .env file', '.env')
|
||||
.option('-s, --schema <path>', 'Path to schema.json file')
|
||||
.option('-o, --output <path>', 'Output file path (stdout if not specified)')
|
||||
.option('-n, --name <name>', 'Interface name', 'EnvVariables')
|
||||
.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 interfaceCode = generateTypeScriptInterface(schema, parsedEnv, options.name);
|
||||
const formattedCode = await formatCode(interfaceCode);
|
||||
|
||||
if (options.output) {
|
||||
const outputPath = path.resolve(options.output);
|
||||
fs.writeFileSync(outputPath, formattedCode);
|
||||
console.log(`✓ TypeScript interface written to ${outputPath}`);
|
||||
} else {
|
||||
console.log(formattedCode);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error during generation:', (error as Error).message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
return cmd;
|
||||
}
|
||||
Reference in New Issue
Block a user