angular-cn/aio/tools/translator/translate.ts

59 lines
1.9 KiB
TypeScript
Raw Normal View History

import * as fs from 'fs';
import * as _ from 'lodash';
import { DictEntry } from './dict-entry';
import { dirs } from './dirs';
import { listMarkdownFiles } from './extractor';
import { indentOf, normalizeLines, repeat } from './utils';
2018-03-02 19:13:52 -05:00
export const dict = require('./dict-3.json') as DictEntry[];
export function lookup(english: string, filename: RegExp = /.*/): DictEntry[] {
const entries = dict
.filter(entry => filename.test(entry.sourceFile))
.filter(entry => kernelText(entry.original) === kernelText(english));
return _.uniqBy(entries, 'translation');
}
export function kernelText(text: string): string {
2018-03-06 19:48:31 -05:00
return text
.replace(/[\s\n]+/g, '')
.replace(/\.$/g, '')
.trim();
}
2018-03-01 09:52:16 -05:00
export function translate(content: string): string[] {
const lines = normalizeLines(content)
.split(/\n+\s*\n+/);
2018-03-01 09:52:16 -05:00
return lines
.map(line => {
if (!line.trim()) {
return line;
}
2018-03-03 04:47:09 -05:00
const translations = lookup(line);
2018-03-01 09:52:16 -05:00
const indent = indentOf(line);
const padding = repeat(indent);
if (translations.length === 0) {
return line;
} else if (translations.length === 1) {
return line + '\n\n' + padding + translations[0].translation;
} else {
return line + '\n\n' + padding + translations[translations.length - 1].translation;
2018-03-01 09:52:16 -05:00
}
});
}
export function translateFile(sourceFile: string, targetFile: string): void {
const content = fs.readFileSync(sourceFile, 'utf-8');
const result = translate(content);
fs.writeFileSync(targetFile, result.join('\n\n').trim() + '\n', 'utf-8');
}
export function translateDirectory(sourceDir: string, targetDir: string): void {
const files = listMarkdownFiles(sourceDir);
files.forEach(fileName => {
2018-03-03 04:47:09 -05:00
console.log('translating ...', fileName);
translateFile(fileName, fileName.replace(/^.*content-en\//, dirs.content));
2018-03-03 04:47:09 -05:00
console.log('translated ', fileName);
});
}