-
Notifications
You must be signed in to change notification settings - Fork 35
/
index.js
249 lines (209 loc) · 6.21 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
'use strict';
import fs from 'fs';
import path from 'path';
import gt from 'gettext-parser';
import async from 'async';
import createKeywordSpec from './src/keyword-spec.js';
import objectAssign from 'object-assign';
import ejs from 'gettext-ejs';
import handlebars from 'gettext-handlebars';
import swig from 'gettext-swig';
import volt from 'gettext-volt';
const PARSERS = {
ejs,
handlebars,
swig,
volt
};
/**
* Simple is object check.
*
* @param item
* @returns {boolean}
*/
function isObject (item) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
/**
* Deep merge two objects.
*
* @param target
* @param source
*/
function mergeDeep (target, source) {
let dummy;
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) {
dummy = {};
dummy[key] = {};
objectAssign(target, dummy);
}
mergeDeep(target[key], source[key]);
} else {
dummy = {};
dummy[key] = source[key];
objectAssign(target, dummy);
}
}
}
return target;
}
/**
* Parse input and save the i18n strings to a PO file.
*
* @param Array|String input Array of files to parse or input string
* @param Object options Options
* @param Function cb Callback
*/
function xgettext (input, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
if (!input) {
throw new Error('No input specified');
}
if (!options.language && typeof input === 'string') {
throw new Error('Language is required');
}
options.output = options.output || 'messages.po';
options.directory = options.directory || ['.'];
options.keyword = options.keyword || [];
options['from-code'] = options['from-code'] || 'utf8';
options['force-po'] = options['force-po'] || false;
options['join-existing'] = options['join-existing'] || false;
options['sort-output'] = options['sort-output'] || false;
if (typeof options.keyword === 'string') {
options.keyword = [options.keyword];
}
if (typeof options.directory === 'string') {
options.directory = [options.directory];
}
const parsers = {};
const getParser = function (name, keywordSpec) {
name = name.trim().toLowerCase();
if (!parsers[name]) {
const Parser = PARSERS[name];
if (Object.keys(keywordSpec).length > 0) {
parsers[name] = new Parser(keywordSpec);
} else if (Parser.keywordSpec) {
parsers[name] = new Parser(Parser.keywordSpec);
} else {
parsers[name] = new Parser();
}
}
return parsers[name];
};
const keywordSpec = createKeywordSpec(options.keyword);
const translations = Object.create(null);
const parseTemplate = function (parser, template, linePrefixer) {
const strings = parser.parse(template);
for (const key in strings) {
if (Object.prototype.hasOwnProperty.call(strings, key)) {
const msgctxt = strings[key].msgctxt || '';
const context = translations[msgctxt] || (translations[msgctxt] = {});
const msgid = strings[key].msgid || key;
context[msgid] = context[msgid] || { msgid, comments: {} };
if (msgctxt) {
context[msgid].msgctxt = strings[key].msgctxt;
}
if (strings[key].plural) {
context[msgid].msgid_plural = context[msgid].msgid_plural || strings[key].plural;
context[msgid].msgstr = ['', ''];
}
if (!options['no-location']) {
context[msgid].comments.reference = (context[msgid].comments.reference || '')
.split('\n')
.concat(strings[key].line.map(linePrefixer))
.join('\n')
.trim('\n');
}
}
}
};
const output = function () {
if (cb) {
if (Object.keys(translations).length > 0 || options['force-po']) {
let existing = {};
const writeToStdout = options.output === '-' || options.output === '/dev/stdout';
if (!writeToStdout && options['join-existing']) {
try {
fs.accessSync(options.output, fs.F_OK);
existing = gt.po.parse(fs.readFileSync(options.output, {
encoding: options['from-code']
}));
} catch (e) {
// ignore non-existing file
}
mergeDeep(translations, existing.translations);
}
const po = gt.po.compile({
charset: options['from-code'],
headers: {
'content-type': `text/plain; charset=${options['from-code']}`
},
translations
}, { sort: options['sort-output'] });
if (writeToStdout) {
cb(po);
} else {
fs.writeFile(options.output, po, err => {
if (err) {
throw err;
}
cb(po);
});
}
} else {
cb();
}
}
};
if (typeof input === 'string') {
parseTemplate(
getParser(options.language, keywordSpec),
input,
line => `standard input:${line}`
);
output();
} else {
const addPath = path => line => `${path}:${line}`;
if (options['files-from']) {
input = fs.readFileSync(options['files-from'], options['from-code'])
.split('\n')
.filter(line => line.trim().length > 0);
}
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'], (err, res) => {
if (err) {
throw err;
}
const extension = path.extname(file);
const language = options.language || xgettext.languages[extension];
if (!language) {
throw new Error(`No language specified for extension '${extension}'.`);
}
parseTemplate(getParser(language, keywordSpec), res, addPath(file.replace(/\\/g, '/')));
cb();
});
};
}), output);
}
}
xgettext.languages = {
'.hbs': 'Handlebars',
'.swig': 'Swig',
'.volt': 'Volt',
'.ejs': 'EJS'
};
export default xgettext;