Run prettier on code

This commit is contained in:
Kim Biesbjerg 2020-03-25 11:47:44 +01:00
parent ce399ee717
commit ecf629118a
14 changed files with 81 additions and 79 deletions

View File

@ -18,14 +18,13 @@ import { normalizePaths } from '../utils/fs-helpers';
import { donateMessage } from '../utils/donate'; import { donateMessage } from '../utils/donate';
// First parsing pass to be able to access pattern argument for use input/output arguments // First parsing pass to be able to access pattern argument for use input/output arguments
const y = yargs const y = yargs.option('patterns', {
.option('patterns', { alias: 'p',
alias: 'p', describe: 'Default patterns',
describe: 'Default patterns', type: 'array',
type: 'array', default: ['/**/*.html', '/**/*.ts'],
default: ['/**/*.html', '/**/*.ts'], hidden: true
hidden: true });
});
const parsed = y.parse(); const parsed = y.parse();

View File

@ -24,8 +24,8 @@ export class ExtractTask implements TaskInterface {
protected compiler: CompilerInterface; protected compiler: CompilerInterface;
public constructor(protected inputs: string[], protected outputs: string[], options?: ExtractTaskOptionsInterface) { public constructor(protected inputs: string[], protected outputs: string[], options?: ExtractTaskOptionsInterface) {
this.inputs = inputs.map(input => path.resolve(input)); this.inputs = inputs.map((input) => path.resolve(input));
this.outputs = outputs.map(output => path.resolve(output)); this.outputs = outputs.map((output) => path.resolve(output));
this.options = { ...this.options, ...options }; this.options = { ...this.options, ...options };
} }
@ -44,7 +44,7 @@ export class ExtractTask implements TaskInterface {
this.out(bold('Saving:')); this.out(bold('Saving:'));
this.outputs.forEach(output => { this.outputs.forEach((output) => {
let dir: string = output; let dir: string = output;
let filename: string = `strings.${this.compiler.extension}`; let filename: string = `strings.${this.compiler.extension}`;
if (!fs.existsSync(output) || !fs.statSync(output).isDirectory()) { if (!fs.existsSync(output) || !fs.statSync(output).isDirectory()) {
@ -98,11 +98,11 @@ export class ExtractTask implements TaskInterface {
*/ */
protected extract(): TranslationCollection { protected extract(): TranslationCollection {
let collection: TranslationCollection = new TranslationCollection(); let collection: TranslationCollection = new TranslationCollection();
this.inputs.forEach(pattern => { this.inputs.forEach((pattern) => {
this.getFiles(pattern).forEach(filePath => { this.getFiles(pattern).forEach((filePath) => {
this.out(dim('- %s'), filePath); this.out(dim('- %s'), filePath);
const contents: string = fs.readFileSync(filePath, 'utf-8'); const contents: string = fs.readFileSync(filePath, 'utf-8');
this.parsers.forEach(parser => { this.parsers.forEach((parser) => {
const extracted = parser.extract(contents, filePath); const extracted = parser.extract(contents, filePath);
if (extracted instanceof TranslationCollection) { if (extracted instanceof TranslationCollection) {
collection = collection.union(extracted); collection = collection.union(extracted);
@ -117,7 +117,7 @@ export class ExtractTask implements TaskInterface {
* Run strings through configured post processors * Run strings through configured post processors
*/ */
protected process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection { protected process(draft: TranslationCollection, extracted: TranslationCollection, existing: TranslationCollection): TranslationCollection {
this.postProcessors.forEach(postProcessor => { this.postProcessors.forEach((postProcessor) => {
draft = postProcessor.process(draft, extracted, existing); draft = postProcessor.process(draft, extracted, existing);
}); });
return draft; return draft;
@ -139,9 +139,7 @@ export class ExtractTask implements TaskInterface {
* Get all files matching pattern * Get all files matching pattern
*/ */
protected getFiles(pattern: string): string[] { protected getFiles(pattern: string): string[] {
return glob return glob.sync(pattern).filter((filePath) => fs.statSync(filePath).isFile());
.sync(pattern)
.filter(filePath => fs.statSync(filePath).isFile());
} }
protected out(...args: any[]): void { protected out(...args: any[]): void {
@ -151,7 +149,7 @@ export class ExtractTask implements TaskInterface {
protected printEnabledParsers(): void { protected printEnabledParsers(): void {
this.out(cyan('Enabled parsers:')); this.out(cyan('Enabled parsers:'));
if (this.parsers.length) { 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 { } else {
this.out(cyan(dim('(none)'))); this.out(cyan(dim('(none)')));
} }
@ -161,7 +159,7 @@ export class ExtractTask implements TaskInterface {
protected printEnabledPostProcessors(): void { protected printEnabledPostProcessors(): void {
this.out(cyan('Enabled post processors:')); this.out(cyan('Enabled post processors:'));
if (this.postProcessors.length) { 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 { } else {
this.out(cyan(dim('(none)'))); this.out(cyan(dim('(none)')));
} }

View File

@ -28,6 +28,6 @@ export class JsonCompiler implements CompilerInterface {
} }
protected isNamespacedJsonFormat(values: any): boolean { 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');
} }
} }

View File

@ -22,18 +22,15 @@ export class PoCompiler implements CompilerInterface {
'content-transfer-encoding': '8bit' 'content-transfer-encoding': '8bit'
}, },
translations: { translations: {
[this.domain]: Object.keys(collection.values).reduce( [this.domain]: Object.keys(collection.values).reduce((translations, key) => {
(translations, key) => { return {
return { ...translations,
...translations, [key]: {
[key]: { msgid: key,
msgid: key, msgstr: collection.get(key)
msgstr: collection.get(key) }
} };
}; }, {} as any)
},
{} as any
)
} }
}; };
@ -49,16 +46,13 @@ export class PoCompiler implements CompilerInterface {
} }
const values = Object.keys(po.translations[this.domain]) const values = Object.keys(po.translations[this.domain])
.filter(key => key.length > 0) .filter((key) => key.length > 0)
.reduce( .reduce((result, key) => {
(result, key) => { return {
return { ...result,
...result, [key]: po.translations[this.domain][key].msgstr.pop()
[key]: po.translations[this.domain][key].msgstr.pop() };
}; }, {} as TranslationType);
},
{} as TranslationType
);
return new TranslationCollection(values); return new TranslationCollection(values);
} }

View File

@ -13,7 +13,7 @@ export class DirectiveParser implements ParserInterface {
let collection: TranslationCollection = new TranslationCollection(); let collection: TranslationCollection = new TranslationCollection();
const nodes: TmplAstNode[] = this.parseTemplate(source, filePath); const nodes: TmplAstNode[] = this.parseTemplate(source, filePath);
this.getTranslatableElements(nodes).forEach(element => { this.getTranslatableElements(nodes).forEach((element) => {
const key = this.getElementTranslateAttrValue(element) || this.getElementContent(element); const key = this.getElementTranslateAttrValue(element) || this.getElementContent(element);
collection = collection.add(key); collection = collection.add(key);
}); });
@ -23,11 +23,11 @@ export class DirectiveParser implements ParserInterface {
protected getTranslatableElements(nodes: TmplAstNode[]): TmplAstElement[] { protected getTranslatableElements(nodes: TmplAstNode[]): TmplAstElement[] {
return nodes return nodes
.filter(element => this.isElement(element)) .filter((element) => this.isElement(element))
.reduce((result: TmplAstElement[], element: TmplAstElement) => { .reduce((result: TmplAstElement[], element: TmplAstElement) => {
return result.concat(this.findChildrenElements(element)); return result.concat(this.findChildrenElements(element));
}, []) }, [])
.filter(element => this.isTranslatable(element)); .filter((element) => this.isTranslatable(element));
} }
protected findChildrenElements(node: TmplAstNode): TmplAstElement[] { protected findChildrenElements(node: TmplAstNode): TmplAstElement[] {
@ -62,14 +62,14 @@ export class DirectiveParser implements ParserInterface {
} }
protected isTranslatable(node: TmplAstNode): boolean { 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 true;
} }
return false; return false;
} }
protected getElementTranslateAttrValue(element: TmplAstElement): string { 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 ?? ''; return attr?.value ?? '';
} }

View File

@ -19,7 +19,7 @@ export class MarkerParser implements ParserInterface {
let collection: TranslationCollection = new TranslationCollection(); let collection: TranslationCollection = new TranslationCollection();
const callExpressions = findFunctionCallExpressions(sourceFile, markerImportName); const callExpressions = findFunctionCallExpressions(sourceFile, markerImportName);
callExpressions.forEach(callExpression => { callExpressions.forEach((callExpression) => {
const [firstArg] = callExpression.arguments; const [firstArg] = callExpression.arguments;
if (!firstArg) { if (!firstArg) {
return; return;

View File

@ -14,8 +14,8 @@ export class PipeParser implements ParserInterface {
let collection: TranslationCollection = new TranslationCollection(); let collection: TranslationCollection = new TranslationCollection();
const nodes: TmplAstNode[] = this.parseTemplate(source, filePath); const nodes: TmplAstNode[] = this.parseTemplate(source, filePath);
const pipes: BindingPipe[] = nodes.map(node => this.findPipesInNode(node)).flat(); const pipes: BindingPipe[] = nodes.map((node) => this.findPipesInNode(node)).flat();
pipes.forEach(pipe => { pipes.forEach((pipe) => {
this.parseTranslationKeysFromPipe(pipe).forEach((key: string) => { this.parseTranslationKeysFromPipe(pipe).forEach((key: string) => {
collection = collection.add(key); collection = collection.add(key);
}); });

View File

@ -3,7 +3,15 @@ import { tsquery } from '@phenomnomnominal/tsquery';
import { ParserInterface } from './parser.interface'; import { ParserInterface } from './parser.interface';
import { TranslationCollection } from '../utils/translation.collection'; import { TranslationCollection } from '../utils/translation.collection';
import { findClassDeclarations, findClassPropertyByType, findPropertyCallExpressions, findMethodCallExpressions, getStringsFromExpression, findMethodParameterByType, findConstructorDeclaration } 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_TYPE_REFERENCE = 'TranslateService';
const TRANSLATE_SERVICE_METHOD_NAMES = ['get', 'instant', 'stream']; const TRANSLATE_SERVICE_METHOD_NAMES = ['get', 'instant', 'stream'];
@ -19,13 +27,13 @@ export class ServiceParser implements ParserInterface {
let collection: TranslationCollection = new TranslationCollection(); let collection: TranslationCollection = new TranslationCollection();
classDeclarations.forEach(classDeclaration => { classDeclarations.forEach((classDeclaration) => {
const callExpressions = [ const callExpressions = [
...this.findConstructorParamCallExpressions(classDeclaration), ...this.findConstructorParamCallExpressions(classDeclaration),
...this.findPropertyCallExpressions(classDeclaration) ...this.findPropertyCallExpressions(classDeclaration)
]; ];
callExpressions.forEach(callExpression => { callExpressions.forEach((callExpression) => {
const [firstArg] = callExpression.arguments; const [firstArg] = callExpression.arguments;
if (!firstArg) { if (!firstArg) {
return; return;

View File

@ -66,7 +66,7 @@ export function findMethodCallExpressions(node: Node, propName: string, fnName:
fnName = fnName.join('|'); fnName = fnName.join('|');
} }
const query = `CallExpression > PropertyAccessExpression:has(Identifier[name=/^(${fnName})$/]):has(PropertyAccessExpression:has(Identifier[name="${propName}"]):not(:has(ThisKeyword)))`; 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); const nodes = tsquery<PropertyAccessExpression>(node, query).map((n) => n.parent as CallExpression);
return nodes; return nodes;
} }
@ -102,7 +102,7 @@ export function findPropertyCallExpressions(node: Node, prop: string, fnName: st
fnName = fnName.join('|'); fnName = fnName.join('|');
} }
const query = `CallExpression > PropertyAccessExpression:has(Identifier[name=/^(${fnName})$/]):has(PropertyAccessExpression:has(Identifier[name="${prop}"]):has(ThisKeyword))`; 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; return nodes;
} }

View File

@ -20,13 +20,17 @@ export function expandPattern(pattern: string): string[] {
} }
export function normalizePaths(patterns: string[], defaultPatterns: string[] = []): string[] { export function normalizePaths(patterns: string[], defaultPatterns: string[] = []): string[] {
return patterns.map(pattern => return patterns
expandPattern(pattern).map(path => { .map((pattern) =>
path = normalizeHomeDir(path); expandPattern(pattern)
if (fs.existsSync(path) && fs.statSync(path).isDirectory()) { .map((path) => {
return defaultPatterns.map(defaultPattern => path + defaultPattern); path = normalizeHomeDir(path);
} if (fs.existsSync(path) && fs.statSync(path).isDirectory()) {
return path; return defaultPatterns.map((defaultPattern) => path + defaultPattern);
}).flat() }
).flat(); return path;
})
.flat()
)
.flat();
} }

View File

@ -14,21 +14,18 @@ export class TranslationCollection {
} }
public addKeys(keys: string[]): TranslationCollection { public addKeys(keys: string[]): TranslationCollection {
const values = keys.reduce( const values = keys.reduce((results, key) => {
(results, key) => { return { ...results, [key]: '' };
return { ...results, [key]: '' }; }, {} as TranslationType);
},
{} as TranslationType
);
return new TranslationCollection({ ...this.values, ...values }); return new TranslationCollection({ ...this.values, ...values });
} }
public remove(key: string): TranslationCollection { 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 { 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; return this;
} }
@ -56,7 +53,7 @@ export class TranslationCollection {
public intersect(collection: TranslationCollection): TranslationCollection { public intersect(collection: TranslationCollection): TranslationCollection {
const values: TranslationType = {}; const values: TranslationType = {};
this.filter(key => collection.has(key)).forEach((key, val) => { this.filter((key) => collection.has(key)).forEach((key, val) => {
values[key] = val; values[key] = val;
}); });
@ -87,7 +84,7 @@ export class TranslationCollection {
const values: TranslationType = {}; const values: TranslationType = {};
this.keys() this.keys()
.sort(compareFn) .sort(compareFn)
.forEach(key => { .forEach((key) => {
values[key] = this.get(key); values[key] = this.get(key);
}); });

View File

@ -1 +0,0 @@
{{ 'SOURCES.' + source.name + '.NAME_PLURAL' | translate }}

View File

@ -94,7 +94,9 @@ describe('DirectiveParser', () => {
</p> </p>
`; `;
const keys = parser.extract(contents, templateFilename).keys(); 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.']); 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', () => { it('should extract contents without indent spaces', () => {
@ -105,7 +107,9 @@ describe('DirectiveParser', () => {
</div> </div>
`; `;
const keys = parser.extract(contents, templateFilename).keys(); 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.']); 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', () => { it('should extract contents without indent spaces', () => {

View File

@ -50,5 +50,4 @@ describe('MarkerParser', () => {
const keys = parser.extract(contents, componentFilename).keys(); const keys = parser.extract(contents, componentFilename).keys();
expect(keys).to.deep.equal(['DYNAMIC_TRAD.val1', 'DYNAMIC_TRAD.val2']); expect(keys).to.deep.equal(['DYNAMIC_TRAD.val1', 'DYNAMIC_TRAD.val2']);
}); });
}); });