ngx-translate-extract/src/extractor.ts

77 lines
1.8 KiB
TypeScript
Raw Normal View History

2016-12-03 17:09:39 +03:00
import { ParserInterface } from './parsers/parser.interface';
import { PipeParser } from './parsers/pipe.parser';
import { DirectiveParser } from "./parsers/directive.parser";
import { ServiceParser } from './parsers/service.parser';
2016-12-03 17:09:39 +03:00
import { SerializerInterface } from './serializers/serializer.interface';
2016-12-05 00:53:59 +03:00
import * as lodash from 'lodash';
import * as glob from 'glob';
import * as fs from 'fs';
2016-12-03 17:09:39 +03:00
export class Extractor {
public parsers: ParserInterface[] = [
new PipeParser(),
new ServiceParser(),
new DirectiveParser()
];
2016-12-03 17:09:39 +03:00
2016-12-05 00:53:59 +03:00
public globPatterns: string[] = [
'/**/*.ts',
'/**/*.html'
];
public messages: string[] = [];
2016-12-03 17:09:39 +03:00
public constructor(public serializer: SerializerInterface) { }
/**
* Extracts messages from paths
*/
2016-12-05 00:53:59 +03:00
public extract(dir: string): string[] {
2016-12-03 17:09:39 +03:00
let messages = [];
2016-12-05 00:53:59 +03:00
this.globPatterns.forEach(globPattern => {
const filePaths = glob.sync(dir + globPattern);
filePaths
.filter(filePath => fs.statSync(filePath).isFile())
.forEach(filePath => {
const result = this._extractMessages(filePath);
messages = [...messages, ...result];
});
2016-12-03 17:09:39 +03:00
});
2016-12-05 00:53:59 +03:00
return this.messages = lodash.uniq(messages);
2016-12-03 17:09:39 +03:00
}
/**
* Serialize and return output
*/
public serialize(): string {
return this.serializer.serialize(this.messages);
}
/**
* Serialize and save to destination
*/
public save(destination: string): string {
const data = this.serialize();
2016-12-05 00:53:59 +03:00
fs.writeFileSync(destination, data);
2016-12-03 17:09:39 +03:00
return data;
}
/**
* Extract messages from file using specialized parser
*/
protected _extractMessages(filePath: string): string[] {
let results = [];
2016-12-03 17:09:39 +03:00
2016-12-05 00:53:59 +03:00
const contents: string = fs.readFileSync(filePath, 'utf-8');
this.parsers.forEach((parser: ParserInterface) => {
results = results.concat(parser.process(contents));
});
2016-12-03 17:09:39 +03:00
return results;
2016-12-03 17:09:39 +03:00
}
}