-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathterminal.js
More file actions
371 lines (363 loc) · 13 KB
/
terminal.js
File metadata and controls
371 lines (363 loc) · 13 KB
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
BrowserFS.configure({ fs: "IndexedDB", options: {} }, function (err) {
window.fs = BrowserFS.BFSRequire("fs");
window.path = BrowserFS.BFSRequire("path");
// --------------------------------------------------------------
function list(path) {
term.pause();
return listDir(path).then((list) => (term.resume(), list));
}
// --------------------------------------------------------------
function get_path(string) {
var path = cwd.replace(/^\//, '').split('/');
if (path[0] === '') {
path = path.slice(1);
}
var parts = string === '/'
? string.split('/')
: string.replace(/\/?[^\/]*$/, '').split('/');
if (parts[0] === '') {
parts = parts.slice(1);
}
if (string === '/') {
return [];
} else if (string.startsWith('/')) {
return parts;
} else if (path.length) {
return path.concat(parts);
} else {
return parts;
}
}
// --------------------------------------------------------------
function read(cmd, cb) {
var filename = typeof cmd === 'string' ? cmd : cmd.args.length == 1 ? cwd + '/' + cmd.args[0] : null;
if (filename) {
term.pause();
fs.readFile(filename, function(err, data) {
if (err) {
term.error(err.message);
} else {
cb(data.toString());
}
term.resume();
});
} else {
term.error('No filename');
}
}
window.resolve = function resolve(path) {
if (path[0] === '/') {
return path;
} else {
return window.path.resolve(window.path.join(cwd, path));
}
}
// --------------------------------------------------------------
function mkdir(path) {
path = resolve(path);
return new Promise((resolve, reject) => {
fs.stat(path, (err, stat) => {
if (err) {
fs.mkdir(path, function(err) {
if (err) {
reject(err.message);
} else {
resolve();
}
});
} else if (stat.isFile()) {
reject(`${path} is file`);
} else {
resolve();
}
});
});
}
// --------------------------------------------------------------
window.cwd = '/';
var commands = {
help: function(cmd) {
term.echo(`Available commands: ${Object.keys(commands).join(', ')}`);
},
mkdir: function(cmd) {
term.pause();
mkdir(cmd.args[0]).then(term.resume);
},
cd: function(cmd) {
if (cmd.args.length === 1) {
var dirname = path.resolve(cwd + '/' + cmd.args[0]);
term.pause();
fs.stat(dirname, (err, stat) => {
if (err) {
term.error("Directory don't exits").resume();
} else if (stat.isFile()) {
term.error(`"${dirname}" is not directory`).resume();
} else {
cwd = dirname == '/' ? dirname : dirname.replace(/\/$/, '');
term.resume();
}
});
}
},
cat: function(cmd) {
read(cmd, (x) => term.echo(x, {newline: false}));
},
less: function(cmd) {
read(cmd, term.less.bind(term));
},
ls: function(cmd) {
var {options, args} = split_args(cmd.args);
function filter(list) {
if (options.match(/a/)) {
return list;
} else if (options.match(/A/)) {
return list.filter(name => !name.match(/^\.{1,2}$/));
} else {
return list.filter(name => !name.match(/^\./));
}
}
list(cwd + '/' + (args[0] || '')).then((content) => {
var dirs = filter(['.', '..'].concat(content.dirs)).map((dir) => color('blue', dir));
var output = dirs.concat(filter(content.files));
if (output.length) {
term.echo(output.join('\n'));
}
});
},
rm: function(cmd) {
var {options, args} = split_args(cmd.args);
var len = args.length;
if (len) {
term.pause();
}
args.forEach(arg => {
var path_name = path.resolve(cwd + '/' + arg);
fs.stat(path_name, (err, stat) => {
if (err) {
term.error(err);
} else if (stat) {
if (stat.isDirectory()) {
if (options.match(/r/)) {
rmDir(path_name);
} else {
term.error(`${path_name} is directory`);
}
} else if (stat.isFile()) {
fs.unlink(path_name);
} else {
term.error(`${path_name} is invalid`)
}
if (!--len) {
term.resume();
}
}
});
});
},
credits: function() {
this.echo(`
[[!;;;;https://github.com/jcubic/jsvi]JSVI]
Copyright (C) 2006-2008 Internet Connection, Inc.
Copyright (C) 2013-2018 Jakub T. Jankiewicz
[[!;;;;https://terminal.jcubic.pl]jQuery Terminal]
Copyright (C) 2011-2021 Jakub T. Jankiewicz
[[!;;;;https://github.com/timoxley/wcwidth]wcwidth]
Copyright (c) 2012 by Jun Woong
[[!;;;;https://prismjs.com/]PrismJS]
Copyright (c) 2012 Lea Verou
[[!;;;;https://github.com/inexorabletash/polyfill]Keyboard Polyfill]
Copyright (c) 2018 Joshua Bell
[[!;;;;https://github.com/jvilk/BrowserFS]BrowserFS]
Copyright (c) 2013, 2014, 2015, 2016, 2017 John Vilk and other BrowserFS contributors.
`)
},
vi: function(cmd) {
var textarea = $('.vi');
var editor;
var fname = cmd.args[0];
term.focus(false);
if (fname) {
var path = resolve(fname);
function open(file) {
// we need to replace < and & because jsvi is handling html tags
// and don't work properly for raw text
textarea.val(file.replace(/</g, '<').replace(/&/g, '&'));
editor = window.editor = vi(textarea[0], {
color: '#ccc',
backgroundColor: '#000',
onSave: function() {
var file = textarea.val().replace(/&/g, '&').replace(/</g, '<');
fs.writeFile(path, file, function(err, wr) {
if (err) {
term.error(err.message);
}
});
},
onExit: term.focus
});
}
fs.stat(path, (err, stat) => {
if (stat && stat.isFile()) {
read(cmd, open, true);
} else {
var dir = path.replace(/[^\/]+$/, '');
fs.stat(dir, (err, stat) => {
if (stat && stat.isDirectory()) {
open('')
} else if (err) {
term.error(err.message);
} else {
term.error(`${dir} directory don't exists`);
}
});
}
});
}
}
};
// --------------------------------------------------------------
var term = $('.term').terminal((command) => {
var cmd = $.terminal.parse_command(command);
if (commands[cmd.name]) {
commands[cmd.name].call(term, cmd);
} else {
term.error('Command not found');
}
}, {
checkArity: false,
greetings: 'Fake Linux Terminal (see also the [[!;;;;https://fake.terminal.jcubic.pl/]new version])\n[[;white;]TIP]: Use [[;white;]vi] to create files and [[;white;]mkdir] to create directories\n',
prompt: function() {
return [
color('green', 'user@example.com'),
':',
color('blue', cwd),
'$ '
].join('');
},
completion: function(string, cb) {
var cmd = $.terminal.parse_command(this.before_cursor());
function processAssets(callback) {
var dir = get_path(string);
list('/' + dir.join('/')).then(callback);
}
function prepend(list) {
if (string.match(/\//)) {
var path = string.replace(/\/[^\/]+$/, '').replace(/\/+$/, '');
return list.map((dir) => path + '/' + dir);
} else {
return list;
}
}
function trailing(list) {
return list.map((dir) => dir + '/');
}
if (cmd.name !== string) {
switch (cmd.name) {
// complete file and directories
case 'cat':
case 'vi':
case 'less':
return processAssets(content => cb(prepend(trailing(content.dirs).concat(content.files))));
// complete directories
case 'ls':
case 'cd':
return processAssets(content => cb(prepend(trailing(content.dirs))));
}
}
cb(Object.keys(commands));
}
});
});
// -------------------------------------------------------------------
function color(name, string) {
var colors = {
blue: '#55f',
green: '#4d4',
grey: '#999',
red: '#A00',
yellow: '#FF5',
violet: '#a320ce',
white: '#fff'
}
if (colors[name]) {
return '[[;' + colors[name] + ';]' + string + ']';
} else {
return string;
}
}
// -------------------------------------------------------------------
function listDir(path) {
return new Promise(function(resolve, reject) {
fs.readdir(path, function(err, dirList) {
if (err) {
return reject(err);
}
var result = {
files: [],
dirs: []
};
var len = dirList.length;
if (!len) {
resolve(result);
}
dirList.forEach(function(filename) {
var file = (path === '/' ? '' : path) + '/' + filename;
fs.stat(file, function(err, stat) {
if (stat) {
result[stat.isFile() ? 'files' : 'dirs'].push(filename);
}
if (!--len) {
resolve(result);
}
});
});
});
});
}
// -------------------------------------------------------------------
function split_args(args) {
return {
options: args.filter(arg => arg.match(/^-/)).join('').replace(/-/g, ''),
args: args.filter(arg => !arg.match(/^-/))
};
}
// this is how you can create backed as replecement for BrowserFS
// this url need to point to JSON-RPC service you can easily create
// using library for your backend language of choice
var json_rpc_url = 'backend.php';
function cb_call(method, args, cb) {
$.jrpc(json_rpc_url, method, args, function(resp) {
if (resp.error) {
cb(resp.error);
} else {
cb(null, resp.result);
}
}, function(err, status) {
cb(status);
})
}
// same API as BrowserFS that's based on node.js
var backendFS = {
readFile: function(path, cb) {
cb_call('readFile', [path], cb);
},
stat: function(path, cb) {
cb_call('stat', [path], function(err, result) {
if (err) {
cb(err);
} else {
cb(err, {
isFile: function() {
return result === 'file';
},
isDirectory: function() {
return result === 'directory';
}
});
}
});
},
readdir: function(path, cb) {
cb_call('readdir', [path], cb);
}
};