import { Command } from 'commander'; import path from 'path'; import fs from 'fs'; import { getProjectPath } from '../../../../helpers/cluserHelper'; import { normalizeName, searchSchema, } from '../../../../helpers/profileGeneratorHelper'; import inquirer from 'inquirer'; import { parse, stringify } from 'yaml'; import { setEntityColumnsSourceId, setEntityColumnsKeys, setEntityColumnsTrackForChanges, setEntityColumnsVisibility, } from '../../../../helpers/entityHelper'; import { composeProfile } from '../../../compose/composeCommand'; export function RegenerateSchemaCommand(): Command { const cmd = new Command('regenerate') .alias('rg') .description( 'Regenerate a table with new columns, replacing old ones, without touching the schema.', ) .option( '-n, --schema-name ', "Specify the schema name whose table needs to be regenerated, e.g., 'warehouse mapping'.", ) .action(async ({ schemaName }) => { const componentPath = getProjectPath(); const schemaYml = (await searchSchema(schemaName)) as any; const schemaDir = path.join(componentPath, 'schemas'); if (!fs.existsSync(schemaDir)) { console.error(`Schema directory does not exist: ${schemaDir}`); return; } const normalizedSchemaName = normalizeName(schemaName); const schemaVariableKey = `${normalizedSchemaName.camelCaseName}_Schema`; const tableFilePath = path.join( schemaDir, `${schemaVariableKey}_Table.yaml`, ); if (!fs.existsSync(tableFilePath)) { console.error(`Table file not found in directory: ${schemaDir}`); return; } const tableContent = parse(fs.readFileSync(tableFilePath, 'utf8')); const { columns } = await inquirer.prompt([ { type: 'input', name: 'columns', message: 'Please provide new table columns (comma-separated):', }, ]); const columnsArray = columns.split(',').map((col) => col.trim()); tableContent.tables[0].columns = columnsArray.reduce((acc, col) => { acc[col.replace(/[^a-zA-Z0-9]+/g, '_')] = { name: col, indexGroups: [], }; return acc; }, {}); const updatedTableYml = stringify(tableContent, { keepSourceTokens: true, lineWidth: 0, }); fs.writeFileSync(tableFilePath, updatedTableYml); console.log(`Table regenerated successfully: Schema Name: ${schemaName} New Columns: ${columnsArray.join(', ')}`); await setEntityColumnsSourceId(schemaYml.tableId, '', 'table'); await setEntityColumnsKeys(schemaYml.tableId, '', 'table'); await setEntityColumnsTrackForChanges(schemaYml.tableId, '', 'table'); await setEntityColumnsVisibility(schemaYml.tableId, '', 'table'); await composeProfile(); }); return cmd; }