-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathgulpfile.js
344 lines (301 loc) · 11 KB
/
gulpfile.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
const gulp = require('gulp');
const angularGettext = require('gulp-angular-gettext');
const nodemon = require('gulp-nodemon');
const templatecache = require('gulp-angular-templatecache');
const del = require('del');
const path = require('path');
const mergeStream = require('merge-stream');
const child_process = require('child_process');
const { po } = require('gettext-parser');
const { Transform } = require('stream');
const Vinyl = require('vinyl');
const po2json = require('po2json');
const translations = gulp.series(translations_clean, translations_build, translations_esm_build);
const templatesModules = [
'dashboard-edit',
'dashboard-view',
'inspector',
'layer-edit',
'report',
'report-edit',
];
const templates = gulp.parallel(templatesModules.map(m => templates_compile(m)));
const defaultTask = gulp.parallel(
css,
translations,
templates,
);
module.exports = {
default: defaultTask,
dev: gulp.parallel(watch_less, watch_templates, nodemon_start),
css,
translations,
templates,
doc,
pot,
'po:update': gulp.series(pot, po_update),
'watch:doc': watch_doc,
'watch:less': watch_less,
'watch:templates': watch_templates,
watch: gulp.parallel(watch_doc, watch_less, watch_templates),
};
function translations_clean () {
return del('public/translations/*');
}
function css () {
const less = require('gulp-less');
return gulp.src('public/less/bootstrap.less')
.pipe(less({
paths: [
path.join(__dirname, 'node_modules', 'bootstrap', 'less'),
],
}))
.pipe(gulp.dest('public/css'));
}
function translations_build () {
return gulp.src(['language/*.po'])
.pipe(poToJs())
.pipe(gulp.dest('public/translations'));
}
function translations_esm_build () {
return gulp.src(['language/*.po'])
.pipe(poToJs({ esm: true }))
.pipe(gulp.dest('public/translations'));
}
function templates_compile (name) {
const f = function () {
const base = path.join(__dirname, 'public', 'partials');
return gulp.src(`public/partials/${name}/*.html`, { base })
.pipe(templatecache(name + '.templates.js', {
root: 'partials',
module: 'app.' + name,
moduleSystem: 'IIFE',
}))
.pipe(gulp.dest('public/js/ng/' + name));
};
f.displayName = 'templates:' + name;
return f;
}
function nodemon_start (done) {
nodemon({
script: 'bin/www',
ext: 'js',
env: { NODE_ENV: 'development' },
watch: [
'server/',
],
done
});
}
function pot () {
const streamJs = gulp.src(['public/js/**/*.js', 'server/**/*.js'], { base: '.' })
.pipe(xgettextJs());
const streamHtml = gulp.src(['public/partials/**/*.html'], { base: '.' })
.pipe(angularGettext.extract('template.pot'));
const streamLiquid = gulp.src(['views/**/*.liquid'], { base: '.' })
.pipe(xgettextLiquid());
const headers = {
'project-id-version': 'Urungi',
'content-type': 'text/plain; charset=utf-8',
'content-transfer-encoding': '8bit',
};
return mergeStream(streamJs, streamHtml, streamLiquid)
.pipe(concatPo('template.pot', { headers }))
.pipe(gulp.dest('language'));
}
function po_update () {
const fs = require('fs');
const util = require('util');
const exec = util.promisify(child_process.exec);
const readdir = util.promisify(fs.readdir);
return readdir('language').then(files => {
const promises = files
.filter(file => file.endsWith('.po'))
.map(file => exec('msgmerge --quiet --backup=none -U language/' + file + ' language/template.pot'));
return Promise.all(promises);
});
}
function watch_templates () {
gulp.watch('public/partials/**/*.html', templates);
}
function watch_less () {
gulp.watch('public/less/*.less', css);
}
function watch_doc () {
gulp.watch(['doc/user/**', '!doc/user/_build/**'], doc);
}
function doc (done) {
const options = {
env: Object.assign({
SPHINXOPTS: '-q --color',
}, process.env),
};
child_process.exec('make -C doc/user clean html', options, function (err, stdout, stderr) {
if (err) {
done(err);
return;
}
process.stderr.write(stderr);
done();
});
}
function xgettextLiquid () {
function addToTranslationObject (translationObject, { msgid, msgid_plural, token }) {
if (!translationObject.translations[''][msgid]) {
translationObject.translations[''][msgid] = {
msgid,
msgid_plural,
msgstr: '',
comments: {
reference: '',
}
};
}
const reference = path.relative(__dirname, token.file) + ':' + token.getPosition()[0];
if (reference) {
if (translationObject.translations[''][msgid].comments.reference) {
translationObject.translations[''][msgid].comments.reference += '\n';
}
translationObject.translations[''][msgid].comments.reference += reference;
}
}
return new Transform({
objectMode: true,
transform (file, encoding, callback) {
const { TokenKind, Tokenizer } = require('liquidjs');
const liquid = require('./server/config/liquid.js');
const data = {
charset: 'utf8',
headers: {
'content-type': 'text/plain; charset=utf-8',
'content-transfer-encoding': '8bit',
},
translations: {
'': {},
}
};
const tokenizer = new Tokenizer(file.contents.toString(), liquid.options.operatorsTrie, file.path);
const tokens = tokenizer.readTopLevelTokens(liquid.options);
const tagTokens = tokens.filter(t => t.kind === TokenKind.Tag);
const translationTagTokens = tagTokens.filter(t => ['t', 'tn'].includes(t.name));
for (const token of translationTagTokens) {
const tokenizer = new Tokenizer(token.args);
if (token.name === 't') {
const msgidToken = tokenizer.readQuoted();
if (msgidToken) {
const msgid = msgidToken.content;
addToTranslationObject(data, { msgid, token });
}
} else if (token.name === 'tn') {
const msgidToken = tokenizer.readQuoted();
const msgidPluralToken = tokenizer.readQuoted();
if (msgidToken && msgidPluralToken) {
const msgid = msgidToken.content;
const msgid_plural = msgidPluralToken.content;
addToTranslationObject(data, { msgid, msgid_plural, token });
}
}
}
file.contents = po.compile(data);
callback(null, file);
},
});
}
function xgettextJs () {
return new Transform({
objectMode: true,
transform (file, encoding, callback) {
const relativePath = path.relative(__dirname, file.path);
const cmd = 'xgettext -o - --from-code=UTF-8 --omit-header -L JavaScript -kt ' + relativePath;
const po = child_process.execSync(cmd);
file.contents = po;
callback(null, file);
},
});
}
function concatPo (filename, options) {
const translationObject = {
charset: 'utf8',
headers: options.headers || {},
translations: {
'': {},
},
};
return new Transform({
objectMode: true,
transform (file, encoding, callback) {
const data = po.parse(file.contents);
for (const msgctxt in data.translations) {
for (const msgid in data.translations[msgctxt]) {
if (!translationObject.translations[msgctxt]) {
translationObject.translations[msgctxt] = {};
}
if (!translationObject.translations[msgctxt][msgid]) {
translationObject.translations[msgctxt][msgid] = data.translations[msgctxt][msgid];
continue;
}
const fileMsg = data.translations[msgctxt][msgid];
if (!fileMsg.comments) {
continue;
}
const msg = translationObject.translations[msgctxt][msgid];
if (!msg.comments) {
msg.comments = {};
}
for (const key of ['translator', 'reference', 'extracted', 'flag', 'previous']) {
if (!fileMsg.comments[key]) {
continue;
}
const comments = msg.comments[key] ? msg.comments[key].split(/\r?\n|\r/) : [];
const fileComments = fileMsg.comments[key].split(/\r?\n|\r/);
const mergedComments = comments.concat(fileComments);
mergedComments.sort();
msg.comments[key] = mergedComments.join('\n');
}
}
}
callback();
},
flush (callback) {
const file = new Vinyl();
file.path = path.join(file.base, filename);
file.contents = Buffer.concat([
po.compile(translationObject, { sort: true, foldLength: 0 }),
Buffer.from('\n'),
]);
callback(null, file);
},
});
}
function poToJs (options = {}) {
return new Transform({
objectMode: true,
transform (file, encoding, callback) {
const jsonData = po2json.parse(file.contents);
const json = {};
if ('' in jsonData) {
json[''] = {
language: jsonData[''].language,
'plural-forms': jsonData['']['plural-forms']
};
delete jsonData[''];
}
for (const key in jsonData) {
if (jsonData[key][1] !== '') {
json[key] = jsonData[key].length === 2 ? jsonData[key][1] : jsonData[key].slice(1);
}
}
// Make it work in the browser and in Node
if (options.esm) {
const js = `export default ${JSON.stringify(json)}`;
file.contents = Buffer.from(js);
file.extname = '.esm.js';
} else {
const js = `(((r,f)=>{if(typeof module==="object"&&module.exports){module.exports=f();}else{r.Urungi.messages=f();}})(typeof self!=="undefined"?self:this,()=>(${JSON.stringify(json)})))`;
file.contents = Buffer.from(js);
file.extname = '.js';
}
callback(null, file);
},
});
}