Update generate-choice-labels.cjs

This commit is contained in:
David Bruno Vontor
2026-01-26 09:54:56 +01:00
parent 7c768c9be3
commit 304194d7ec

View File

@@ -1,22 +1,29 @@
#!/usr/bin/env node #!/usr/bin/env node
/** /**
* Generates TypeScript file with choice labels from Orval-generated enum files * Generates TypeScript file with choice labels from Django TextChoices in Python models
* *
* Usage: node scripts/generate-choice-labels.js * Usage: node scripts/generate-choice-labels.cjs
* *
* This script reads the TypeScript enum files generated by Orval and extracts * This script reads Django models.py files from backend apps and extracts
* choice labels from JSDoc comments (format: * `value` - Label) and generates * TextChoices class definitions (format: VALUE = 'value', 'Czech Label')
* a TypeScript file with runtime-accessible label mappings. * and generates a TypeScript file with runtime-accessible label mappings.
*
* This is more reliable than parsing OpenAPI schema since it reads directly
* from the source of truth (Python models).
*/ */
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
// Configuration // Configuration - Backend Python apps to scan
const MODELS_DIRS = [ const PYTHON_APPS = [
path.join(__dirname, '../src/api/generated/private/models'), path.join(__dirname, '../../backend/account'),
path.join(__dirname, '../src/api/generated/public/models') path.join(__dirname, '../../backend/booking'),
path.join(__dirname, '../../backend/commerce'),
path.join(__dirname, '../../backend/servicedesk'),
path.join(__dirname, '../../backend/product'),
path.join(__dirname, '../../backend/configuration'),
]; ];
const OUTPUT_PATH = path.join(__dirname, '../src/constants/choiceLabels.ts'); const OUTPUT_PATH = path.join(__dirname, '../src/constants/choiceLabels.ts');
@@ -28,112 +35,119 @@ function camelToSnakeCase(str) {
.toUpperCase(); .toUpperCase();
} }
// Extract enum labels from TypeScript file comments // Extract TextChoices from Python models.py file
function parseEnumFile(filePath) { function parsePythonModels(filePath) {
const content = fs.readFileSync(filePath, 'utf8'); const content = fs.readFileSync(filePath, 'utf8');
const filename = path.basename(filePath, '.ts'); const results = {};
// Extract all JSDoc comment blocks // First, find all model class definitions to track context
// Match all: /** ... */ // Match: class ModelName(SoftDeleteModel): or class ModelName(models.Model):
const commentRegex = /\/\*\*\s*\n([\s\S]*?)\*\//g; const modelRegex = /class\s+(\w+)\([^)]*(?:Model|SoftDeleteModel)[^)]*\):/g;
const comments = []; const modelPositions = [];
let match; let modelMatch;
while ((match = commentRegex.exec(content)) !== null) { while ((modelMatch = modelRegex.exec(content)) !== null) {
comments.push(match[1]); modelPositions.push({
name: modelMatch[1],
start: modelMatch.index,
});
} }
if (comments.length === 0) { // Match TextChoices class definitions:
return null; // class RoleChoices(models.TextChoices): or class StatusChoices(models.TextChoices):
} const classRegex = /class\s+(\w+Choices)\s*\([^)]*TextChoices[^)]*\):\s*\n((?:\s+\w+\s*=\s*[^\n]+\n?)+)/g;
// Try to find labels in all comment blocks let classMatch;
// Parse labels from comment lines like: * `value` - Label while ((classMatch = classRegex.exec(content)) !== null) {
// Note: The asterisk might have 0 or more spaces after it const [, className, classBody] = classMatch;
const labelPattern = /\*\s*`([^`]+)`\s*-\s*(.+)/g; const choicePosition = classMatch.index;
const labels = {};
// Find the parent model class (closest model before this choice)
for (const comment of comments) { let parentModel = null;
let labelMatch; for (let i = modelPositions.length - 1; i >= 0; i--) {
while ((labelMatch = labelPattern.exec(comment)) !== null) { if (modelPositions[i].start < choicePosition) {
const [, value, label] = labelMatch; parentModel = modelPositions[i].name;
labels[value] = label.trim(); break;
}
}
// Generate enum name based on parent model + choice class name
// MarketSlot + StatusChoices -> MarketSlotStatusEnum
// Reservation + StatusChoices -> ReservationStatusEnum (but spec uses Status9e5Enum)
// Order + StatusChoices -> OrderStatusEnum
// For top-level choices (no parent), use just the choice name
let enumName;
if (parentModel && className === 'StatusChoices') {
// Use parent model name for nested StatusChoices
enumName = `${parentModel}${className.replace(/Choices$/, 'Enum')}`;
} else {
// Top-level choices like RoleChoices, AccountTypeChoices
enumName = className.replace(/Choices$/, 'Enum');
}
// Parse individual choice lines: ADMIN = 'admin', 'Administrátor'
const choiceRegex = /\w+\s*=\s*['"]([^'"]+)['"],\s*['"]([^'"]+)['"]/g;
const labels = {};
let choiceMatch;
while ((choiceMatch = choiceRegex.exec(classBody)) !== null) {
const [, value, label] = choiceMatch;
labels[value] = label;
}
if (Object.keys(labels).length > 0) {
results[enumName] = labels;
} }
} }
// Only return if we found labels return results;
if (Object.keys(labels).length === 0) {
return null;
}
// Extract enum name from the type definition
// Match: export type EnumName = ...
const typeMatch = content.match(/export\s+type\s+(\w+Enum)\s*=/);
const enumName = typeMatch ? typeMatch[1] : null;
if (!enumName) {
return null;
}
return { enumName, labels };
} }
// Main function // Main function
function generateLabels() { function generateLabels() {
console.log('🔍 Scanning Orval-generated enum files...'); console.log('🔍 Scanning Python models for TextChoices...');
const enums = {}; const enums = {};
let totalEnumFiles = 0; let totalFiles = 0;
// Check each models directory // Scan each backend app for models.py
for (const MODELS_DIR of MODELS_DIRS) { for (const appDir of PYTHON_APPS) {
const dirName = path.basename(path.dirname(MODELS_DIR)); const appName = path.basename(appDir);
const modelsFile = path.join(appDir, 'models.py');
if (!fs.existsSync(MODELS_DIR)) { if (!fs.existsSync(modelsFile)) {
console.warn(`⚠️ Models directory not found: ${MODELS_DIR}`);
continue; continue;
} }
console.log(`📁 Scanning ${dirName}/models...`); console.log(`📁 Scanning ${appName}/models.py...`);
totalFiles++;
// Read all enum files // Parse the models file
const files = fs.readdirSync(MODELS_DIR); const results = parsePythonModels(modelsFile);
const enumFiles = files.filter(f => f.endsWith('Enum.ts'));
console.log(` Found ${enumFiles.length} enum files`); for (const [enumName, labels] of Object.entries(results)) {
totalEnumFiles += enumFiles.length; if (enums[enumName]) {
// Check for conflicts
// Parse each enum file const existing = JSON.stringify(enums[enumName]);
for (const file of enumFiles) { const current = JSON.stringify(labels);
const filePath = path.join(MODELS_DIR, file);
const result = parseEnumFile(filePath); if (existing !== current) {
console.warn(` ⚠️ ${enumName}: Conflict in ${appName}, keeping first version`);
if (result) {
// Check if enum already exists from another directory
if (enums[result.enumName]) {
// Compare labels to see if they're the same
const existing = JSON.stringify(enums[result.enumName]);
const current = JSON.stringify(result.labels);
if (existing !== current) {
console.warn(` ⚠️ ${result.enumName}: Different labels found in ${dirName}, keeping first version`);
}
} else {
enums[result.enumName] = result.labels;
console.log(`${result.enumName}: ${Object.keys(result.labels).length} labels`);
} }
} else {
enums[enumName] = labels;
console.log(`${enumName}: ${Object.keys(labels).length} labels`);
} }
} }
} }
if (totalEnumFiles === 0) { if (totalFiles === 0) {
console.error('❌ No enum files found in any models directory'); console.error('❌ No models.py files found in backend apps');
console.error(' Run "npm run api:gen" first to generate API client');
process.exit(1); process.exit(1);
} }
if (Object.keys(enums).length === 0) { if (Object.keys(enums).length === 0) {
console.error('❌ No enum labels found in generated files'); console.error('❌ No TextChoices found in Python models');
process.exit(1); process.exit(1);
} }
@@ -141,10 +155,12 @@ function generateLabels() {
console.log('📝 Generating TypeScript file...'); console.log('📝 Generating TypeScript file...');
const tsContent = `/** const tsContent = `/**
* Auto-generated choice labels from Orval-generated enum files * Auto-generated choice labels from Django TextChoices in Python models
* Generated by: scripts/generate-choice-labels.cjs * Generated by: scripts/generate-choice-labels.cjs
* *
* DO NOT EDIT MANUALLY - Run \`npm run api:gen\` to regenerate * DO NOT EDIT MANUALLY - Run \`npm run api:gen\` to regenerate
*
* Source: backend (TextChoices classes)
*/ */
${Object.entries(enums).map(([enumName, labels]) => { ${Object.entries(enums).map(([enumName, labels]) => {