-
Notifications
You must be signed in to change notification settings - Fork 165
/
gulpfile.js
483 lines (411 loc) · 15.7 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
'use strict';
/********
* setup *
********/
const nwVersion = '0.18.1',
availablePlatforms = ['linux32', 'linux64', 'win32', 'win64', 'osx64'],
releasesDir = 'build';
/***************
* dependencies *
***************/
const gulp = require('gulp'),
glp = require('gulp-load-plugins')(),
runSequence = require('run-sequence'),
del = require('del'),
nwBuilder = require('nw-builder'),
currentPlatform = require('nw-builder/lib/detectCurrentPlatform.js'),
yargs = require('yargs'),
nib = require('nib'),
git = require('git-rev'),
fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
spawn = require('child_process').spawn,
pkJson = require('./package.json');
/***********
* custom *
***********/
// returns an array of platforms that should be built
const parsePlatforms = () => {
const requestedPlatforms = (yargs.argv.platforms || currentPlatform()).split(','),
validPlatforms = [];
for (let i in requestedPlatforms) {
if (availablePlatforms.indexOf(requestedPlatforms[i]) !== -1) {
validPlatforms.push(requestedPlatforms[i]);
}
}
// for osx and win, 32-bits works on 64, if needed
if (availablePlatforms.indexOf('win64') === -1 && requestedPlatforms.indexOf('win64') !== -1) {
validPlatforms.push('win32');
}
if (availablePlatforms.indexOf('osx64') === -1 && requestedPlatforms.indexOf('osx64') !== -1) {
validPlatforms.push('osx32');
}
// remove duplicates
validPlatforms.filter((item, pos) => {
return validPlatforms.indexOf(item) === pos;
});
return requestedPlatforms[0] === 'all' ? availablePlatforms : validPlatforms;
};
// returns an array of paths with the node_modules to include in builds
const parseReqDeps = () => {
return new Promise((resolve, reject) => {
exec('npm ls --production=true --parseable=true', (error, stdout, stderr) => {
if (error || stderr) {
reject(error || stderr);
} else {
// build array
let npmList = stdout.split('\n');
// remove empty or soon-to-be empty
npmList = npmList.filter((line) => {
return line.replace(process.cwd().toString(), '');
});
// format for nw-builder
npmList = npmList.map((line) => {
return line.replace(process.cwd(), '.') + '/**';
});
// return
resolve(npmList);
}
});
});
};
// console.log for thenable promises
const log = () => {
console.log.apply(console, arguments);
};
// handle callbacks
function promiseCallback(fn) {
// use ES6 rest params for much cleaner code
let args = Array.prototype.slice.call(arguments, 1);
return new Promise((resolve, reject) => {
fn.apply(this, args.concat([res => {
return res ?
resolve(res) :
reject(res);
}]));
});
}
// del wrapper for `clean` tasks
const deleteAndLog = (path, what) => (
() => (
del(path).then(paths => {
paths.length ?
console.log('Deleted', what, ':\n', paths.join('\n')) :
console.log('Nothing to delete');
})
)
);
// nw-builder configuration
const nw = new nwBuilder({
files: [],
buildDir: releasesDir,
zip: false,
macIcns: './src/app/images/popcorntime.icns',
version: nwVersion,
downloadUrl: 'https://get.popcorntime.sh/repo/nw/',
platforms: parsePlatforms()
}).on('log', console.log);
/*************
* gulp tasks *
*************/
// start app in development
gulp.task('run', () => {
return new Promise((resolve, reject) => {
let platform = parsePlatforms()[0],
bin = path.join('cache', nwVersion, platform);
// path to nw binary
switch(platform.slice(0,3)) {
case 'osx':
bin += '/nwjs.app/Contents/MacOS/nwjs';
break;
case 'lin':
bin += '/nw';
break;
case 'win':
bin += '/nw.exe';
break;
default:
reject(new Error('Unsupported %s platform', platform));
}
console.log('Running %s from cache', platform);
// spawn cached binary with package.json, toggle dev flag
const child = spawn(bin, ['.', '--development']);
// nwjs console speaks to stderr
child.stderr.on('data', (buf) => {
console.log(buf.toString());
});
child.on('close', (exitCode) => {
console.log('%s exited with code %d', pkJson.name, exitCode);
resolve();
});
child.on('error', (error) => {
// nw binary most probably missing
if (error.code === 'ENOENT') {
console.log('%s is not available in cache. Try running `gulp build` beforehand', platform);
}
reject(error);
});
});
});
// build app from sources
gulp.task('build', (callback) => {
runSequence('injectgit', 'css', 'nwjs', callback);
});
// create redistribuable packages
gulp.task('dist', (callback) => {
runSequence('build', 'compress', 'deb', 'nsis', callback);
});
// clean gulp-created files
gulp.task('clean', ['clean:dist', 'clean:build', 'clean:css']);
// default is help, because we can!
gulp.task('default', () => {
console.log([
'\nBasic usage:',
' gulp run\tStart the application in dev mode',
' gulp build\tBuild the application',
' gulp dist\tCreate a redistribuable package',
'\nAvailable options:',
' --platforms=<platform>',
'\tArguments: ' + availablePlatforms + ',all',
'\tExample: `gulp build --platforms=all`',
'\nUse `gulp --tasks` to show the task dependency tree of gulpfile.js\n'
].join('\n'));
});
// download and compile nwjs
gulp.task('nwjs', () => {
return parseReqDeps().then((requiredDeps) => {
// required files
nw.options.files = ['./src/**', '!./src/app/styl/**', './package.json', './README.md', './CHANGELOG.md', './LICENSE.txt', './.git.json'];
// add node_modules
nw.options.files = nw.options.files.concat(requiredDeps);
// remove junk files
nw.options.files = nw.options.files.concat(['!./node_modules/**/*.bin', '!./node_modules/**/*.c', '!./node_modules/**/*.h', '!./node_modules/**/Makefile', '!./node_modules/**/*.h', '!./**/test*/**', '!./**/doc*/**', '!./**/example*/**', '!./**/demo*/**', '!./**/bin/**', '!./**/build/**', '!./**/.*/**']);
return nw.build();
}).catch(function (error) {
console.error(error);
});
});
// create .git.json (used in 'About')
gulp.task('injectgit', () => {
return Promise.all([promiseCallback(git.branch), promiseCallback(git.long)]).then(gitInfo => (
new Promise((resolve, reject) => {
fs.writeFile('.git.json', JSON.stringify({
branch: gitInfo[0],
commit: gitInfo[1]
}), (error) => {
return error ?
reject(error) :
resolve(gitInfo);
});
})
)).then(gitInfo => {
console.log('Branch:', gitInfo[0]);
console.log('Commit:', gitInfo[1].substr(0, 8));
}).catch(error => {
console.log(error);
console.log('Injectgit task failed');
});
});
// compile styl files
gulp.task('css', () => {
const sources = 'src/app/styl/*.styl',
dest = 'src/app/themes/';
return gulp.src(sources)
.pipe(glp.stylus({
use: nib()
}))
.pipe(gulp.dest(dest))
.on('end', () => {
console.log('Stylus files compiled in %s', path.join(process.cwd(), dest));
});
});
// compile nsis installer
gulp.task('nsis', () => {
return Promise.all(nw.options.platforms.map((platform) => {
// nsis is for win only
if (platform.match(/osx|linux/) !== null) {
console.log('No `nsis` task for', platform);
return null;
}
return new Promise((resolve, reject) => {
console.log('Packaging nsis for: %s', platform);
// spawn isn't exec
const makensis = process.platform === 'win32' ? 'makensis.exe' : 'makensis';
const child = spawn(makensis, [
'-DARCH=' + platform,
'-DOUTDIR=' + path.join(process.cwd(), releasesDir),
'dist/windows/installer_makensis.nsi'
]);
// display log only on failed build
const nsisLogs = [];
child.stdout.on('data', (buf) => {
nsisLogs.push(buf.toString());
});
child.on('close', (exitCode) => {
if (!exitCode) {
console.log('%s nsis packaged in', platform, path.join(process.cwd(), releasesDir));
} else {
if (nsisLogs.length) {
console.log(nsisLogs.join('\n'));
}
console.log('%s failed to package nsis', platform);
}
resolve();
});
child.on('error', (error) => {
console.log(error);
console.log(platform + ' failed to package nsis');
resolve();
});
});
})).catch(log);
});
// compile debian packages
// TODO: https://www.npmjs.com/package/nobin-debian-installer
gulp.task('deb', () => {
return Promise.all(nw.options.platforms.map((platform) => {
// deb is for linux only
if (platform.match(/osx|win/) !== null) {
console.log('No `deb` task for:', platform);
return null;
}
if (currentPlatform().indexOf('linux') === -1) {
console.log('Packaging deb is only possible on linux');
return null;
}
return new Promise((resolve, reject) => {
console.log('Packaging deb for: %s', platform);
const child = spawn('bash', [
'dist/linux/deb-maker.sh',
nwVersion,
platform,
pkJson.name,
pkJson.version,
releasesDir
]);
// display log only on failed build
const debLogs = [];
child.stdout.on('data', (buf) => {
debLogs.push(buf.toString());
});
child.stderr.on('data', (buf) => {
debLogs.push(buf.toString());
});
child.on('close', (exitCode) => {
if (!exitCode) {
console.log('%s deb packaged in', platform, path.join(process.cwd(), releasesDir));
} else {
if (debLogs.length) {
console.log(debLogs.join('\n'));
}
console.log('%s failed to package deb', platform);
}
resolve();
});
child.on('error', (error) => {
console.log(error);
console.log('%s failed to package deb', platform);
resolve();
});
});
})).catch(log);
});
// package in tgz (win) or in xz (unix)
gulp.task('compress', () => {
return Promise.all(nw.options.platforms.map((platform) => {
// don't package win, use nsis
if (platform.indexOf('win') !== -1) {
console.log('No `compress` task for:', platform);
return null;
}
return new Promise((resolve, reject) => {
console.log('Packaging tar for: %s', platform);
const sources = path.join('build', pkJson.name, platform);
// compress with gulp on windows
if (currentPlatform().indexOf('win') !== -1) {
return gulp.src(sources + '/**')
.pipe(glp.tar(pkJson.name + '-' + pkJson.version + '_' + platform + '.tar'))
.pipe(glp.gzip())
.pipe(gulp.dest(releasesDir))
.on('end', () => {
console.log('%s tar packaged in %s', platform, path.join(process.cwd(), releasesDir));
resolve();
});
// compress with tar on unix*
} else {
// using the right directory
const platformCwd = platform.indexOf('linux') !== -1 ? '.' : pkJson.name + '.app';
// list of commands
const commands = [
'cd ' + sources,
'tar --exclude-vcs -c ' + platformCwd + ' | $(command -v pxz || command -v xz) -T8 -7 > "' + path.join(process.cwd(), releasesDir, pkJson.name + '-' + pkJson.version + '_' + platform + '.tar.xz') + '"',
'echo "' + platform + ' tar packaged in ' + path.join(process.cwd(), releasesDir) + '" || echo "' + platform + ' failed to package tar"'
].join(' && ');
exec(commands, (error, stdout, stderr) => {
if (error || stderr) {
console.log(error || stderr);
console.log('%s failed to package tar', platform);
resolve();
} else {
console.log(stdout.replace('\n', ''));
resolve();
}
});
}
});
})).catch(log);
});
// prevent commiting if conditions aren't met and force beautify (bypass with `git commit -n`)
// gulp.task('pre-commit', ['jshint']);
gulp.task('pre-commit', () => {
console.log('Dissabled jshint for now.');
});
// check entire sources for potential coding issues (tweak in .jshintrc)
gulp.task('jshint', () => {
return gulp.src(['gulpfile.js', 'src/app/lib/*.js', 'src/app/lib/**/*.js', 'src/app/vendor/videojshooks.js', 'src/app/vendor/videojsplugins.js', 'src/app/*.js'])
.pipe(glp.jshint('.jshintrc'))
.pipe(glp.jshint.reporter('jshint-stylish'))
.pipe(glp.jshint.reporter('fail'));
});
// beautify entire code (tweak in .jsbeautifyrc)
gulp.task('jsbeautifier', () => {
return gulp.src(['src/app/lib/*.js', 'src/app/lib/**/*.js', 'src/app/*.js', 'src/app/vendor/videojshooks.js', 'src/app/vendor/videojsplugins.js', '*.js', '*.json'], {
base: './'
})
.pipe(glp.jsbeautifier({
config: '.jsbeautifyrc'
}))
.pipe(glp.jsbeautifier.reporter())
.pipe(gulp.dest('./'));
});
// clean build files (nwjs)
gulp.task('clean:build',
deleteAndLog([path.join(releasesDir, pkJson.name)], 'build files')
);
// clean dist files (dist)
gulp.task('clean:dist',
deleteAndLog([path.join(releasesDir, '*.*')], 'distribuables')
);
// clean compiled css
gulp.task('clean:css',
deleteAndLog(['src/app/themes'], 'css files')
);
// travis tests
gulp.task('test', (callback) => {
runSequence('jshint', 'injectgit', 'css', callback);
});
//TODO:
//setexecutable?
//bower_clean
//TODO: test and tweak
/*gulp.task('codesign', () => {
exec('sh dist/mac/codesign.sh || echo "Codesign failed, likely caused by not being run on mac, continuing"', (error, stdout, stderr) => {
console.log(stdout);
});
});
gulp.task('createDmg', () => {
exec('dist/mac/yoursway-create-dmg/create-dmg --volname "' + pkJson.name + '-' + pkJson.version + '" --background ./dist/mac/background.png --window-size 480 540 --icon-size 128 --app-drop-link 240 370 --icon "' + pkJson.name + '" 240 110 ./build/releases/' + pkJson.name + '/mac/' + pkJson.name + '-' + pkJson.version + '-Mac.dmg ./build/releases/' + pkJson.name + '/mac/ || echo "Create dmg failed, likely caused by not being run on mac, continuing"', (error, stdout, stderr) => {
console.log(stdout);
});
});*/