Compare commits
15 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
d0e9a8cd85 | ||
|
f157025f0a | ||
|
ecf629118a | ||
|
ce399ee717 | ||
|
e8bc023ea6 | ||
|
33d8c26a28 | ||
|
b07d929484 | ||
|
a0f2b69f36 | ||
|
13f46a524f | ||
|
6ed962fa6e | ||
|
8aa2774eca | ||
|
37ca29648a | ||
|
97d844c3d2 | ||
|
e7795c5349 | ||
|
9da4939f5d |
12
README.md
12
README.md
@@ -91,12 +91,12 @@ Options:
|
||||
patterns and multiple paths [array] [required]
|
||||
|
||||
Examples:
|
||||
cli.js -i ./src-a/ -i ./src-b/ -o strings.json Extract (ts, html) from multiple paths
|
||||
cli.js -i './{src-a,src-b}/' -o strings.json Extract (ts, html) from multiple paths using brace
|
||||
ngx-translate-extract -i ./src-a/ -i ./src-b/ -o strings.json Extract (ts, html) from multiple paths
|
||||
ngx-translate-extract -i './{src-a,src-b}/' -o strings.json Extract (ts, html) from multiple paths using brace
|
||||
expansion
|
||||
cli.js -i ./src/ -o ./i18n/da.json -o ./i18n/en.json Extract (ts, html) and save to da.json and en.json
|
||||
cli.js -i ./src/ -o './i18n/{en,da}.json' Extract (ts, html) and save to da.json and en.json
|
||||
ngx-translate-extract -i ./src/ -o ./i18n/da.json -o ./i18n/en.json Extract (ts, html) and save to da.json and en.json
|
||||
ngx-translate-extract -i ./src/ -o './i18n/{en,da}.json' Extract (ts, html) and save to da.json and en.json
|
||||
using brace expansion
|
||||
cli.js -i './src/**/*.{ts,tsx,html}' -o strings.json Extract from ts, tsx and html
|
||||
cli.js -i './src/**/!(*.spec).{ts,html}' -o Extract from ts, html, excluding files with ".spec"
|
||||
ngx-translate-extract -i './src/**/*.{ts,tsx,html}' -o strings.json Extract from ts, tsx and html
|
||||
ngx-translate-extract -i './src/**/!(*.spec).{ts,html}' -o Extract from ts, html, excluding files with ".spec"
|
||||
strings.json
|
35
package-lock.json
generated
35
package-lock.json
generated
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@biesbjerg/ngx-translate-extract",
|
||||
"version": "4.2.0",
|
||||
"version": "6.0.0",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
@@ -169,9 +169,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"@types/node": {
|
||||
"version": "12.12.30",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.30.tgz",
|
||||
"integrity": "sha512-sz9MF/zk6qVr3pAnM0BSQvYIBK44tS75QC5N+VbWSE4DjCV/pJ+UzCW/F+vVnl7TkOPcuwQureKNtSSwjBTaMg==",
|
||||
"version": "12.12.31",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.31.tgz",
|
||||
"integrity": "sha512-T+wnJno8uh27G9c+1T+a1/WYCHzLeDqtsGJkoEdSp2X8RTh3oOCZQcUnjAx90CS8cmmADX51O0FI/tu9s0yssg==",
|
||||
"dev": true
|
||||
},
|
||||
"@types/parse-json": {
|
||||
@@ -1133,9 +1133,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"lint-staged": {
|
||||
"version": "10.0.8",
|
||||
"resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-10.0.8.tgz",
|
||||
"integrity": "sha512-Oa9eS4DJqvQMVdywXfEor6F4vP+21fPHF8LUXgBbVWUSWBddjqsvO6Bv1LwMChmgQZZqwUvgJSHlu8HFHAPZmA==",
|
||||
"version": "10.0.9",
|
||||
"resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-10.0.9.tgz",
|
||||
"integrity": "sha512-NKJHYgRa8oI9c4Ic42ZtF2XA6Ps7lFbXwg3q0ZEP0r55Tw3YWykCW1RzW6vu+QIGqbsy7DxndvKu93Wtr5vPQw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"chalk": "^3.0.0",
|
||||
@@ -1881,9 +1881,9 @@
|
||||
}
|
||||
},
|
||||
"prettier": {
|
||||
"version": "1.19.1",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-1.19.1.tgz",
|
||||
"integrity": "sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==",
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.0.2.tgz",
|
||||
"integrity": "sha512-5xJQIPT8BraI7ZnaDwSbu5zLrB6vvi8hVV58yHQ+QK64qrY40dULy0HSRlQ2/2IdzeBpjhDkqdcFBnFeDEMVdg==",
|
||||
"dev": true
|
||||
},
|
||||
"process": {
|
||||
@@ -1978,6 +1978,15 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"rimraf": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
|
||||
"integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"glob": "^7.1.3"
|
||||
}
|
||||
},
|
||||
"rxjs": {
|
||||
"version": "6.5.4",
|
||||
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.4.tgz",
|
||||
@@ -2222,9 +2231,9 @@
|
||||
}
|
||||
},
|
||||
"ts-node": {
|
||||
"version": "8.7.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-8.7.0.tgz",
|
||||
"integrity": "sha512-s659CsHrsxaRVDEleuOkGvbsA0rWHtszUNEt1r0CgAFN5ZZTQtDzpsluS7W5pOGJIa1xZE8R/zK4dEs+ldFezg==",
|
||||
"version": "8.8.1",
|
||||
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-8.8.1.tgz",
|
||||
"integrity": "sha512-10DE9ONho06QORKAaCBpPiFCdW+tZJuY/84tyypGtl6r+/C7Asq0dhqbRZURuUlLQtZxxDvT8eoj8cGW0ha6Bg==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"arg": "^4.1.0",
|
||||
|
15
package.json
15
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@biesbjerg/ngx-translate-extract",
|
||||
"version": "5.0.0",
|
||||
"version": "6.0.1",
|
||||
"description": "Extract strings from projects using ngx-translate",
|
||||
"main": "dist/index.js",
|
||||
"typings": "dist/index.d.ts",
|
||||
@@ -14,7 +14,7 @@
|
||||
"scripts": {
|
||||
"build": "npm run clean && tsc",
|
||||
"watch": "npm run clean && tsc --watch",
|
||||
"clean": "rm -rf ./dist",
|
||||
"clean": "rimraf ./dist",
|
||||
"lint": "tslint --force './src/**/*.ts'",
|
||||
"test": "mocha -r ts-node/register tests/**/*.spec.ts"
|
||||
},
|
||||
@@ -57,7 +57,7 @@
|
||||
},
|
||||
"homepage": "https://github.com/biesbjerg/ngx-translate-extract",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
"node": ">=11.15.0"
|
||||
},
|
||||
"config": {},
|
||||
"devDependencies": {
|
||||
@@ -67,15 +67,16 @@
|
||||
"@types/glob": "^7.1.1",
|
||||
"@types/mkdirp": "^1.0.0",
|
||||
"@types/mocha": "^7.0.2",
|
||||
"@types/node": "^12.12.30",
|
||||
"@types/node": "^12.12.31",
|
||||
"@types/yargs": "^15.0.4",
|
||||
"braces": "^3.0.2",
|
||||
"chai": "^4.2.0",
|
||||
"husky": "^4.2.3",
|
||||
"lint-staged": "^10.0.8",
|
||||
"lint-staged": "^10.0.9",
|
||||
"mocha": "^7.1.1",
|
||||
"prettier": "^1.19.1",
|
||||
"ts-node": "^8.7.0",
|
||||
"prettier": "^2.0.2",
|
||||
"rimraf": "^3.0.2",
|
||||
"ts-node": "^8.8.1",
|
||||
"tslint": "^6.1.0",
|
||||
"tslint-config-prettier": "^1.18.0",
|
||||
"tslint-eslint-rules": "^5.4.0",
|
||||
|
@@ -18,14 +18,13 @@ import { normalizePaths } from '../utils/fs-helpers';
|
||||
import { donateMessage } from '../utils/donate';
|
||||
|
||||
// First parsing pass to be able to access pattern argument for use input/output arguments
|
||||
const y = yargs
|
||||
.option('patterns', {
|
||||
alias: 'p',
|
||||
describe: 'Default patterns',
|
||||
type: 'array',
|
||||
default: ['/**/*.html', '/**/*.ts'],
|
||||
hidden: true
|
||||
});
|
||||
const y = yargs.option('patterns', {
|
||||
alias: 'p',
|
||||
describe: 'Default patterns',
|
||||
type: 'array',
|
||||
default: ['/**/*.html', '/**/*.ts'],
|
||||
hidden: true
|
||||
});
|
||||
|
||||
const parsed = y.parse();
|
||||
|
||||
|
@@ -24,8 +24,8 @@ export class ExtractTask implements TaskInterface {
|
||||
protected compiler: CompilerInterface;
|
||||
|
||||
public constructor(protected inputs: string[], protected outputs: string[], options?: ExtractTaskOptionsInterface) {
|
||||
this.inputs = inputs.map(input => path.resolve(input));
|
||||
this.outputs = outputs.map(output => path.resolve(output));
|
||||
this.inputs = inputs.map((input) => path.resolve(input));
|
||||
this.outputs = outputs.map((output) => path.resolve(output));
|
||||
this.options = { ...this.options, ...options };
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ export class ExtractTask implements TaskInterface {
|
||||
|
||||
this.out(bold('Saving:'));
|
||||
|
||||
this.outputs.forEach(output => {
|
||||
this.outputs.forEach((output) => {
|
||||
let dir: string = output;
|
||||
let filename: string = `strings.${this.compiler.extension}`;
|
||||
if (!fs.existsSync(output) || !fs.statSync(output).isDirectory()) {
|
||||
@@ -98,11 +98,11 @@ export class ExtractTask implements TaskInterface {
|
||||
*/
|
||||
protected extract(): TranslationCollection {
|
||||
let collection: TranslationCollection = new TranslationCollection();
|
||||
this.inputs.forEach(pattern => {
|
||||
this.getFiles(pattern).forEach(filePath => {
|
||||
this.inputs.forEach((pattern) => {
|
||||
this.getFiles(pattern).forEach((filePath) => {
|
||||
this.out(dim('- %s'), filePath);
|
||||
const contents: string = fs.readFileSync(filePath, 'utf-8');
|
||||
this.parsers.forEach(parser => {
|
||||
this.parsers.forEach((parser) => {
|
||||
const extracted = parser.extract(contents, filePath);
|
||||
if (extracted instanceof TranslationCollection) {
|
||||
collection = collection.union(extracted);
|
||||
@@ -117,7 +117,7 @@ export class ExtractTask implements TaskInterface {
|
||||
* Run strings through configured post processors
|
||||
*/
|
||||
protected process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection {
|
||||
this.postProcessors.forEach(postProcessor => {
|
||||
this.postProcessors.forEach((postProcessor) => {
|
||||
draft = postProcessor.process(draft, extracted, existing);
|
||||
});
|
||||
return draft;
|
||||
@@ -139,9 +139,7 @@ export class ExtractTask implements TaskInterface {
|
||||
* Get all files matching pattern
|
||||
*/
|
||||
protected getFiles(pattern: string): string[] {
|
||||
return glob
|
||||
.sync(pattern)
|
||||
.filter(filePath => fs.statSync(filePath).isFile());
|
||||
return glob.sync(pattern).filter((filePath) => fs.statSync(filePath).isFile());
|
||||
}
|
||||
|
||||
protected out(...args: any[]): void {
|
||||
@@ -151,7 +149,7 @@ export class ExtractTask implements TaskInterface {
|
||||
protected printEnabledParsers(): void {
|
||||
this.out(cyan('Enabled parsers:'));
|
||||
if (this.parsers.length) {
|
||||
this.out(cyan(dim(this.parsers.map(parser => `- ${parser.constructor.name}`).join('\n'))));
|
||||
this.out(cyan(dim(this.parsers.map((parser) => `- ${parser.constructor.name}`).join('\n'))));
|
||||
} else {
|
||||
this.out(cyan(dim('(none)')));
|
||||
}
|
||||
@@ -161,7 +159,7 @@ export class ExtractTask implements TaskInterface {
|
||||
protected printEnabledPostProcessors(): void {
|
||||
this.out(cyan('Enabled post processors:'));
|
||||
if (this.postProcessors.length) {
|
||||
this.out(cyan(dim(this.postProcessors.map(postProcessor => `- ${postProcessor.constructor.name}`).join('\n'))));
|
||||
this.out(cyan(dim(this.postProcessors.map((postProcessor) => `- ${postProcessor.constructor.name}`).join('\n'))));
|
||||
} else {
|
||||
this.out(cyan(dim('(none)')));
|
||||
}
|
||||
|
@@ -28,6 +28,6 @@ export class JsonCompiler implements CompilerInterface {
|
||||
}
|
||||
|
||||
protected isNamespacedJsonFormat(values: any): boolean {
|
||||
return Object.keys(values).some(key => typeof values[key] === 'object');
|
||||
return Object.keys(values).some((key) => typeof values[key] === 'object');
|
||||
}
|
||||
}
|
||||
|
@@ -22,18 +22,15 @@ export class PoCompiler implements CompilerInterface {
|
||||
'content-transfer-encoding': '8bit'
|
||||
},
|
||||
translations: {
|
||||
[this.domain]: Object.keys(collection.values).reduce(
|
||||
(translations, key) => {
|
||||
return {
|
||||
...translations,
|
||||
[key]: {
|
||||
msgid: key,
|
||||
msgstr: collection.get(key)
|
||||
}
|
||||
};
|
||||
},
|
||||
{} as any
|
||||
)
|
||||
[this.domain]: Object.keys(collection.values).reduce((translations, key) => {
|
||||
return {
|
||||
...translations,
|
||||
[key]: {
|
||||
msgid: key,
|
||||
msgstr: collection.get(key)
|
||||
}
|
||||
};
|
||||
}, {} as any)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -49,16 +46,13 @@ export class PoCompiler implements CompilerInterface {
|
||||
}
|
||||
|
||||
const values = Object.keys(po.translations[this.domain])
|
||||
.filter(key => key.length > 0)
|
||||
.reduce(
|
||||
(result, key) => {
|
||||
return {
|
||||
...result,
|
||||
[key]: po.translations[this.domain][key].msgstr.pop()
|
||||
};
|
||||
},
|
||||
{} as TranslationType
|
||||
);
|
||||
.filter((key) => key.length > 0)
|
||||
.reduce((result, key) => {
|
||||
return {
|
||||
...result,
|
||||
[key]: po.translations[this.domain][key].msgstr.pop()
|
||||
};
|
||||
}, {} as TranslationType);
|
||||
|
||||
return new TranslationCollection(values);
|
||||
}
|
||||
|
@@ -13,8 +13,8 @@ export class DirectiveParser implements ParserInterface {
|
||||
let collection: TranslationCollection = new TranslationCollection();
|
||||
|
||||
const nodes: TmplAstNode[] = this.parseTemplate(source, filePath);
|
||||
this.getTranslatableElements(nodes).forEach(element => {
|
||||
const key = this.getElementTranslateAttrValue(element) || this.getElementContents(element);
|
||||
this.getTranslatableElements(nodes).forEach((element) => {
|
||||
const key = this.getElementTranslateAttrValue(element) || this.getElementContent(element);
|
||||
collection = collection.add(key);
|
||||
});
|
||||
|
||||
@@ -23,11 +23,11 @@ export class DirectiveParser implements ParserInterface {
|
||||
|
||||
protected getTranslatableElements(nodes: TmplAstNode[]): TmplAstElement[] {
|
||||
return nodes
|
||||
.filter(element => this.isElement(element))
|
||||
.filter((element) => this.isElement(element))
|
||||
.reduce((result: TmplAstElement[], element: TmplAstElement) => {
|
||||
return result.concat(this.findChildrenElements(element));
|
||||
}, [])
|
||||
.filter(element => this.isTranslatable(element));
|
||||
.filter((element) => this.isTranslatable(element));
|
||||
}
|
||||
|
||||
protected findChildrenElements(node: TmplAstNode): TmplAstElement[] {
|
||||
@@ -35,7 +35,7 @@ export class DirectiveParser implements ParserInterface {
|
||||
return [];
|
||||
}
|
||||
|
||||
// If element has translate attribute all its contents is translatable
|
||||
// If element has translate attribute all its content is translatable
|
||||
// so we don't need to traverse any deeper
|
||||
if (this.isTranslatable(node)) {
|
||||
return [node];
|
||||
@@ -62,21 +62,26 @@ export class DirectiveParser implements ParserInterface {
|
||||
}
|
||||
|
||||
protected isTranslatable(node: TmplAstNode): boolean {
|
||||
if (this.isElement(node) && node.attributes.some(attribute => attribute.name === 'translate')) {
|
||||
if (this.isElement(node) && node.attributes.some((attribute) => attribute.name === 'translate')) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
protected getElementTranslateAttrValue(element: TmplAstElement): string {
|
||||
const attr: TmplAstTextAttribute = element.attributes.find(attribute => attribute.name === 'translate');
|
||||
const attr: TmplAstTextAttribute = element.attributes.find((attribute) => attribute.name === 'translate');
|
||||
return attr?.value ?? '';
|
||||
}
|
||||
|
||||
protected getElementContents(element: TmplAstElement): string {
|
||||
const contents = element.sourceSpan.start.file.content;
|
||||
protected getElementContent(element: TmplAstElement): string {
|
||||
const content = element.sourceSpan.start.file.content;
|
||||
const start = element.startSourceSpan.end.offset;
|
||||
const end = element.endSourceSpan.start.offset;
|
||||
return contents.substring(start, end).trim();
|
||||
const val = content.substring(start, end);
|
||||
return this.cleanKey(val);
|
||||
}
|
||||
|
||||
protected cleanKey(val: string): string {
|
||||
return val.replace(/\r?\n|\r|\t/g, '');
|
||||
}
|
||||
}
|
||||
|
@@ -19,7 +19,7 @@ export class MarkerParser implements ParserInterface {
|
||||
let collection: TranslationCollection = new TranslationCollection();
|
||||
|
||||
const callExpressions = findFunctionCallExpressions(sourceFile, markerImportName);
|
||||
callExpressions.forEach(callExpression => {
|
||||
callExpressions.forEach((callExpression) => {
|
||||
const [firstArg] = callExpression.arguments;
|
||||
if (!firstArg) {
|
||||
return;
|
||||
|
@@ -14,8 +14,8 @@ export class PipeParser implements ParserInterface {
|
||||
|
||||
let collection: TranslationCollection = new TranslationCollection();
|
||||
const nodes: TmplAstNode[] = this.parseTemplate(source, filePath);
|
||||
const pipes: BindingPipe[] = nodes.map(node => this.findPipesInNode(node)).flat();
|
||||
pipes.forEach(pipe => {
|
||||
const pipes: BindingPipe[] = nodes.map((node) => this.findPipesInNode(node)).flat();
|
||||
pipes.forEach((pipe) => {
|
||||
this.parseTranslationKeysFromPipe(pipe).forEach((key: string) => {
|
||||
collection = collection.add(key);
|
||||
});
|
||||
|
@@ -1,8 +1,17 @@
|
||||
import { ClassDeclaration, CallExpression } from 'typescript';
|
||||
import { tsquery } from '@phenomnomnominal/tsquery';
|
||||
|
||||
import { ParserInterface } from './parser.interface';
|
||||
import { TranslationCollection } from '../utils/translation.collection';
|
||||
import { findClassDeclarations, findClassPropertyByType, findMethodCallExpressions, getStringsFromExpression } from '../utils/ast-helpers';
|
||||
import {
|
||||
findClassDeclarations,
|
||||
findClassPropertyByType,
|
||||
findPropertyCallExpressions,
|
||||
findMethodCallExpressions,
|
||||
getStringsFromExpression,
|
||||
findMethodParameterByType,
|
||||
findConstructorDeclaration
|
||||
} from '../utils/ast-helpers';
|
||||
|
||||
const TRANSLATE_SERVICE_TYPE_REFERENCE = 'TranslateService';
|
||||
const TRANSLATE_SERVICE_METHOD_NAMES = ['get', 'instant', 'stream'];
|
||||
@@ -18,14 +27,13 @@ export class ServiceParser implements ParserInterface {
|
||||
|
||||
let collection: TranslationCollection = new TranslationCollection();
|
||||
|
||||
classDeclarations.forEach(classDeclaration => {
|
||||
const propName: string = findClassPropertyByType(classDeclaration, TRANSLATE_SERVICE_TYPE_REFERENCE);
|
||||
if (!propName) {
|
||||
return;
|
||||
}
|
||||
classDeclarations.forEach((classDeclaration) => {
|
||||
const callExpressions = [
|
||||
...this.findConstructorParamCallExpressions(classDeclaration),
|
||||
...this.findPropertyCallExpressions(classDeclaration)
|
||||
];
|
||||
|
||||
const callExpressions = findMethodCallExpressions(classDeclaration, propName, TRANSLATE_SERVICE_METHOD_NAMES);
|
||||
callExpressions.forEach(callExpression => {
|
||||
callExpressions.forEach((callExpression) => {
|
||||
const [firstArg] = callExpression.arguments;
|
||||
if (!firstArg) {
|
||||
return;
|
||||
@@ -36,4 +44,21 @@ export class ServiceParser implements ParserInterface {
|
||||
});
|
||||
return collection;
|
||||
}
|
||||
|
||||
protected findConstructorParamCallExpressions(classDeclaration: ClassDeclaration): CallExpression[] {
|
||||
const constructorDeclaration = findConstructorDeclaration(classDeclaration);
|
||||
if (!constructorDeclaration) {
|
||||
return [];
|
||||
}
|
||||
const paramName = findMethodParameterByType(constructorDeclaration, TRANSLATE_SERVICE_TYPE_REFERENCE);
|
||||
return findMethodCallExpressions(constructorDeclaration, paramName, TRANSLATE_SERVICE_METHOD_NAMES);
|
||||
}
|
||||
|
||||
protected findPropertyCallExpressions(classDeclaration: ClassDeclaration): CallExpression[] {
|
||||
const propName: string = findClassPropertyByType(classDeclaration, TRANSLATE_SERVICE_TYPE_REFERENCE);
|
||||
if (!propName) {
|
||||
return [];
|
||||
}
|
||||
return findPropertyCallExpressions(classDeclaration, propName, TRANSLATE_SERVICE_METHOD_NAMES);
|
||||
}
|
||||
}
|
||||
|
@@ -1,15 +1,16 @@
|
||||
import { tsquery } from '@phenomnomnominal/tsquery';
|
||||
import {
|
||||
SyntaxKind,
|
||||
Node,
|
||||
NamedImports,
|
||||
Identifier,
|
||||
ClassDeclaration,
|
||||
CallExpression,
|
||||
ConstructorDeclaration,
|
||||
isStringLiteralLike,
|
||||
isArrayLiteralExpression,
|
||||
CallExpression,
|
||||
Expression,
|
||||
isBinaryExpression,
|
||||
SyntaxKind,
|
||||
isConditionalExpression,
|
||||
PropertyAccessExpression
|
||||
} from 'typescript';
|
||||
@@ -45,6 +46,30 @@ export function findClassPropertyByType(node: ClassDeclaration, type: string): s
|
||||
return findClassPropertyConstructorParameterByType(node, type) || findClassPropertyDeclarationByType(node, type);
|
||||
}
|
||||
|
||||
export function findConstructorDeclaration(node: ClassDeclaration): ConstructorDeclaration {
|
||||
const query = `Constructor`;
|
||||
const [result] = tsquery<ConstructorDeclaration>(node, query);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function findMethodParameterByType(node: Node, type: string): string | null {
|
||||
const query = `Parameter:has(TypeReference > Identifier[name="${type}"]) > Identifier`;
|
||||
const [result] = tsquery<Identifier>(node, query);
|
||||
if (result) {
|
||||
return result.text;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function findMethodCallExpressions(node: Node, propName: string, fnName: string | string[]): CallExpression[] {
|
||||
if (Array.isArray(fnName)) {
|
||||
fnName = fnName.join('|');
|
||||
}
|
||||
const query = `CallExpression > PropertyAccessExpression:has(Identifier[name=/^(${fnName})$/]):has(PropertyAccessExpression:has(Identifier[name="${propName}"]):not(:has(ThisKeyword)))`;
|
||||
const nodes = tsquery<PropertyAccessExpression>(node, query).map((n) => n.parent as CallExpression);
|
||||
return nodes;
|
||||
}
|
||||
|
||||
export function findClassPropertyConstructorParameterByType(node: ClassDeclaration, type: string): string | null {
|
||||
const query = `Constructor Parameter:has(TypeReference > Identifier[name="${type}"]):has(PublicKeyword,ProtectedKeyword,PrivateKeyword) > Identifier`;
|
||||
const [result] = tsquery<Identifier>(node, query);
|
||||
@@ -72,12 +97,12 @@ export function findFunctionCallExpressions(node: Node, fnName: string | string[
|
||||
return nodes;
|
||||
}
|
||||
|
||||
export function findMethodCallExpressions(node: Node, prop: string, fnName: string | string[]): CallExpression[] {
|
||||
export function findPropertyCallExpressions(node: Node, prop: string, fnName: string | string[]): CallExpression[] {
|
||||
if (Array.isArray(fnName)) {
|
||||
fnName = fnName.join('|');
|
||||
}
|
||||
const query = `CallExpression > PropertyAccessExpression:has(Identifier[name=/^(${fnName})$/]):has(PropertyAccessExpression:has(Identifier[name="${prop}"]):has(ThisKeyword))`;
|
||||
const nodes = tsquery<PropertyAccessExpression>(node, query).map(n => n.parent as CallExpression);
|
||||
const nodes = tsquery<PropertyAccessExpression>(node, query).map((n) => n.parent as CallExpression);
|
||||
return nodes;
|
||||
}
|
||||
|
||||
|
@@ -2,6 +2,12 @@ import * as os from 'os';
|
||||
import * as fs from 'fs';
|
||||
import * as braces from 'braces';
|
||||
|
||||
declare module 'braces' {
|
||||
interface Options {
|
||||
keepEscaping?: boolean; // Workaround for option not present in @types/braces 3.0.0
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeHomeDir(path: string): string {
|
||||
if (path.substring(0, 1) === '~') {
|
||||
return `${os.homedir()}/${path.substring(1)}`;
|
||||
@@ -10,17 +16,21 @@ export function normalizeHomeDir(path: string): string {
|
||||
}
|
||||
|
||||
export function expandPattern(pattern: string): string[] {
|
||||
return braces(pattern, { expand: true });
|
||||
return braces(pattern, { expand: true, keepEscaping: true });
|
||||
}
|
||||
|
||||
export function normalizePaths(patterns: string[], defaultPatterns: string[] = []): string[] {
|
||||
return patterns.map(pattern =>
|
||||
expandPattern(pattern).map(path => {
|
||||
path = normalizeHomeDir(path);
|
||||
if (fs.existsSync(path) && fs.statSync(path).isDirectory()) {
|
||||
return defaultPatterns.map(defaultPattern => path + defaultPattern);
|
||||
}
|
||||
return path;
|
||||
}).flat()
|
||||
).flat();
|
||||
return patterns
|
||||
.map((pattern) =>
|
||||
expandPattern(pattern)
|
||||
.map((path) => {
|
||||
path = normalizeHomeDir(path);
|
||||
if (fs.existsSync(path) && fs.statSync(path).isDirectory()) {
|
||||
return defaultPatterns.map((defaultPattern) => path + defaultPattern);
|
||||
}
|
||||
return path;
|
||||
})
|
||||
.flat()
|
||||
)
|
||||
.flat();
|
||||
}
|
||||
|
@@ -14,21 +14,18 @@ export class TranslationCollection {
|
||||
}
|
||||
|
||||
public addKeys(keys: string[]): TranslationCollection {
|
||||
const values = keys.reduce(
|
||||
(results, key) => {
|
||||
return { ...results, [key]: '' };
|
||||
},
|
||||
{} as TranslationType
|
||||
);
|
||||
const values = keys.reduce((results, key) => {
|
||||
return { ...results, [key]: '' };
|
||||
}, {} as TranslationType);
|
||||
return new TranslationCollection({ ...this.values, ...values });
|
||||
}
|
||||
|
||||
public remove(key: string): TranslationCollection {
|
||||
return this.filter(k => key !== k);
|
||||
return this.filter((k) => key !== k);
|
||||
}
|
||||
|
||||
public forEach(callback: (key?: string, val?: string) => void): TranslationCollection {
|
||||
Object.keys(this.values).forEach(key => callback.call(this, key, this.values[key]));
|
||||
Object.keys(this.values).forEach((key) => callback.call(this, key, this.values[key]));
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -56,7 +53,7 @@ export class TranslationCollection {
|
||||
|
||||
public intersect(collection: TranslationCollection): TranslationCollection {
|
||||
const values: TranslationType = {};
|
||||
this.filter(key => collection.has(key)).forEach((key, val) => {
|
||||
this.filter((key) => collection.has(key)).forEach((key, val) => {
|
||||
values[key] = val;
|
||||
});
|
||||
|
||||
@@ -87,7 +84,7 @@ export class TranslationCollection {
|
||||
const values: TranslationType = {};
|
||||
this.keys()
|
||||
.sort(compareFn)
|
||||
.forEach(key => {
|
||||
.forEach((key) => {
|
||||
values[key] = this.get(key);
|
||||
});
|
||||
|
||||
|
@@ -85,4 +85,36 @@ describe('DirectiveParser', () => {
|
||||
const keys = parser.extract(contents, componentFilename).keys();
|
||||
expect(keys).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it('should extract contents without line breaks', () => {
|
||||
const contents = `
|
||||
<p translate>
|
||||
Please leave a message for your client letting them know why you
|
||||
rejected the field and what they need to do to fix it.
|
||||
</p>
|
||||
`;
|
||||
const keys = parser.extract(contents, templateFilename).keys();
|
||||
expect(keys).to.deep.equal([
|
||||
'Please leave a message for your client letting them know why you rejected the field and what they need to do to fix it.'
|
||||
]);
|
||||
});
|
||||
|
||||
it('should extract contents without indent spaces', () => {
|
||||
const contents = `
|
||||
<div *ngIf="!isLoading && studentsToGrid && studentsToGrid.length == 0" class="no-students" mt-rtl translate>There
|
||||
are currently no students in this class. The good news is, adding students is really easy! Just use the options
|
||||
at the top.
|
||||
</div>
|
||||
`;
|
||||
const keys = parser.extract(contents, templateFilename).keys();
|
||||
expect(keys).to.deep.equal([
|
||||
'There are currently no students in this class. The good news is, adding students is really easy! Just use the options at the top.'
|
||||
]);
|
||||
});
|
||||
|
||||
it('should extract contents without indent spaces', () => {
|
||||
const contents = `<button mat-button (click)="search()" translate>client.search.searchBtn</button>`;
|
||||
const keys = parser.extract(contents, templateFilename).keys();
|
||||
expect(keys).to.deep.equal(['client.search.searchBtn']);
|
||||
});
|
||||
});
|
||||
|
@@ -35,4 +35,19 @@ describe('MarkerParser', () => {
|
||||
const keys = parser.extract(contents, componentFilename).keys();
|
||||
expect(keys).to.deep.equal(['Hello world', 'This is a very very very very long line.', 'Mix of different types']);
|
||||
});
|
||||
|
||||
it('should extract the strings', () => {
|
||||
const contents = `
|
||||
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
|
||||
|
||||
export class AppModule {
|
||||
constructor() {
|
||||
marker('DYNAMIC_TRAD.val1');
|
||||
marker('DYNAMIC_TRAD.val2');
|
||||
}
|
||||
}
|
||||
`;
|
||||
const keys = parser.extract(contents, componentFilename).keys();
|
||||
expect(keys).to.deep.equal(['DYNAMIC_TRAD.val1', 'DYNAMIC_TRAD.val2']);
|
||||
});
|
||||
});
|
||||
|
@@ -147,4 +147,16 @@ describe('PipeParser', () => {
|
||||
const keys = parser.extract(contents, templateFilename).keys();
|
||||
expect(keys).to.deep.equal(['message']);
|
||||
});
|
||||
|
||||
it('should ignore calculated values', () => {
|
||||
const contents = `{{ 'SOURCES.' + source.name + '.NAME_PLURAL' | translate }}`;
|
||||
const keys = parser.extract(contents, templateFilename).keys();
|
||||
expect(keys).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it('should not extract pipe argument', () => {
|
||||
const contents = `{{ value | valueToTranslationKey: 'argument' | translate }}`;
|
||||
const keys = parser.extract(contents, templateFilename).keys();
|
||||
expect(keys).to.deep.equal([]);
|
||||
});
|
||||
});
|
||||
|
@@ -11,6 +11,18 @@ describe('ServiceParser', () => {
|
||||
parser = new ServiceParser();
|
||||
});
|
||||
|
||||
it('should extract strings when TranslateService is accessed directly via constructor parameter', () => {
|
||||
const contents = `
|
||||
@Component({ })
|
||||
export class MyComponent {
|
||||
public constructor(protected translateService: TranslateService) {
|
||||
translateService.get('It works!');
|
||||
}
|
||||
`;
|
||||
const keys = parser.extract(contents, componentFilename).keys();
|
||||
expect(keys).to.deep.equal(['It works!']);
|
||||
});
|
||||
|
||||
it('should support extracting binary expressions', () => {
|
||||
const contents = `
|
||||
@Component({ })
|
||||
|
@@ -8,10 +8,9 @@
|
||||
"noImplicitUseStrict": true,
|
||||
"removeComments": true,
|
||||
"declaration": true,
|
||||
"target": "es2015",
|
||||
"target": "es2019",
|
||||
"lib": [
|
||||
"dom",
|
||||
"esnext.array"
|
||||
"es2019"
|
||||
],
|
||||
"module": "commonjs",
|
||||
"outDir": "dist",
|
||||
|
Reference in New Issue
Block a user