Refactor and clean code

This commit is contained in:
Kim Biesbjerg 2016-12-09 14:40:21 +01:00
parent 73801a9cc5
commit 59ef277c64
6 changed files with 37 additions and 42 deletions

View File

@ -10,8 +10,8 @@ const dest = '/your/project/template.json';
try { try {
const collection: StringCollection = extractor.process(src); const collection: StringCollection = extractor.process(src);
const output: string = extractor.save(dest); const serialized: string = extractor.save(dest);
console.log({ strings: collection.keys(), output: output }); console.log({ strings: collection.keys(), serialized });
} catch (e) { } catch (e) {
console.log(`Something went wrong: ${e.toString()}`); console.log(`Something went wrong: ${e.toString()}`);
} }

View File

@ -10,18 +10,18 @@ import * as fs from 'fs';
export class Extractor { export class Extractor {
public patterns: string[] = [
'/**/*.html',
'/**/*.ts',
'/**/*.js'
];
public parsers: ParserInterface[] = [ public parsers: ParserInterface[] = [
new PipeParser(), new PipeParser(),
new DirectiveParser(), new DirectiveParser(),
new ServiceParser() new ServiceParser()
]; ];
public find: string[] = [
'/**/*.html',
'/**/*.ts',
'/**/*.js'
];
public collection: StringCollection = new StringCollection(); public collection: StringCollection = new StringCollection();
public constructor(public serializer: SerializerInterface) { } public constructor(public serializer: SerializerInterface) { }
@ -30,7 +30,7 @@ export class Extractor {
* Process dir * Process dir
*/ */
public process(dir: string): StringCollection { public process(dir: string): StringCollection {
this._getFiles(dir).forEach(path => { this._readDir(dir, this.patterns).forEach(path => {
const contents: string = fs.readFileSync(path, 'utf-8'); const contents: string = fs.readFileSync(path, 'utf-8');
this.parsers.forEach((parser: ParserInterface) => { this.parsers.forEach((parser: ParserInterface) => {
this.collection.merge(parser.extract(contents, path)); this.collection.merge(parser.extract(contents, path));
@ -57,20 +57,14 @@ export class Extractor {
} }
/** /**
* Get all files in dir that matches glob patterns * Get all files in dir matching find patterns
*/ */
protected _getFiles(dir: string): string[] { protected _readDir(dir: string, patterns: string[]): string[] {
let results: string[] = []; return patterns.reduce((results, pattern) => {
return glob.sync(dir + pattern)
this.find.forEach(pattern => { .filter(path => fs.statSync(path).isFile())
const files = glob .concat(results);
.sync(dir + pattern) }, []);
.filter(path => fs.statSync(path).isFile());
results = [...results, ...files];
});
return results;
} }
} }

View File

@ -5,14 +5,14 @@ export abstract class AbstractTemplateParser {
* makes the assumption that it is an Angular Component * makes the assumption that it is an Angular Component
*/ */
protected _isAngularComponent(path: string): boolean { protected _isAngularComponent(path: string): boolean {
return new RegExp(/\.(ts|js)$/, 'i').test(path); return new RegExp(/\.ts|js$/, 'i').test(path);
} }
/** /**
* Extracts inline template from components * Extracts inline template from components
*/ */
protected _extractInlineTemplate(contents: string): string { protected _extractInlineTemplate(contents: string): string {
const match = new RegExp(/template\s?:\s?("|\'|`)((.|[\r\n])+?[^\\])\1/).exec(contents); const match = new RegExp(/template\s*:\s*(["'`])((.|[\r\n])+?[^\\])\1/).exec(contents);
if (match !== null) { if (match !== null) {
return match[2]; return match[2];
} }

View File

@ -19,7 +19,7 @@ export class DirectiveParser extends AbstractTemplateParser implements ParserInt
template = this._normalizeTemplateAttributes(template); template = this._normalizeTemplateAttributes(template);
$(template) $(template)
.find('[translate],[ng2-translate]') .find('[translate], [ng2-translate]')
.addBack() .addBack()
.each((i: number, element: CheerioElement) => { .each((i: number, element: CheerioElement) => {
const $element = $(element); const $element = $(element);
@ -31,8 +31,8 @@ export class DirectiveParser extends AbstractTemplateParser implements ParserInt
$element $element
.contents() .contents()
.toArray() .toArray()
.filter(textNode => textNode.type === 'text') .filter(node => node.type === 'text')
.map(textNode => textNode.nodeValue.trim()) .map(node => node.nodeValue.trim())
.filter(text => text.length > 0) .filter(text => text.length > 0)
.forEach(text => collection.add(text)); .forEach(text => collection.add(text));
} }

View File

@ -15,7 +15,7 @@ export class PipeParser extends AbstractTemplateParser implements ParserInterfac
protected _parseTemplate(template: string): StringCollection { protected _parseTemplate(template: string): StringCollection {
const collection = new StringCollection(); const collection = new StringCollection();
const regExp = new RegExp(/([\'"`])([^\1\r\n]*)\1\s+\|\s*translate(:.*?)?/, 'g'); const regExp = new RegExp(/(['"`])([^\1\r\n]*)\1\s*\|\s*translate(:.*?)?/, 'g');
let matches; let matches;
while (matches = regExp.exec(template)) { while (matches = regExp.exec(template)) {

View File

@ -11,13 +11,14 @@ export class ServiceParser implements ParserInterface {
return collection; return collection;
} }
const methodRegExp: RegExp = new RegExp(/(?:get|instant)\s*\(\s*(\[?([\'"`])([^\1\r\n]+)\2\]?)/); const methodRegExp: RegExp = new RegExp(/(?:get|instant)\s*\(\s*(\[?(['"`])([^\1\r\n]+)\2\]?)/);
const regExp: RegExp = new RegExp(`${translateServiceVar}\.${methodRegExp.source}`, 'g'); const regExp: RegExp = new RegExp(`${translateServiceVar}\.${methodRegExp.source}`, 'g');
let matches; let matches;
while (matches = regExp.exec(contents)) { while (matches = regExp.exec(contents)) {
if (this._stringContainsArray(matches[1])) { if (this._stringContainsArray(matches[1])) {
collection.add(this._stringToArray(matches[1])); const matchCollection = StringCollection.fromArray(this._stringToArray(matches[1]));
collection.merge(matchCollection);
} else { } else {
collection.add(matches[3]); collection.add(matches[3]);
} }
@ -26,6 +27,18 @@ export class ServiceParser implements ParserInterface {
return collection; return collection;
} }
/**
* Extracts name of TranslateService variable for use in patterns
*/
protected _extractTranslateServiceVar(contents: string): string {
const matches = contents.match(/([a-z0-9_]+)\s*:\s*TranslateService/i);
if (matches === null) {
return '';
}
return matches[1];
}
/** /**
* Checks if string contains an array * Checks if string contains an array
*/ */
@ -44,16 +57,4 @@ export class ServiceParser implements ParserInterface {
return []; return [];
} }
/**
* Extracts name of TranslateService variable for use in patterns
*/
protected _extractTranslateServiceVar(contents: string): string {
const matches = contents.match(/([a-z0-9_]+)\s*:\s*TranslateService/i);
if (matches === null) {
return '';
}
return matches[1];
}
} }