forked from zhaoky/flqin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkit.js
632 lines (508 loc) · 14.3 KB
/
kit.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
"use strict";
const
gulp = require("gulp");
const oKit = {
BASE_VERSION: "6.7.0"
};
let _iAliasFactory = initAliasFactory();
const kit = {
checkVersion: checkVersion,
checkNodeVer: checkNodeVer,
checkNpm: checkNpm,
loadConfig: loadConfigFactory(),
loadCampusConfig: loadCampusConfig,
getCliArgs: getCliArgsFactory(),
isProduction: isProduction,
getSrcFilter: getSrcFilter,
renamePath: renamePath,
getAlias: _iAliasFactory.getAlias,
setAlias: _iAliasFactory.setAlias,
log: log,
wLog: wLogFactory(),
getErrors: getErrors,
getUglifyConfig: getUglifyConfig,
getHtmlConfig: getHtmlConfig,
getCssConfig: getCssConfig,
getPreProcessConfig: getPreProcessConfig,
getWatcherConfig: getWatcherConfig,
isCordovaDir: isCordovaDir,
task: task,
taskBuildApp: taskBuildApp,
getDestPath: getDestPathFactory()
};
/**
* 读取 构建平台模式
*/
function _loadConfig() {
const
campusAlias = kit.getAlias(),
onfRawDefault = require("../default_config");
var
onfCampus,
config;
log(`[CAMPUS_ALIAS]: ${campusAlias}`);
config = onfRawDefault.defaultConfig;
onfCampus = loadCampusConfig();
// 校园自定数据 写入 配置数据
assignDeep(config, onfCampus);
config.build.isProduction = isProduction();
config.project.version = config.project.version || gulp.pkg.version;
config.project.alias = campusAlias;
return config;
}
function loadConfigFactory() {
var config;
return (isForce) => {
config = config && !isForce ? config : _loadConfig();
return config;
}
}
/**
* 加载 校园配置
* @returns {*}
*/
function loadCampusConfig() {
var
campusAlias = kit.getAlias();
try {
return require(`../campus_config/${campusAlias}_config`);
} catch (e) {
return {};
}
}
/**
* 获取 getter/setter run-time-building 校园别名
* @returns {*}
*/
function initAliasFactory() {
var _alias;
return {
setAlias: (alias) => {
_alias = alias;
},
getAlias: () => {
if (!_alias) {
_alias = kit.getCliArgs()["alias"] || require("../default_config")["defaultConfig"]["project"]["alias"];
}
return _alias
}
}
}
/**
* 获取 "命令行" 参数
* @returns {() => }
*/
function getCliArgsFactory() {
var
minimist = require("minimist"),
cliAgr;
return (isFore) => {
if (!cliAgr && !isFore) {
cliAgr = cliAgr || minimist(process.argv.slice(2), {
default: {}
});
delete cliAgr._;
}
return cliAgr;
};
}
/**
* 检测 Node 版本
* @returns { Boolean } 是否为稳定版
*/
function checkNodeVer() {
var
shell = require("shelljs"),
baseVersion,
curVersion,
isNodeAvailable,
isNodeLessVer;
if (!shell.which("node")) {
shell.echo("Require Node Environment.");
shell.echo("Please install by: http://nodejs.org");
shell.exit();
}
baseVersion = oKit.BASE_VERSION;
curVersion = shell.exec("node -v", {
silent: true
}).stdout;
isNodeAvailable = checkVersion(curVersion, baseVersion).eq;
isNodeLessVer = checkVersion(curVersion, baseVersion).lt;
if (!isNodeAvailable) {
let error = isNodeLessVer ?
`Your Node Version Is Out Of Date! \nPlease Install V${baseVersion} Node On: http://nodejs.org` :
`Your Node Version Is Too High \nFor Stable,Please Install V${baseVersion} Node On: http://nodejs.org`;
getErrors(error);
}
return isNodeAvailable;
}
/**
* 错误提示
* @param { String } error 错误提示语
*/
function getErrors(error) {
const shell = require("shelljs");
shell.echo(" ");
shell.echo("### Caution: ###");
shell.echo("");
shell.echo(error);
shell.echo("");
}
/**
* 检测版本号
* @param { String } curVersion 当前版本号
* @param { String } baseVersion 基准版本号
* @returns { Object } onf 是否通过验证
* @returns { Boolean } onf.eq 是否相等
* @returns { Boolean } onf.lt 是否小于
* @returns { Boolean } onf.gt 是否大于
*/
function checkVersion(curVersion, baseVersion) {
const
curVer = transVersion(curVersion),
baseVer = transVersion(baseVersion);
let
equal = true,
lessThan = undefined;
equal = curVer.reduce((lastVal, cur, index) => {
if (!lastVal) { return false }
let isEqual = Number(cur) === Number(baseVer[index] || 0);
if (!isEqual) {
lessThan = Number(cur) < Number(baseVer[index]);
}
return isEqual;
}, equal);
return {
eq: equal,
lt: lessThan,
gt: !lessThan
};
}
/**
* 将版本号转换为数组以便于比较
* @param { String } version 版本号
* @returns { Array } 转换后的版本号
*/
function transVersion(version) {
return version.match(/([\d\.]+)/g)[0].split(".");
}
/**
* 检测 npm package 是否安装正确
* @returns { Boolean } 是否通过验证
*/
function checkNpm() {
const
dependenvies = gulp.pkg.devDependencies,
plugins = Object.keys(dependenvies),
shell = require("shelljs"),
promise = [];
let
isPassed = true,
isNotFind = false;
for (let plugin of plugins) {
const baseVersion = dependenvies[plugin];
let sInstallTips = `Can Not Find node_module: [${plugin}] \nPlease Install At First:\n` +
`\n` +
` npm install ${plugin}` +
`\n`;
try {
require(plugin);
promise.push(checkNpmVer(plugin, baseVersion)
.then((value) => value)
.catch((msg) => {
let error;
isPassed = false;
switch (msg) {
case "notFind":
isNotFind = true;
error = sInstallTips;
break;
case "<":
error = `Your [${plugin}] version is out of date! \nPlease Install V${baseVersion.match(/([\d\.]+)/g)[0]}!`;
break;
case ">":
error = `Your [${plugin}] version is too High, \nFor Stable,Please Install V${baseVersion.match(/([\d\.]+)/g)[0]}!`;
}
getErrors(error);
}));
} catch (err) {
isPassed = false;
isNotFind = true;
let error = sInstallTips;
getErrors(error);
}
}
isNotFind && shell.exit(1);
Promise.all(promise)
.then(() => {
isNotFind && shell.exit(1);
return isPassed;
});
}
/**
* 检测 npm 版本
* @returns { Promise }
*/
function checkNpmVer(plugin, baseVersion) {
const fs = require("fs");
return new Promise((resolve, reject) => {
fs.readFile(`./node_modules/${plugin}/package.json`, "utf-8", (err, data) => {
if (err) {
reject("notFind");
return;
}
let
isEqual,
isLessThan,
curVersion = JSON.parse(data).version;
isEqual = checkVersion(curVersion, baseVersion).eq;
isLessThan = checkVersion(curVersion, baseVersion).lt;
if (!isEqual) {
let msg = isLessThan ? "<" : ">";
reject(msg);
}
resolve(true);
});
});
}
/**
* 是否为 "产品级" 构建模式
* @returns {boolean}
*/
function isProduction() {
var cliArgs = kit.getCliArgs();
return !!(cliArgs.p || true === cliArgs.production);
}
/**
* print something
*/
function log() {
var arrLog = Array.prototype.slice.call(arguments);
arrLog.unshift("-----");
console.log.apply(console, arrLog);
}
/**
* Log for Gulp Watch
* @param taskName
* @param event
*/
function wLogFactory() {
const
path = require("path");
return (taskName, event) => {
let rawPath = event.path.split(path.sep);
kit.log(rawPath.slice(-3).join(path.sep) + ` was changed by ${event.type}, running task: [${taskName}]`);
}
}
/**
* 获取 Uglify 默认配置
* @param { Object } [onf]
* @returns { Object }
*/
function getUglifyConfig(onf) {
return assignDeep({
mangle: true,
compress: {
sequences: true, // join consecutive statemets with the “comma operator”
properties: true, // optimize property access: a["foo"] → a.foo
dead_code: true, // discard unreachable code
drop_debugger: true, // discard “debugger” statements
unsafe: false, // some unsafe optimizations (see below)
conditionals: true, // optimize if-s and conditional expressions
comparisons: true, // optimize comparisons
evaluate: true, // evaluate constant expressions
booleans: true, // optimize boolean expressions
loops: true, // optimize loops
unused: true, // drop unused variables/functions
hoist_funs: true, // hoist function declarations
hoist_vars: false, // hoist variable declarations
if_return: true, // optimize if-s followed by return/continue
join_vars: true, // join declarations
cascade: true, // try to cascade `right` into `left` in sequences
side_effects: true, // drop side-effect-free statements
drop_console: false, // drop console
warnings: false // warn about potentially dangerous optimizations/code
}
}, onf);
}
/**
* 获取 html-min 默认配置
* @param { Object } [onf]
* @returns { Object }
*/
function getHtmlConfig(onf) {
return Object.assign({
collapseWhitespace: true,
conservativeCollapse: true,
preserveLineBreaks: true,
minifyJS: true,
minifyCSS: true
}, onf);
}
/**
* 获取 process css 默认配置
* @param { Object } [onf]
* @returns { Object }
*/
function getCssConfig(onf) {
return Object.assign({
advanced: false
}, onf);
}
/**
* 获取 preProcess 默认配置
*
* @param { Object } [data]
* @param { Object } [data.build]
* @param { Object } [data.project]
* @param { Object } [data.cordova]
* @param { Object } [data.h5]
*
* @param { Object } [onf]
* @param { Object } [onf.isForce] 是否重新获取 配置数据
* @returns { Object }
*/
function getPreProcessConfig(data, onf) {
var config;
data = data || {};
onf = onf || {};
/**
* @type { Object } onf
* @type { Object } onf.build
* @type { Object } onf.project
* @type { Object } onf.cordova
* @type { Object } onf.h5
*/
config = assignDeep({}, kit.loadConfig(onf.isForce));
assignDeep(config, data);
return {
context: config
};
}
/**
* 获取 gulp-watch 默认配置
* @returns {{interval: number, debounceDelay: number, mode: string}}
*/
function getWatcherConfig(onf) {
// docs: https://github.com/shama/gaze
return Object.assign({
interval: 800,
debounceDelay: 200,
// "auto", "watch", "poll"
mode: "auto"
}, onf);
}
/**
* 获取 src 路径
* @param { Array | String } path
*/
function getSrcFilter(path) {
var
arrPath = [],
alias = kit.getAlias();
if ("[object Array]" === Object.prototype.toString.call(path)) {
arrPath.push.apply(arrPath, path);
} else {
arrPath.push(path);
}
arrPath.push(`!**/_$!(${alias})_*/*`, `!**/_$!(${alias})_*/`);
return arrPath;
}
/**
* 获取 { Object } path
* @param path
*/
function renamePath(path) {
var reg = /(_\$[^_]+_)/;
path.basename = path.basename.replace(reg, "$");
path.dirname = path.dirname.replace(reg, "$");
return path;
}
/**
* Deep Mode For Object.assign
* @param target
* @param source
* @returns {*}
*/
function assignDeep(target, source) {
for (let prop in source) {
let isDeepAssign;
if (!source.hasOwnProperty(prop)) { continue }
isDeepAssign = isObject(source[prop]);
if (isDeepAssign) {
target[prop] = isObject(target[prop]) ?
target[prop] : {};
}
target[prop] = isDeepAssign ?
assignDeep(target[prop], source[prop]) :
"" === source[prop] ?
target[prop] :
source[prop];
}
return target;
}
const toString = Object.prototype.toString;
function isObject(target) {
return "[object Object]" === toString.call(target);
}
/**
* 检测当前是否在 Cordova 目录
* @returns {boolean}
*/
function isCordovaDir() {
const
shell = require("shelljs"),
path = require("path"),
currentPath = shell.pwd();
let _raw;
_raw = currentPath.split(path.sep).join("*");
return -1 !== _raw.lastIndexOf("*" + gulp.config.build + "*app");
}
/**
* @deprecated
* @param { String } taskCliAli
* @param { String } taskName
* @param { Array } [dependTask]
* @param { Function } taskFn
*/
function task(taskCliAli, taskName, dependTask, taskFn) {
const
dargs = require("dargs");
var isRunningFlag = `_isTask${taskName}`;
if ("function" === typeof dependTask) {
taskFn = dependTask;
dependTask = [];
}
gulp.task(taskName, dependTask, (cb) => {
if (kit.getCliArgs()["isRunningFlag"]) {
return taskFn.call(this, cb);
} else {
let
arrDrags;
arrDrags = dargs(kit.getCliArgs(), { useEquals: false });
arrDrags.push(`--${isRunningFlag}`);
taskCliAli += " " + arrDrags.join(" ");
console.log(taskCliAli);
require("shelljs").exec(`gulp ${taskName} ${taskCliAli}`);
}
});
}
/**
* @deprecated
* @param { String } taskName
* @param { Array } [dependTask]
* @param { Function } taskFn
*/
function taskBuildApp(taskName, dependTask, taskFn) {
return task.call(this, "--mode app", taskName, dependTask, taskFn);
}
function getDestPathFactory() {
var path;
return (isForce) => {
return path = isForce ? getDestPath() : path || getDestPath();
}
}
function getDestPath() {
return gulp.config.build["dest"];
}
module.exports = kit;