forked from bpatrik/pigallery2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.ts
327 lines (284 loc) · 10.6 KB
/
gulpfile.ts
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
import * as gulp from 'gulp';
import * as fs from 'fs';
import {promises as fsp} from 'fs';
import * as path from 'path';
import * as util from 'util';
import * as zip from 'gulp-zip';
import * as ts from 'gulp-typescript';
import * as xml2js from 'xml2js';
import * as child_process from 'child_process';
// @ts-ignore
import * as jeditor from 'gulp-json-editor';
import {XLIFF} from 'xlf-google-translate';
import {PrivateConfigClass} from './src/common/config/private/Config';
import {ConfigClassBuilder} from 'typeconfig/src/decorators/builders/ConfigClassBuilder';
const execPr = util.promisify(child_process.exec);
const translationFolder = 'translate';
const tsBackendProject = ts.createProject('tsconfig.json');
declare var process: NodeJS.Process;
const getSwitch = (name: string, def: string = null): string => {
name = '--' + name;
for (let i = 0; i < process.argv.length; i++) {
if (process.argv[i].startsWith(name + '=')) {
return process.argv[i].replace(name + '=', '').trim();
}
if (process.argv[i].startsWith(name)) {
if (i + 1 < process.argv.length) {
return process.argv[i + 1].trim();
}
return 'true';
}
}
return def;
};
gulp.task('build-backend', (): any =>
gulp.src([
'src/common/**/*.ts',
'src/backend/**/*.ts',
'benchmark/**/*.ts'], {base: '.'})
.pipe(tsBackendProject())
.js
.pipe(gulp.dest('./release')));
const createDynamicTranslationFile = async (language: string): Promise<void> => {
// load
const folder = './src/frontend/' + translationFolder;
const data: string = await fsp.readFile(path.join(folder, `messages.${language}.xlf`), 'utf-8');
const translationXml: XLIFF.Root = await xml2js.parseStringPromise(data);
// clean translations, keep only .ts transaltions
const hasTsTranslation = (cg: XLIFF.ContextGroup): boolean =>
cg.context.findIndex((c: any): boolean => c.$['context-type'] === 'sourcefile' && c._.endsWith('.ts')) !== -1;
const translations = translationXml.xliff.file[0].body[0]['trans-unit'];
const filtered = translations.filter((tr): boolean => tr['context-group'].findIndex(hasTsTranslation) !== -1);
filtered.forEach((tr): boolean => delete tr['context-group']);
translationXml.xliff.file[0].body[0]['trans-unit'] = filtered;
// save
const builder = new xml2js.Builder();
const xml = builder.buildObject(translationXml);
await fsp.writeFile(path.join(folder, `ts-only-msg.${language}.xlf`), xml);
};
const removeDynamicTranslationFile = async (language: string): Promise<void> => {
const translationFile = path.join('./src/frontend/', translationFolder, `ts-only-msg.${language}.xlf`);
fsp.unlink(translationFile);
};
const setDynTransFileAtAppModule = async (language: string): Promise<void> => {
const file = './src/frontend/app/app.module.ts';
let data: string = await fsp.readFile(file, 'utf-8');
const from = 'messages.${locale}.xlf';
const to = `ts-only-msg.${language}.xlf`;
data = data.replace(from, to);
await fsp.writeFile(file, data);
};
const resetAppModule = async (language: string): Promise<void> => {
const file = './src/frontend/app/app.module.ts';
let data: string = await fsp.readFile(file, 'utf-8');
const from = 'messages.${locale}.xlf';
const to = `ts-only-msg.${language}.xlf`;
data = data.replace(to, from);
await fsp.writeFile(file, data);
};
const createFrontendTask = (type: string, language: string, script: string): void => {
gulp.task(type, async (cb): Promise<void> => {
try {
const {stdout, stderr} = await execPr(script);
console.log(stdout);
console.error(stderr);
} catch (e) {
console.error(e);
cb(e);
}
});
};
const getLanguages = (): any[] | string[] => {
if (!fs.existsSync('./src/frontend/' + translationFolder)) {
return [];
}
const dirCont = fs.readdirSync('./src/frontend/' + translationFolder);
const files: string[] = dirCont.filter((elm): any => {
return elm.match(/.*\.[a-zA-Z]+\.(xlf)/ig);
});
// get languages to filter
let languageFilter: string[] = null;
if (getSwitch('languages')) {
languageFilter = getSwitch('languages').split(',');
}
let languages = files.map((f: string): string => {
return f.split('.')[1];
});
if (languageFilter !== null) {
languages = languages.filter((l): boolean => {
return languageFilter.indexOf(l) !== -1;
});
}
return languages;
};
gulp.task('build-frontend', ((): any => {
const tasks = [];
createFrontendTask('build-frontend-release default', 'all',
'ng build --prod --no-progress --output-path=./release/dist');
tasks.push('build-frontend-release default');
return gulp.series(...tasks);
})());
gulp.task('copy-static', (): any => gulp.src([
'src/backend/model/diagnostics/blank.jpg',
'README.md',
// 'package-lock.json', should not add, it keeps optional packages optional even with --force-opt-packages.
'LICENSE'], {base: '.'})
.pipe(gulp.dest('./release')));
gulp.task('copy-package', (): any => gulp.src([
'package.json'], {base: '.'})
.pipe(jeditor((json: {
devDependencies: { [key: string]: string },
scripts: { [key: string]: string },
dependencies: { [key: string]: string },
optionalDependencies: { [key: string]: string },
buildTime: string,
buildCommitHash: string
}): {
devDependencies: { [p: string]: string };
scripts: { [p: string]: string };
dependencies: { [p: string]: string };
optionalDependencies: { [p: string]: string };
buildTime: string; buildCommitHash: string
} => {
delete json.devDependencies;
json.scripts = {start: 'node ./src/backend/index.js'};
if (getSwitch('skip-opt-packages')) {
const skipPackages = getSwitch('skip-opt-packages').split(',');
for (const pkg of skipPackages) {
for (const key of Object.keys(json.optionalDependencies)) {
if (key.indexOf(pkg) !== -1) {
delete json.optionalDependencies[key];
}
}
}
}
if (!!getSwitch('force-opt-packages')) {
for (const key of Object.keys(json.optionalDependencies)) {
json.dependencies[key] = json.optionalDependencies[key];
}
delete json.optionalDependencies;
}
json.buildTime = (new Date()).toISOString();
try {
json.buildCommitHash = require('child_process').execSync('git rev-parse HEAD').toString().trim();
} catch (e) {
}
return json;
}))
.pipe(gulp.dest('./release')));
gulp.task('zip-release', (): any =>
gulp.src(['release/**/*'], {base: './release'})
.pipe(zip('pigallery2.zip'))
.pipe(gulp.dest('.')));
gulp.task('create-release', gulp.series('build-frontend', 'build-backend', 'copy-static', 'copy-package', 'zip-release'));
const simpleBuild = (isProd: boolean): any => {
const tasks = [];
let cmd = 'ng build ';
if (isProd) {
cmd += ' --prod --no-extract-licenses ';
}
if (!process.env.CI) {
createFrontendTask('build-frontend default', 'all', cmd);
} else {
createFrontendTask('build-frontend default', 'all', cmd + '--localize=false');
}
tasks.push('build-frontend default');
return gulp.series(...tasks);
};
gulp.task('extract-locale', async (cb): Promise<any> => {
console.log('creating source translation file: locale.source.xlf');
try {
{
const {stdout, stderr} = await execPr('ng extract-i18n --out-file=locale.source.xlf --format=xlf',
{maxBuffer: 1024 * 1024});
console.log(stdout);
console.error(stderr);
}
{
const {stdout, stderr} = await execPr('ngx-extractor -i src/frontend/**/*.ts -f xlf --out-file locale.source.xlf');
console.log(stdout);
console.error(stderr);
}
cb();
} catch (e) {
console.error(e);
return cb(e);
}
});
const translate = async (list: any[], cb: (err?: any) => void): Promise<void> => {
try {
const localsStr = '"[\\"' + list.join('\\",\\"') + '\\"]"';
const {stdout, stderr} = await execPr('xlf-google-translate ' +
'--source-lang="en" ' +
'--source-file="./locale.source.xlf" ' +
'--destination-filename="messages" ' +
'--destination-folder="./src/frontend/"' + translationFolder + ' --destination-languages=' + localsStr);
console.log(stdout);
console.error(stderr);
cb();
} catch (e) {
console.error(e);
return cb(e);
}
};
const merge = async (list: any[], cb: (err?: any) => void): Promise<void> => {
try {
const localsStr = '"[\\"' + list.join('\\",\\"') + '\\"]"';
const command = 'xlf-google-translate ' +
'--method="extend-only" ' +
'--source-lang="en" ' +
'--source-file="./locale.source.xlf" ' +
'--destination-filename="messages" ' +
'--destination-folder="./src/frontend/' + translationFolder + '" ' +
'--destination-languages=' + localsStr;
console.log(command);
const {stdout, stderr} = await execPr(command);
console.log(stdout);
console.error(stderr);
cb();
} catch (e) {
console.error(e);
return cb(e);
}
};
gulp.task('update-translation-only', (cb): void => {
translate(getLanguages(), cb).catch(console.error);
});
gulp.task('merge-translation-only', (cb): void => {
merge(getLanguages(), cb).catch(console.error);
});
gulp.task('update-translation', gulp.series('extract-locale', 'update-translation-only'));
gulp.task('merge-new-translation', gulp.series('extract-locale', 'merge-translation-only'));
gulp.task('add-translation-only', (cb): any => {
const languages = getLanguages();
let lng = null;
for (let i = 0; i < process.argv.length - 1; i++) {
if (process.argv[i] === 'add-translation') {
lng = process.argv[i + 1].replace('--', '');
}
}
if (lng == null) {
console.error('Error: set language with \'--\' e.g: npm run add-translation -- --en');
return cb();
}
if (languages.indexOf(lng) !== -1) {
console.error('Error: language already exists, can\'t add. These language(s) already exist(s): ' + languages);
return cb();
}
translate([lng], cb);
});
gulp.task('generate-man', async (cb): Promise<void> => {
const defCFG = ConfigClassBuilder.attachInterface(new PrivateConfigClass());
defCFG.Server.sessionSecret = [];
let txt = '# Pigallery 2 man page\n';
txt += 'pigallery2 uses [typeconfig](https://github.com/bpatrik/typeconfig) for configuration\n\n';
txt += '`npm start -- --help` prints the following:\n\n';
txt += '```\n' + ConfigClassBuilder.attachPrivateInterface(defCFG).__printMan() + '```';
txt += '\n\n ### `config.json` sample:\n';
txt += '```json\n' + JSON.stringify(defCFG, null, 4) + '```';
await fsp.writeFile('MANPAGE.md', txt);
cb();
});
gulp.task('add-translation', gulp.series('extract-locale', 'add-translation-only'));
gulp.task('build-dev', simpleBuild(false));
gulp.task('build-prod', simpleBuild(true));