Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Parsers and Compilers configurable #136

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion bin/cli.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
#! /usr/bin/env node

require('../dist/cli/cli');
//need to be imported once per application: @see https://github.com/inversify/InversifyJS/issues/262#issuecomment-227593844
let reflectMetadata = require('reflect-metadata');

//IoC configuration: imported here to allow redefintion for usage as library
let inversifyConfig = require('../dist/ioc/inversify.config');


let cli = require('../dist/cli/cli');

cli.getExtractTask().execute();

21 changes: 20 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,10 @@
"flat": "git://github.com/lenchvolodymyr/flat.git#ffe77ef",
"gettext-parser": "^4.0.1",
"glob": "^7.1.4",
"inversify": "^5.0.1",
"mkdirp": "^0.5.1",
"path": "^0.12.7",
"reflect-metadata": "^0.1.13",
"terminal-link": "^1.3.0",
"typescript": "^3.5.3",
"yargs": "^13.3.0"
Expand Down
230 changes: 109 additions & 121 deletions src/cli/cli.ts
Original file line number Diff line number Diff line change
@@ -1,138 +1,126 @@
import * as fs from 'fs';
import * as yargs from 'yargs';

import { ExtractTask } from './tasks/extract.task';
import { ParserInterface } from '../parsers/parser.interface';
import { PipeParser } from '../parsers/pipe.parser';
import { DirectiveParser } from '../parsers/directive.parser';
import { ServiceParser } from '../parsers/service.parser';
import { FunctionParser } from '../parsers/function.parser';

import { PostProcessorInterface } from '../post-processors/post-processor.interface';
import { SortByKeyPostProcessor } from '../post-processors/sort-by-key.post-processor';
import { KeyAsDefaultValuePostProcessor } from '../post-processors/key-as-default-value.post-processor';
import { PurgeObsoleteKeysPostProcessor } from '../post-processors/purge-obsolete-keys.post-processor';
import { CompilerInterface } from '../compilers/compiler.interface';
import { CompilerFactory } from '../compilers/compiler.factory';
import { donateMessage } from '../utils/donate';

export const cli = yargs
.usage('Extract strings from files for translation.\nUsage: $0 [options]')
.version(require(__dirname + '/../../package.json').version)
.alias('version', 'v')
.help('help')
.alias('help', 'h')
.option('input', {
alias: 'i',
describe: 'Paths you would like to extract strings from. You can use path expansion, glob patterns and multiple paths',
default: process.env.PWD,
type: 'array',
normalize: true
})
.check(options => {
options.input.forEach((dir: string) => {
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
throw new Error(`The path you supplied was not found: '${dir}'`);
}
import { TYPES } from '../ioc/types';
import { container } from '../ioc/inversify.config';
import { TaskFactoryOptions, createTask } from './tasks/task.factory';

export const getExtractTask = () => {

let selectors = container.getAll<CompilerInterface>(TYPES.COMPILER).map( compiler => compiler.selector);

});
return true;
})
.option('patterns', {
alias: 'p',
describe: 'Extract strings from the following file patterns',
type: 'array',
default: ['/**/*.html', '/**/*.ts']
})
.option('output', {
alias: 'o',
describe: 'Paths where you would like to save extracted strings. You can use path expansion, glob patterns and multiple paths',
type: 'array',
normalize: true,
required: true
})
.option('marker', {
alias: 'm',
describe: 'Extract strings passed to a marker function',
default: false,
type: 'string'
})
.option('format', {
alias: 'f',
describe: 'Output format',
default: 'json',
type: 'string',
choices: ['json', 'namespaced-json', 'pot']
})
.option('format-indentation', {
alias: 'fi',
describe: 'Output format indentation',
default: '\t',
type: 'string'
})
.option('replace', {
alias: 'r',
describe: 'Replace the contents of output file if it exists (Merges by default)',
default: false,
type: 'boolean'
})
.option('sort', {
alias: 's',
describe: 'Sort strings in alphabetical order when saving',
default: false,
type: 'boolean'
})
.option('clean', {
alias: 'c',
describe: 'Remove obsolete strings when merging',
default: false,
type: 'boolean'
})
.option('key-as-default-value', {
alias: 'k',
describe: 'Use key as default value for translations',
default: false,
type: 'boolean'
})
.exitProcess(true)
.parse(process.argv);
const cli = yargs
.usage('Extract strings from files for translation.\nUsage: $0 [options]')
.version(require(__dirname + '/../../package.json').version)
.alias('version', 'v')
.help('help')
.alias('help', 'h')
.option('input', {
alias: 'i',
describe: 'Paths you would like to extract strings from. You can use path expansion, glob patterns and multiple paths',
default: process.env.PWD,
type: 'array',
normalize: true
})
.check(options => {
options.input.forEach((dir: string) => {
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
throw new Error(`The path you supplied was not found: '${dir}'`);
}

const extractTask = new ExtractTask(cli.input, cli.output, {
replace: cli.replace,
patterns: cli.patterns
});
});
return true;
})
.option('patterns', {
alias: 'p',
describe: 'Extract strings from the following file patterns',
type: 'array',
default: ['/**/*.html', '/**/*.ts']
})
.option('output', {
alias: 'o',
describe: 'Paths where you would like to save extracted strings. You can use path expansion, glob patterns and multiple paths',
type: 'array',
normalize: true,
required: true
})
.option('marker', {
alias: 'm',
describe: 'Extract strings passed to a marker function',
default: false,
type: 'string'
})
.option('format', {
alias: 'f',
describe: 'Output format',
default: 'json',
type: 'string',
choices: selectors
})
.option('format-indentation', {
alias: 'fi',
describe: 'Output format indentation',
default: '\t',
type: 'string'
})
.option('replace', {
alias: 'r',
describe: 'Replace the contents of output file if it exists (Merges by default)',
default: false,
type: 'boolean'
})
.option('sort', {
alias: 's',
describe: 'Sort strings in alphabetical order when saving',
default: false,
type: 'boolean'
})
.option('clean', {
alias: 'c',
describe: 'Remove obsolete strings when merging',
default: false,
type: 'boolean'
})
.option('key-as-default-value', {
alias: 'k',
describe: 'Use key as default value for translations',
default: false,
type: 'boolean'
})
.exitProcess(true)
.parse(process.argv);

