-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
96 lines (84 loc) · 2.82 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
/*
* gulp-confirm
* https://github.com/anseki/gulp-confirm
*
* Copyright (c) 2018 anseki
* Licensed under the MIT license.
*/
'use strict';
var PluginError = require('plugin-error'),
log = require('fancy-log'),
through = require('through2'),
readlineSync = require('readline-sync'),
RE_CTRL_CHAR = /\x1B\[\d+m/,
HL_IN = '\x1B[1m', HL_OUT = '\x1B[22m';
// Wrap handler
function callHandler(handler, argsArray) {
try {
return {val: handler.apply(null, argsArray)};
} catch (e) {
return {err: e};
}
}
function hl(text) {
return !(text += '') || RE_CTRL_CHAR.test(text) ? text : HL_IN + text + HL_OUT;
}
function Confirm(options) {
var that = this;
that.options = options;
that.stream = through.obj(function() { that.transform.apply(that, arguments); });
}
Confirm.prototype.transform = function(file, encoding, callback) {
var options = this.options, query, matches,
res, rlsMethod, rlsOptions = {history: false};
if (typeof this.proceed !== 'boolean') {
if (typeof options.question === 'function') {
res = callHandler(options.question);
if (res.err) {
console.error('"question" failed.');
return callback(new PluginError('gulp-confirm', res.err));
}
if (!res.val) {
this.proceed = true;
callback(null, file); // Do nothing.
return;
}
query = res.val;
} else {
query = options.question ?
options.question + ' :' : options.question; // accept ''
}
if ((matches = /^\s*_key(?:\:(.+))?\s*$/i.exec(options.input + ''))) {
rlsMethod = 'keyIn';
if (matches[1]) { rlsOptions.trueValue = matches[1]; }
else if (typeof options.proceed !== 'function' &&
typeof options.proceed !== 'boolean') { rlsMethod = 'keyInPause'; }
} else {
rlsMethod = 'question';
if (options.input) { rlsOptions.trueValue = (options.input + '').split(','); }
}
if (process.platform === 'win32' && process.stdin.isTTY) {
// init force
try {
require('fs').writeSync(process.stdin.fd, ''); // not stdout
} catch (e) {}
}
res = readlineSync[rlsMethod](query && process.platform !== 'win32' ?
hl(query) : query, rlsOptions); // accept undefined
if (rlsOptions.trueValue) {
this.proceed = res === true;
} else if (typeof options.proceed === 'function') {
res = callHandler(options.proceed, [res]);
if (res.err) {
console.error('"proceed" failed.');
return callback(new PluginError('gulp-confirm', res.err));
}
this.proceed = !!res.val;
} else {
this.proceed = typeof options.proceed === 'boolean' ? options.proceed : true;
}
if (!this.proceed) { log(hl('Tasks are aborted.')); }
}
callback(null, this.proceed ? file : null);
};
module.exports = function(options) { return (new Confirm(options)).stream; };