-
-
Notifications
You must be signed in to change notification settings - Fork 571
/
pipe.js
468 lines (468 loc) · 18.9 KB
/
pipe.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
/**@license
* __ _____ ________ __
* / // _ /__ __ _____ ___ __ _/__ ___/__ ___ ______ __ __ __ ___ / /
* __ / // // // // // _ // _// // / / // _ // _// // // \/ // _ \/ /
* / / // // // // // ___// / / // / / // ___// / / / / // // /\ // // / /__
* \___//____ \\___//____//_/ _\_ / /_//____//_/ /_/ /_//_//_/ /_/ \__\_\___/
* \/ /____/
* http://terminal.jcubic.pl
*
* This is object enchancment that will add pipe operator and redirects to commands
*
* Copyright (c) 2014-2021 Jakub Jankiewicz <https://jcubic.pl/me>
* Released under the MIT license
*
*/
/* global define */
(function(factory) {
var root;
if (typeof window !== 'undefined') {
root = window;
} else if (typeof self !== 'undefined') {
root = self;
} else if (typeof global !== 'undefined') {
root = global;
} else {
throw new Error('Unknow context');
}
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
// istanbul ignore next
define(['jquery', 'jquery.terminal'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = function(root, jQuery) {
if (jQuery === undefined) {
// require('jQuery') returns a factory that requires window to
// build a jQuery instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined (how jquery works)
if (typeof window !== 'undefined') {
jQuery = require('jquery');
} else {
jQuery = require('jquery')(root);
}
}
if (!jQuery.fn.terminal) {
if (typeof window !== 'undefined') {
require('jquery.terminal');
} else {
require('jquery.terminal')(jQuery);
}
}
factory(jQuery);
return jQuery;
};
} else {
// Browser
// istanbul ignore next
factory(root.jQuery);
}
})(function($) {
// -----------------------------------------------------------------------------------
// :: split over array - returns array of arrays
// -----------------------------------------------------------------------------------
function array_split(array, splitter) {
var test_fn;
if (typeof splitter === 'function') {
test_fn = splitter;
} else if (splitter instanceof RegExp) {
test_fn = function(item) {
if (item instanceof RegExp) {
item = item.source;
} else if (typeof item !== 'string') {
item = item.toString();
}
var m = item.match(splitter);
if (m) {
if (m.length > 1) {
return m.slice(1);
}
return true;
}
};
} else {
test_fn = function(item) {
return splitter === item;
};
}
var output = [];
var sub = [];
array.forEach(function(item, i) {
var check = test_fn(item, i);
if (check) {
output.push(sub);
sub = [];
if (check instanceof Array) {
output.push(check);
}
} else {
sub.push(item);
}
});
output.push(sub);
return output;
}
// -----------------------------------------------------------------------------------
function is_function(obj) {
return typeof obj === 'function';
}
// -----------------------------------------------------------------------------------
$.terminal.defaults.strings.pipeNestedInterpreterError = 'You can\'t pipe nested ' +
'interpreter';
// -----------------------------------------------------------------------------------
$.terminal.pipe = function pipe(interpreter, options) {
var settings = $.extend({
processArguments: true,
overwrite: undefined,
redirects: {}
}, options);
var overwrite_buffer;
var term;
var orig;
var command_index;
var process_redirect = false;
// -------------------------------------------------------------------------------
function parse_redirect(args, re) {
var redirects = [];
if (args.length) {
var cmd_redirect, settings_redirect;
for (var i = 0; i < args.length; ++i) {
var operator = null;
if (args[i].length === 1 && args[i][0].match(re)) {
operator = args[i][0];
}
if (operator) {
for (var j = settings.redirects.length; j--;) {
if (operator === settings.redirects[j].name) {
settings_redirect = settings.redirects[j];
break;
}
}
cmd_redirect = {
fn: settings_redirect.callback,
args: []
};
redirects.push(cmd_redirect);
} else {
cmd_redirect.args = args[i];
}
}
}
return redirects;
}
// -------------------------------------------------------------------------------
function is_pipe(cmd) {
var quotes = [''].concat(cmd.args_quotes);
return function(string, i) {
return string === '|' && !quotes[i];
};
}
// -------------------------------------------------------------------------------
function tokens(cmd) {
return [cmd.name].concat(cmd.args);
}
// -------------------------------------------------------------------------------
function parse_command(command) {
var cmd;
if (term.settings().processArguments) {
cmd = $.terminal.parse_command(command);
} else {
cmd = $.terminal.split_command(command);
}
var index = 1;
return array_split(tokens(cmd), is_pipe(cmd)).map(function(args, i) {
var result = {
redirects: []
};
var len = args.length;
if (settings.redirects.length) {
var redirect_names = settings.redirects.map(function(redirect) {
return $.terminal.escape_regex(redirect.name);
});
var re = new RegExp('^(' + redirect_names.join('|') + ')$');
var split_args = array_split(args, re);
if (split_args.length > 1) {
args = split_args[0];
result.redirects = parse_redirect(split_args.slice(1), re);
}
}
if (i === 0) {
result.args_quotes = args.map(function(_, i) {
return cmd.args_quotes[i];
});
} else {
result.args_quotes = args.map(function(_, i) {
return cmd.args_quotes[i + index];
}).slice(1);
}
index += len;
result.name = args[0];
result.args = args.slice(1);
return result;
});
}
// -------------------------------------------------------------------------------
function overwrite(command) {
return command.overwrite === true ||
typeof command.overwrite === 'undefined' ||
settings.overwrite === true;
}
// -------------------------------------------------------------------------------
function redirects(command) {
var defer = $.Deferred();
if (overwrite(command)) {
overwrite_buffer = true;
}
function resolve() {
overwrite_buffer = false;
defer.resolve();
}
if (command.redirects.length) {
var i = 0;
(function loop() {
var redirect = command.redirects[i++];
if (redirect) {
var fn = redirect.fn;
var args = redirect.args;
continuation(fn.apply(term, args), function(value) {
echo_non_empty(value);
loop();
}, 'redirect loop');
} else {
resolve();
}
})();
} else {
resolve();
}
return defer.promise();
}
// -------------------------------------------------------------------------------
function continuation(promise, callback) {
if (promise && promise.then) {
promise.then(callback);
return promise;
} else {
callback();
}
}
// -------------------------------------------------------------------------------
function echo_non_empty(value) {
if (typeof value !== 'undefined') {
term.echo(value);
}
}
// -------------------------------------------------------------------------------
function single_command(commands) {
return commands.length === 1 && !commands[0].redirects.length;
}
// -------------------------------------------------------------------------------
function make_tty() {
var tty = {
read: function(message, callback) {
// in case we return read() call from interpreter
// we can't access force_awake flag in term (it's invoked later)
if (term.paused()) {
term.resume();
}
if ((command_index === 0 && !tty.buffer) || process_redirect) {
term.push = orig.push;
term.echo = orig.echo;
var ret = orig.read.apply(term, arguments);
return ret.then(function(value) {
term.push = tty.push;
term.echo = tty.echo;
return value;
});
} else {
var text;
if (tty.buffer) {
text = tty.buffer.replace(/\n$/, '');
delete tty.buffer;
}
var d = new $.Deferred();
if (is_function(callback)) {
callback(text);
}
d.resolve(text);
return d.promise();
}
},
echo: function(string, options) {
if (overwrite_buffer) {
overwrite_buffer = false;
tty.buffer = '';
}
tty.options = tty.options || [];
tty.options.push(options);
tty.buffer = (tty.buffer || '') + string + '\n';
},
push: function() {
this.error(strings(this).pipeNestedInterpreterError);
}
};
return tty;
}
// -------------------------------------------------------------------------------
function strings(term) {
var term_settings = term.settings();
return $.extend(
{},
$.terminal.defaults.strings,
term_settings && term_settings.strings || {}
);
}
// -------------------------------------------------------------------------------
function error(message) {
var echo = term.echo;
term.echo = orig.echo;
term.error(message);
term.echo = echo;
}
// -------------------------------------------------------------------------------
function unparse(string) {
if (term.settings().processArguments) {
return string.replace(/(['"()])/g, '\\$1');
} else {
return string.replace(/ /g, '\\ ');
}
}
// -------------------------------------------------------------------------------
function stringify(cmd) {
return cmd.name + ' ' + cmd.args.map(function(arg, i) {
if (cmd.args_quotes[i]) {
var quote = cmd.args_quotes[i];
return quote + unparse(arg) + quote;
}
return arg.replace(/ /g, '\\ ');
}).join(' ');
}
// -------------------------------------------------------------------------------
return function(command, t) {
command_index = -1;
term = t; // for echo_non_empty and function that call it
var term_settings = term.settings();
if (!orig) {
orig = {
echo: term.echo,
read: term.read,
push: term.push
};
}
var tty = make_tty();
var commands = parse_command(command);
function loop(callback) {
var i = 0;
var d = new $.Deferred();
return (function inner() {
var cmd = commands[i++];
if (cmd) {
process_redirect = true;
redirects(cmd).then(function() {
process_redirect = false;
if (!commands[i]) {
$.extend(term, {echo: orig.echo, push: orig.push});
}
command_index++;
var ret = callback(cmd);
if (ret === false) {
return inner();
} else {
return continuation(ret, inner, 'inner');
}
});
} else {
d.resolve();
}
return d.promise();
})();
}
if (single_command(commands)) {
var cmd = commands[0];
if (is_function(interpreter)) {
return interpreter.call(term, stringify(cmd), term);
} else if (is_function(interpreter[cmd.name])) {
return interpreter[cmd.name].apply(term, cmd.args);
} else if ($.isPlainObject(interpreter[cmd.name])) {
term.push(interpreter[cmd.name], {
prompt: cmd.name + '> ',
name: cmd.name,
completion: Object.keys(interpreter[cmd.name])
});
} else if (is_function(term_settings.onCommandNotFound)) {
term_settings.onCommandNotFound.call(term, command, term);
} else {
error(sprintf(strings(term).commandNotFound, cmd.name));
}
} else {
//term = term.duplicate();
$.extend(term, tty);
var stop_error = false;
var promise = loop(function(cmd) {
var ret;
if (is_function(interpreter)) {
// this branch will be always invoked with new API
// using pipe option
var str = stringify(cmd);
// this resume and exec is needed for rpc
// because it use pause/resume and not promises
// TODO: refactor RPC in terminal
term.resume();
ret = term.exec(str, true);
return continuation(ret, echo_non_empty);
} else {
var inter = interpreter[cmd.name];
if (is_function(inter)) {
ret = inter.apply(term, cmd.args);
return continuation(ret, echo_non_empty);
} else {
if ($.isPlainObject(inter)) {
error(strings(term).pipeNestedInterpreterError);
} else if (is_function(term_settings.onCommandNotFound)) {
if (!stop_error) {
term_settings.onCommandNotFound.call(
term,
command,
term
);
stop_error = true;
}
} else {
error(sprintf(strings(term).commandNotFound, cmd.name));
}
return false;
}
}
});
return promise.then(function() {
$.extend(term, orig);
});
}
};
};
// -------------------------------------------------------------------------
var init = $.fn.terminal;
$.fn.terminal = function(interpreter, options) {
if (options && options.pipe) {
var settings = $.extend({}, options, {
onInit: function() {
var defer = $.Deferred();
if (options && options.pipe) {
var interpreter = $.terminal.pipe(this.commands(), options);
this.set_interpreter(interpreter).then(defer.resolve);
} else {
defer.resolve();
}
if (options && is_function(options.onInit)) {
var self = this;
defer.then(function() {
options.onInit.call(self, self);
});
}
}
});
}
return init.call(this, interpreter, settings || options);
};
});