rojects/source/server/localeGenerator.ts

84 lines
2.4 KiB
TypeScript
Raw Normal View History

import fs from 'fs';
import path from 'path';
import { ROOT } from './rootDir';
const LOCALES_DIR = path.join( ROOT, 'source', 'locale-data', 'en' );
const GENERATED_DIR = path.join( ROOT, 'source', 'locales', 'generated' );
function toPascalCase( name: string ): string
{
return name
.split( /[-_]/ )
.map( part => part.charAt( 0 ).toUpperCase() + part.slice( 1 ) )
.join( '' );
}
function toMemberName( fileName: string ): string
{
const withUnderscores = fileName.replace( /\./g, '_' );
return withUnderscores.replace( /-([a-zA-Z])/g, ( _, c: string ) => c.toUpperCase() );
}
function generateDir( absLocaleDir: string, enRoot: string, absOutDir: string, className: string ): void
{
const files: { memberName: string; relativePath: string }[] = [];
const dirs: { dirName: string; childClassName: string }[] = [];
for ( const entry of fs.readdirSync( absLocaleDir ) )
{
if ( entry.endsWith( '.md' ) ) continue;
const abs = path.join( absLocaleDir, entry );
if ( fs.statSync( abs ).isDirectory() )
{
const childClassName = toPascalCase( entry );
dirs.push( { dirName: entry, childClassName } );
generateDir( abs, enRoot, path.join( absOutDir, entry ), childClassName );
}
else
{
const rel = path.relative( enRoot, abs ).replace( /\\/g, '/' );
files.push( { memberName: toMemberName( entry ), relativePath: rel } );
}
}
const lines: string[] = [];
lines.push( '// Auto-generated by localeGenerator — do not edit manually.' );
if ( dirs.length > 0 )
{
lines.push( '' );
for ( const { dirName, childClassName } of dirs )
{
lines.push( `import { ${childClassName} } from './${dirName}/${childClassName}.js';` );
}
}
lines.push( '' );
lines.push( `export class ${className}` );
lines.push( '{' );
for ( const { memberName, relativePath } of files )
{
lines.push( ` static readonly ${memberName} = '${relativePath}';` );
}
for ( const { childClassName } of dirs )
{
lines.push( ` static readonly ${childClassName} = ${childClassName};` );
}
lines.push( '}' );
fs.mkdirSync( absOutDir, { recursive: true } );
fs.writeFileSync( path.join( absOutDir, `${className}.ts` ), lines.join( '\n' ) + '\n', 'utf8' );
}
export function generateLocales(): void
{
if ( !fs.existsSync( LOCALES_DIR ) ) return;
generateDir( LOCALES_DIR, LOCALES_DIR, GENERATED_DIR, 'Locales' );
}