// Parsers
const parsers: ParserInterface[] = [
new PipeParser(),
new DirectiveParser(),
new ServiceParser()
];
if (cli.marker) {
parsers.push(new FunctionParser({
identifier: cli.marker
}));
}
extractTask.setParsers(parsers);
console.log(donateMessage);

// Post processors
const postProcessors: PostProcessorInterface[] = [];
if (cli.clean) {
postProcessors.push(new PurgeObsoleteKeysPostProcessor());
}
if (cli.keyAsDefaultValue) {
postProcessors.push(new KeyAsDefaultValuePostProcessor());
}
if (cli.sort) {
postProcessors.push(new SortByKeyPostProcessor());
}
extractTask.setPostProcessors(postProcessors);
// Post processors
const postProcessors: PostProcessorInterface[] = [];
if (cli.clean) {
postProcessors.push(new PurgeObsoleteKeysPostProcessor());
}
if (cli.keyAsDefaultValue) {
postProcessors.push(new KeyAsDefaultValuePostProcessor());
}
if (cli.sort) {
postProcessors.push(new SortByKeyPostProcessor());
}

// Compiler
const compiler: CompilerInterface = CompilerFactory.create(cli.format, {
indentation: cli.formatIndentation
});
extractTask.setCompiler(compiler);
const taskFactoryOptions: TaskFactoryOptions = {
replace: cli.replace,
patterns: cli.patterns,
format: cli.format,
formatIndentation: cli['format-indentation'],
marker: cli.marker,
postProcessors: postProcessors
};

extractTask.execute();
return createTask(cli.input, cli.output, taskFactoryOptions);
};

console.log(donateMessage);
21 changes: 11 additions & 10 deletions src/cli/tasks/extract.task.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { TranslationCollection } from '../../utils/translation.collection';
import { TaskInterface } from './task.interface';
import { TaskInterface, ExtractTaskOptionsInterface } from './task.interface';
import { ParserInterface } from '../../parsers/parser.interface';
import { PostProcessorInterface } from '../../post-processors/post-processor.interface';
import { CompilerInterface } from '../../compilers/compiler.interface';
Expand All @@ -9,27 +9,28 @@ import * as glob from 'glob';
import * as fs from 'fs';
import * as path from 'path';
import * as mkdirp from 'mkdirp';
import { injectable } from 'inversify';

export interface ExtractTaskOptionsInterface {
replace?: boolean;
patterns?: string[];
}

@injectable()
export class ExtractTask implements TaskInterface {

protected options: ExtractTaskOptionsInterface = {
replace: false,
patterns: []
};

protected inputs: string[];
protected outputs: string[];

protected parsers: ParserInterface[] = [];
protected postProcessors: PostProcessorInterface[] = [];
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.options = { ...this.options, ...options };

public setup(input: string[], output: string[], opts?: ExtractTaskOptionsInterface) {
this.inputs = input.map( i => path.resolve(i));
this.outputs = output.map( o => path.resolve(o));
this.options = { ...this.options, ...opts };
}

public execute(): void {
Expand Down
Loading