@j-o-r/sh 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils.js ADDED
@@ -0,0 +1,381 @@
1
+ // Copyright 2021 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // https://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ //
15
+ //
16
+ // Original Source: zx
17
+ // Link to Original Source: https://github.com/google/zx
18
+ // Reason for Using This Code:
19
+ // The core functionality of this code is highly beneficial. However, certain parts of the original code
20
+ // were overwriting the global namespace with core libraries and variables. This was causing conflicts with
21
+ // other packages (for instance, fetch) and introducing unexpected elements into my code base.
22
+ // Changes Made:
23
+ // - The code has been or is being reformatted to comply with ES2020 standards.
24
+ // - Some methods were added and existing ones were modified to enhance usability.
25
+ // - The namespace has been changed from '$' to 'SH'.
26
+ // Modified by: jorrit.duin+sh[AT]gmail.com
27
+
28
+ import { promisify } from 'node:util';
29
+ import psTreeModule from 'ps-tree';
30
+ export const psTree = promisify(psTreeModule);
31
+ export function noop() { }
32
+ export function randomId() {
33
+ return Math.random().toString(36).slice(2);
34
+ }
35
+ export function isString(obj) {
36
+ return typeof obj === 'string';
37
+ }
38
+ export function quote(arg) {
39
+ if (/^[a-z0-9/_.\-@:=]+$/i.test(arg) || arg === '') {
40
+ return arg;
41
+ }
42
+ return (`$'` +
43
+ arg
44
+ .replace(/\\/g, '\\\\')
45
+ .replace(/'/g, "\\'")
46
+ .replace(/\f/g, '\\f')
47
+ .replace(/\n/g, '\\n')
48
+ .replace(/\r/g, '\\r')
49
+ .replace(/\t/g, '\\t')
50
+ .replace(/\v/g, '\\v')
51
+ .replace(/\0/g, '\\0') +
52
+ `'`);
53
+ }
54
+ export function quotePowerShell(arg) {
55
+ if (/^[a-z0-9/_.\-]+$/i.test(arg) || arg === '') {
56
+ return arg;
57
+ }
58
+ return `'` + arg.replace(/'/g, "''") + `'`;
59
+ }
60
+
61
+ export function log (entry) {
62
+ switch (entry.kind) {
63
+ case 'cmd':
64
+ if (!entry.verbose) return;
65
+ process.stderr.write(formatCmd(entry.cmd));
66
+ break;
67
+ case 'stdout':
68
+ case 'stderr':
69
+ if (!entry.verbose) return;
70
+ process.stderr.write(entry.data);
71
+ break;
72
+ case 'retry':
73
+ if (!entry.verbose) return;
74
+ process.stderr.write(entry.error + '\n');
75
+ break;
76
+ case 'cd':
77
+ if (!entry.verbose) return;
78
+ process.stderr.write(`cd ${entry.dir}\n`);
79
+ break;
80
+ }
81
+ }
82
+ export function exitCodeInfo(exitCode) {
83
+ return {
84
+ 2: 'Misuse of shell builtins',
85
+ 126: 'Invoked command cannot execute',
86
+ 127: 'Command not found',
87
+ 128: 'Invalid exit argument',
88
+ 129: 'Hangup',
89
+ 130: 'Interrupt',
90
+ 131: 'Quit and dump core',
91
+ 132: 'Illegal instruction',
92
+ 133: 'Trace/breakpoint trap',
93
+ 134: 'Process aborted',
94
+ 135: 'Bus error: "access to undefined portion of memory object"',
95
+ 136: 'Floating point exception: "erroneous arithmetic operation"',
96
+ 137: 'Kill (terminate immediately)',
97
+ 138: 'User-defined 1',
98
+ 139: 'Segmentation violation',
99
+ 140: 'User-defined 2',
100
+ 141: 'Write to pipe with no one reading',
101
+ 142: 'Signal raised by alarm',
102
+ 143: 'Termination (request to terminate)',
103
+ 145: 'Child process terminated, stopped (or continued*)',
104
+ 146: 'Continue if stopped',
105
+ 147: 'Stop executing temporarily',
106
+ 148: 'Terminal stop signal',
107
+ 149: 'Background process attempting to read from tty ("in")',
108
+ 150: 'Background process attempting to write to tty ("out")',
109
+ 151: 'Urgent data available on socket',
110
+ 152: 'CPU time limit exceeded',
111
+ 153: 'File size limit exceeded',
112
+ 154: 'Signal raised by timer counting virtual time: "virtual timer expired"',
113
+ 155: 'Profiling timer expired',
114
+ 157: 'Pollable event',
115
+ 159: 'Bad syscall',
116
+ }[exitCode || -1];
117
+ }
118
+ export function errnoMessage(errno) {
119
+ if (errno === undefined) {
120
+ return 'Unknown error';
121
+ }
122
+ return ({
123
+ 0: 'Success',
124
+ 1: 'Not super-user',
125
+ 2: 'No such file or directory',
126
+ 3: 'No such process',
127
+ 4: 'Interrupted system call',
128
+ 5: 'I/O error',
129
+ 6: 'No such device or address',
130
+ 7: 'Arg list too long',
131
+ 8: 'Exec format error',
132
+ 9: 'Bad file number',
133
+ 10: 'No children',
134
+ 11: 'No more processes',
135
+ 12: 'Not enough core',
136
+ 13: 'Permission denied',
137
+ 14: 'Bad address',
138
+ 15: 'Block device required',
139
+ 16: 'Mount device busy',
140
+ 17: 'File exists',
141
+ 18: 'Cross-device link',
142
+ 19: 'No such device',
143
+ 20: 'Not a directory',
144
+ 21: 'Is a directory',
145
+ 22: 'Invalid argument',
146
+ 23: 'Too many open files in system',
147
+ 24: 'Too many open files',
148
+ 25: 'Not a typewriter',
149
+ 26: 'Text file busy',
150
+ 27: 'File too large',
151
+ 28: 'No space left on device',
152
+ 29: 'Illegal seek',
153
+ 30: 'Read only file system',
154
+ 31: 'Too many links',
155
+ 32: 'Broken pipe',
156
+ 33: 'Math arg out of domain of func',
157
+ 34: 'Math result not representable',
158
+ 35: 'File locking deadlock error',
159
+ 36: 'File or path name too long',
160
+ 37: 'No record locks available',
161
+ 38: 'Function not implemented',
162
+ 39: 'Directory not empty',
163
+ 40: 'Too many symbolic links',
164
+ 42: 'No message of desired type',
165
+ 43: 'Identifier removed',
166
+ 44: 'Channel number out of range',
167
+ 45: 'Level 2 not synchronized',
168
+ 46: 'Level 3 halted',
169
+ 47: 'Level 3 reset',
170
+ 48: 'Link number out of range',
171
+ 49: 'Protocol driver not attached',
172
+ 50: 'No CSI structure available',
173
+ 51: 'Level 2 halted',
174
+ 52: 'Invalid exchange',
175
+ 53: 'Invalid request descriptor',
176
+ 54: 'Exchange full',
177
+ 55: 'No anode',
178
+ 56: 'Invalid request code',
179
+ 57: 'Invalid slot',
180
+ 59: 'Bad font file fmt',
181
+ 60: 'Device not a stream',
182
+ 61: 'No data (for no delay io)',
183
+ 62: 'Timer expired',
184
+ 63: 'Out of streams resources',
185
+ 64: 'Machine is not on the network',
186
+ 65: 'Package not installed',
187
+ 66: 'The object is remote',
188
+ 67: 'The link has been severed',
189
+ 68: 'Advertise error',
190
+ 69: 'Srmount error',
191
+ 70: 'Communication error on send',
192
+ 71: 'Protocol error',
193
+ 72: 'Multihop attempted',
194
+ 73: 'Cross mount point (not really error)',
195
+ 74: 'Trying to read unreadable message',
196
+ 75: 'Value too large for defined data type',
197
+ 76: 'Given log. name not unique',
198
+ 77: 'f.d. invalid for this operation',
199
+ 78: 'Remote address changed',
200
+ 79: 'Can access a needed shared lib',
201
+ 80: 'Accessing a corrupted shared lib',
202
+ 81: '.lib section in a.out corrupted',
203
+ 82: 'Attempting to link in too many libs',
204
+ 83: 'Attempting to exec a shared library',
205
+ 84: 'Illegal byte sequence',
206
+ 86: 'Streams pipe error',
207
+ 87: 'Too many users',
208
+ 88: 'Socket operation on non-socket',
209
+ 89: 'Destination address required',
210
+ 90: 'Message too long',
211
+ 91: 'Protocol wrong type for socket',
212
+ 92: 'Protocol not available',
213
+ 93: 'Unknown protocol',
214
+ 94: 'Socket type not supported',
215
+ 95: 'Not supported',
216
+ 96: 'Protocol family not supported',
217
+ 97: 'Address family not supported by protocol family',
218
+ 98: 'Address already in use',
219
+ 99: 'Address not available',
220
+ 100: 'Network interface is not configured',
221
+ 101: 'Network is unreachable',
222
+ 102: 'Connection reset by network',
223
+ 103: 'Connection aborted',
224
+ 104: 'Connection reset by peer',
225
+ 105: 'No buffer space available',
226
+ 106: 'Socket is already connected',
227
+ 107: 'Socket is not connected',
228
+ 108: "Can't send after socket shutdown",
229
+ 109: 'Too many references',
230
+ 110: 'Connection timed out',
231
+ 111: 'Connection refused',
232
+ 112: 'Host is down',
233
+ 113: 'Host is unreachable',
234
+ 114: 'Socket already connected',
235
+ 115: 'Connection already in progress',
236
+ 116: 'Stale file handle',
237
+ 122: 'Quota exceeded',
238
+ 123: 'No medium (in tape drive)',
239
+ 125: 'Operation canceled',
240
+ 130: 'Previous owner died',
241
+ 131: 'State not recoverable',
242
+ }[-errno] || 'Unknown error');
243
+ }
244
+ export function parseDuration(d) {
245
+ if (typeof d == 'number') {
246
+ if (isNaN(d) || d < 0)
247
+ throw new Error(`Invalid duration: "${d}".`);
248
+ return d;
249
+ }
250
+ else if (/\d+s/.test(d)) {
251
+ return +d.slice(0, -1) * 1000;
252
+ }
253
+ else if (/\d+ms/.test(d)) {
254
+ return +d.slice(0, -2);
255
+ }
256
+ throw new Error(`Unknown duration: "${d}".`);
257
+ }
258
+ export function formatCmd(cmd) {
259
+ if (cmd == undefined)
260
+ return 'undefined';
261
+ const chars = [...cmd];
262
+ let out = '$ ';
263
+ let buf = '';
264
+ let ch;
265
+ let state = root;
266
+ let wordCount = 0;
267
+ while (state) {
268
+ ch = chars.shift() || 'EOF';
269
+ if (ch == '\n') {
270
+ out += style(state, buf) + '\n> ';
271
+ buf = '';
272
+ continue;
273
+ }
274
+ const next = ch == 'EOF' ? undefined : state();
275
+ if (next != state) {
276
+ out += style(state, buf);
277
+ buf = '';
278
+ }
279
+ state = next == root ? next() : next;
280
+ buf += ch;
281
+ }
282
+ function style(state, s) {
283
+ // if (s == '')
284
+ // return '';
285
+ // if (reservedWords.includes(s)) {
286
+ // return chalk.cyanBright(s);
287
+ // }
288
+ // if (state == word && wordCount == 0) {
289
+ // wordCount++;
290
+ // return chalk.greenBright(s);
291
+ // }
292
+ // if (state == syntax) {
293
+ // wordCount = 0;
294
+ // return chalk.cyanBright(s);
295
+ // }
296
+ // if (state == dollar)
297
+ // return chalk.yellowBright(s);
298
+ // if (state?.name.startsWith('str'))
299
+ // return chalk.yellowBright(s);
300
+ return s;
301
+ }
302
+ function isSyntax(ch) {
303
+ return '()[]{}<>;:+|&='.includes(ch);
304
+ }
305
+ function root() {
306
+ if (/\s/.test(ch))
307
+ return space;
308
+ if (isSyntax(ch))
309
+ return syntax;
310
+ if (/[$]/.test(ch))
311
+ return dollar;
312
+ if (/["]/.test(ch))
313
+ return strDouble;
314
+ if (/[']/.test(ch))
315
+ return strSingle;
316
+ return word;
317
+ }
318
+ function space() {
319
+ if (/\s/.test(ch))
320
+ return space;
321
+ return root;
322
+ }
323
+ function word() {
324
+ if (/[0-9a-z/_.]/i.test(ch))
325
+ return word;
326
+ return root;
327
+ }
328
+ function syntax() {
329
+ if (isSyntax(ch))
330
+ return syntax;
331
+ return root;
332
+ }
333
+ function dollar() {
334
+ if (/[']/.test(ch))
335
+ return str;
336
+ return root;
337
+ }
338
+ function str() {
339
+ if (/[']/.test(ch))
340
+ return strEnd;
341
+ if (/[\\]/.test(ch))
342
+ return strBackslash;
343
+ return str;
344
+ }
345
+ function strBackslash() {
346
+ return strEscape;
347
+ }
348
+ function strEscape() {
349
+ return str;
350
+ }
351
+ function strDouble() {
352
+ if (/["]/.test(ch))
353
+ return strEnd;
354
+ return strDouble;
355
+ }
356
+ function strSingle() {
357
+ if (/[']/.test(ch))
358
+ return strEnd;
359
+ return strSingle;
360
+ }
361
+ function strEnd() {
362
+ return root;
363
+ }
364
+ return out + '\n';
365
+ }
366
+ const reservedWords = [
367
+ 'if',
368
+ 'then',
369
+ 'else',
370
+ 'elif',
371
+ 'fi',
372
+ 'case',
373
+ 'esac',
374
+ 'for',
375
+ 'select',
376
+ 'while',
377
+ 'until',
378
+ 'do',
379
+ 'done',
380
+ 'in',
381
+ ];