Skip to content

Instantly share code, notes, and snippets.

@slonoed
Created April 28, 2016 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save slonoed/4b451ff96d754036477a4c121d13adcb to your computer and use it in GitHub Desktop.
Save slonoed/4b451ff96d754036477a4c121d13adcb to your computer and use it in GitHub Desktop.
'use strict';
const _ = require('lodash');
const path = require('path');
const estraverse = require('estraverse');
const esprima = require('esprima');
const recursive = require('recursive-readdir');
const babel = require('babel-core')
const fs = require('fs');
const traverseFileSystem = function (currentPath, onJs) {
var files = fs.readdirSync(currentPath);
for (var i in files) {
var currentFile = currentPath + '/' + files[i];
var stats = fs.statSync(currentFile);
if (stats.isFile()) {
if (/\.js$/.test(currentFile)) {
onJs(currentFile);
}
}
else if (stats.isDirectory()) {
traverseFileSystem(currentFile, onJs);
}
}
};
const keys = {};
function parseFile(name) {
const a = babel.transformFileSync(name);
const ast = a.ast;
function fromPluralNode(node) {
const strs = node.arguments[0].elements
.filter(e => e.type === 'Literal' && _.isString(e.value))
.map(e => e.value);
return strs.length ? strs : null;
}
function process(node) {
const v = node.arguments[0].value;
keys[v] = { msgid: v, msgstr: v };
}
function processPlural(node) {
var k = [];
for (var i = 0; i < 3; i++) {
k.push(node.arguments[i].value);
}
const arg = i => node.arguments[i];
const av = i => arg(i).value
keys[av(0) + ' plural ' + av(2)] = {
msgid: av(0),
msgid_plural: av(2),
msgstr: [av(0), av(1), av(2)]
};
}
estraverse.traverse(esprima.parse(a.code), {
leave: function (node, parent) {
if (node.type === 'CallExpression' && node.callee.name === 't') {
const arg = node.arguments[0];
const type = node.arguments[0].type;
const value = node.arguments[0].value;
if (type === 'Literal' && _.isString(value)) {
process(node);
} else {
console.error(node);
throw new Error('Wrong node');
}
}
if (node.type === 'CallExpression' && node.callee.name === 'tp') {
processPlural(node)
}
}
});
}
traverseFileSystem(path.join(__dirname, '../app'), parseFile);
const data = _.values(keys)
.map((k,i) => {
const s = JSON.stringify;
let text = `#: test ${i}\nmsgid ${s(k.msgid)}\n`;
if (k.msgid_plural) {
const plural = k.msgstr.map((m,i) => `msgstr[${i}] ${s(m)}`).join('\n');
text += `msgid_plural ${s(k.msgid_plural)}\n` + plural;
}
else
text += `msgstr ${s(k.msgstr)}`;
return text;
})
.join('\n\n') + '\n';
fs.writeFileSync(path.join(__dirname, '../locales/exchange.po'), data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment