Skip to content

Commit

Permalink
refactor to es6
Browse files Browse the repository at this point in the history
  • Loading branch information
smhg committed Mar 16, 2019
1 parent 5604c15 commit 71360bf
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 75 deletions.
42 changes: 20 additions & 22 deletions bin/xgettext-template
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
#!/usr/bin/env node
'use strict';

var xgettext = require('..');
var pkg = require('../package.json');
var name = Object.keys(pkg.bin)[0];
const xgettext = require('..');
const pkg = require('../package.json');
const name = Object.keys(pkg.bin)[0];

var languages = xgettext.languages;
var encodings = ['utf8', 'ascii', 'base64'];
const languages = xgettext.languages;
const encodings = ['utf8', 'ascii', 'base64'];

var argv = require('yargs')
const argv = require('yargs')
.usage([
'Usage: ' + name + ' [OPTION] [INPUTFILE]...',
'',
Expand All @@ -31,7 +31,7 @@ var argv = require('yargs')
'language': [
'recognise the specified language\n',
'(',
Object.keys(languages).map(function (key) { return languages[key]; }).join(', '),
Object.keys(languages).map(key => languages[key]).join(', '),
')'
].join(''),
'from-code': 'encoding of input files',
Expand All @@ -56,23 +56,21 @@ var argv = require('yargs')
.group(['keyword'], 'Language specific options:')
.group(['force-po', 'no-location'], 'Output details:')
.group(['help', 'version'], 'Informative output:')
.version('version', 'output version information and exit', function () {
return pkg.name + ' ' + pkg.version;
})
.version('version', 'output version information and exit', () =>
`${pkg.name} ${pkg.version}`
)
.help('help', 'display this help and exit')
.check(function (argv) {
var equalsLanguage = function (ext) {
return argv.language === languages[ext];
};
const equalsLanguage = ext => argv.language === languages[ext];

if (argv.language && !Object.keys(languages).some(equalsLanguage)) {
throw new Error(pkg.name + ': language \'' + argv.language + '\' is not supported');
throw new Error(`${pkg.name}: language '${argv.language}' is not supported`);
}

argv['from-code'] = argv['from-code'].toLowerCase().replace(/\W/g, '');

if (encodings.indexOf(argv['from-code']) < 0) {
throw new Error(pkg.name + ': encoding of input files must be either utf8, ascii or base64');
throw new Error(`${pkg.name}: encoding of input files must be either utf8, ascii or base64`);
}

if (!argv['files-from'] && argv._.length === 0) {
Expand All @@ -82,30 +80,30 @@ var argv = require('yargs')
return true;
})
.epilogue('Report bugs to ' + pkg.bugs.url)
.showHelpOnFail(false, 'Try \'' + pkg.name + ' --help\' for more information.')
.showHelpOnFail(false, `Try '${pkg.name} --help' for more information.`)
.argv;

var input = argv._;
let input = argv._;
delete argv._;

var run = function (subject) {
xgettext(subject, argv, function (po) {
const run = function (subject) {
xgettext(subject, argv, po => {
if (po && (argv.output === '-' || argv.output === '/dev/stdout')) {
process.stdout.write(po);
}
});
};

if (input[0] === '-') {
var stdin = process.stdin;
const stdin = process.stdin;

input = '';

stdin
.on('data', function (chunk) {
.on('data', chunk => {
input += chunk;
})
.on('end', function () {
.on('end', () => {
run(input);
})
.setEncoding(argv['from-code']);
Expand Down
87 changes: 42 additions & 45 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
'use strict';

var fs = require('fs');
var path = require('path');
var gt = require('gettext-parser');
var async = require('async');
var createKeywordSpec = require('./src/keyword-spec');
var objectAssign = require('object-assign');
const fs = require('fs');
const path = require('path');
const gt = require('gettext-parser');
const async = require('async');
const createKeywordSpec = require('./src/keyword-spec');
const objectAssign = require('object-assign');

/**
* Simple is object check.
Expand All @@ -24,10 +24,10 @@ function isObject (item) {
* @param source
*/
function mergeDeep (target, source) {
var dummy;
let dummy;

if (isObject(target) && isObject(source)) {
for (var key in source) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) {
dummy = {};
Expand Down Expand Up @@ -83,12 +83,12 @@ function xgettext (input, options, cb) {
options.directory = [options.directory];
}

var parsers = {};
var getParser = function (name, keywordSpec) {
const parsers = {};
const getParser = function (name, keywordSpec) {
name = name.trim().toLowerCase();

if (!parsers[name]) {
var Parser = require('gettext-' + name);
const Parser = require(`gettext-${name}`);

if (Object.keys(keywordSpec).length > 0) {
parsers[name] = new Parser(keywordSpec);
Expand All @@ -102,17 +102,17 @@ function xgettext (input, options, cb) {
return parsers[name];
};

var keywordSpec = createKeywordSpec(options.keyword);
var translations = Object.create(null);
const keywordSpec = createKeywordSpec(options.keyword);
const translations = Object.create(null);

var parseTemplate = function (parser, template, linePrefixer) {
var strings = parser.parse(template);
const parseTemplate = function (parser, template, linePrefixer) {
const strings = parser.parse(template);

for (var key in strings) {
for (const key in strings) {
if (strings.hasOwnProperty(key)) {
var msgctxt = strings[key].msgctxt || '';
var context = translations[msgctxt] || (translations[msgctxt] = {});
var msgid = strings[key].msgid || key;
const msgctxt = strings[key].msgctxt || '';
const context = translations[msgctxt] || (translations[msgctxt] = {});
const msgid = strings[key].msgid || key;
context[msgid] = context[msgid] || { msgid: msgid, comments: {} };

if (msgctxt) {
Expand All @@ -135,11 +135,11 @@ function xgettext (input, options, cb) {
}
};

var output = function () {
const output = function () {
if (cb) {
if (Object.keys(translations).length > 0 || options['force-po']) {
var existing = {};
var writeToStdout = options.output === '-' || options.output === '/dev/stdout';
let existing = {};
const writeToStdout = options.output === '-' || options.output === '/dev/stdout';

if (!writeToStdout && options['join-existing']) {
try {
Expand All @@ -154,18 +154,18 @@ function xgettext (input, options, cb) {
mergeDeep(translations, existing.translations);
}

var po = gt.po.compile({
const po = gt.po.compile({
charset: options['from-code'],
headers: {
'content-type': 'text/plain; charset=' + options['from-code']
'content-type': `text/plain; charset=${options['from-code']}`
},
translations: translations
});

if (writeToStdout) {
cb(po);
} else {
fs.writeFile(options.output, po, function (err) {
fs.writeFile(options.output, po, err => {
if (err) {
throw err;
}
Expand All @@ -180,44 +180,41 @@ function xgettext (input, options, cb) {
};

if (typeof input === 'string') {
parseTemplate(getParser(options.language, keywordSpec), input, function (line) {
return 'standard input:' + line;
});
parseTemplate(
getParser(options.language, keywordSpec),
input,
line => `standard input:${line}`
);

output();
} else {
var addPath = function (path) {
return function (line) {
return path + ':' + line;
};
};
const addPath = path => line => `${path}:${line}`;

if (options['files-from']) {
input = fs.readFileSync(options['files-from'], options['from-code'])
.split('\n')
.filter(function (line) {
return line.trim().length > 0;
});
.filter(line => line.trim().length > 0);
}

var files = options.directory.reduce(function (result, directory) {
return result.concat(input.map(function (file) {
return path.join(directory, file.replace(/\\/g, path.sep));
}));
}, []);
const files = options.directory.reduce(
(result, directory) => result.concat(input.map(
file => path.join(directory, file.replace(/\\/g, path.sep))
)),
[]
);

async.parallel(files.map(function (file) {
return function (cb) {
fs.readFile(path.resolve(file), options['from-code'], function (err, res) {
fs.readFile(path.resolve(file), options['from-code'], (err, res) => {
if (err) {
throw err;
}

var extension = path.extname(file);
var language = options.language || xgettext.languages[extension];
const extension = path.extname(file);
const language = options.language || xgettext.languages[extension];

if (!language) {
throw new Error('No language specified for extension \'' + extension + '\'.');
throw new Error(`No language specified for extension '${extension}'.`);
}

parseTemplate(getParser(language, keywordSpec), res, addPath(file.replace(/\\/g, '/')));
Expand Down
16 changes: 8 additions & 8 deletions src/keyword-spec.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
'use strict';

var objectAssign = require('object-assign');
const objectAssign = require('object-assign');

var specPattern = / *([^:,]+) *(?::([^, ]+(?:,[^, ]+)*))? */g,
contextPattern = /^(\d)+c$/;
const specPattern = / *([^:,]+) *(?::([^, ]+(?:,[^, ]+)*))? */g;
const contextPattern = /^(\d)+c$/;

function indexify (idx) {
return parseInt(idx, 10) - 1;
}

function addToSpec (spec, item) {
var parts;
let parts;

while ((parts = specPattern.exec(item)) !== null) {
var keyword = parts[1];
var positions = {msgid: 0};
const keyword = parts[1];
let positions = { msgid: 0 };

if (parts[2]) {
positions = parts[2]
.trim()
.split(/ ?, ?/)
.reduce(function (positions, position) {
var context = position.match(contextPattern);
.reduce((positions, position) => {
const context = position.match(contextPattern);

if (context) {
positions.msgctxt = indexify(context[1]);
Expand Down

0 comments on commit 71360bf

Please sign in to comment.