myshell-py 0.2.0__py3-none-any.whl

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.
@@ -0,0 +1,544 @@
1
+ """More builtins: true, false, :, return, shift, local, read, printf, set, env, which,
2
+ unalias, exec and trap."""
3
+ import os
4
+ import re
5
+ import shutil
6
+ import signal
7
+ from typing import Callable, Dict, List, Optional, TextIO
8
+
9
+ from .errors import ReturnFromFunction, ShellExit
10
+ from .state import ShellState
11
+
12
+ Builtin = Callable[[ShellState, List[str], TextIO, TextIO], int]
13
+ NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
14
+
15
+ ECHO_ESCAPES = {"n": "\n", "t": "\t", "r": "\r", "a": "\a", "b": "\b", "f": "\f", "v": "\v",
16
+ "\\": "\\", "e": "\x1b"}
17
+
18
+
19
+ def unescape(text: str) -> str:
20
+ """Backslash escapes as in echo -e and printf: \\n \\t \\\\ \\0NNN \\xHH."""
21
+ out = []
22
+ i = 0
23
+ while i < len(text):
24
+ c = text[i]
25
+ if c != "\\" or i + 1 >= len(text):
26
+ out.append(c)
27
+ i += 1
28
+ continue
29
+ d = text[i + 1]
30
+ if d in ECHO_ESCAPES:
31
+ out.append(ECHO_ESCAPES[d])
32
+ i += 2
33
+ elif d == "0":
34
+ m = re.compile(r"[0-7]{1,3}").match(text, i + 2)
35
+ out.append(chr(int(m.group(), 8)) if m else "\0")
36
+ i = m.end() if m else i + 2
37
+ elif d == "x":
38
+ m = re.compile(r"[0-9a-fA-F]{1,2}").match(text, i + 2)
39
+ out.append(chr(int(m.group(), 16)) if m else "\\x")
40
+ i = m.end() if m else i + 2
41
+ else:
42
+ out.append(c + d)
43
+ i += 2
44
+ return "".join(out)
45
+
46
+
47
+
48
+
49
+ def builtin_true(state, args, stdout, stderr) -> int:
50
+ return 0
51
+
52
+
53
+ def builtin_false(state, args, stdout, stderr) -> int:
54
+ return 1
55
+
56
+
57
+ # --- functions and arguments ---
58
+ def builtin_return(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
59
+ if len(args) > 1:
60
+ print("return: too many arguments", file=stderr)
61
+ return 1
62
+ if state.func_depth == 0:
63
+ print("return: can only `return' from a function or sourced script", file=stderr)
64
+ return 1
65
+ code = state.last_status
66
+ if args:
67
+ try:
68
+ code = int(args[0]) & 0xFF
69
+ except ValueError:
70
+ print(f"return: {args[0]}: numeric argument required", file=stderr)
71
+ code = 2
72
+ raise ReturnFromFunction(code)
73
+
74
+
75
+ def builtin_shift(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
76
+ count = 1
77
+ if args:
78
+ if not args[0].isdigit():
79
+ print(f"shift: {args[0]}: numeric argument required", file=stderr)
80
+ return 1
81
+ count = int(args[0])
82
+ if count > len(state.positional):
83
+ print("shift: shift count out of range", file=stderr)
84
+ return 1
85
+ del state.positional[:count]
86
+ return 0
87
+
88
+
89
+ def builtin_local(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
90
+ if not state.local_frames:
91
+ print("local: can only be used in a function", file=stderr)
92
+ return 1
93
+ frame = state.local_frames[-1]
94
+ status = 0
95
+ for arg in args:
96
+ name, sep, value = arg.partition("=")
97
+ if not NAME_RE.fullmatch(name):
98
+ print(f"local: `{arg}': not a valid identifier", file=stderr)
99
+ status = 1
100
+ continue
101
+ if name not in frame:
102
+ frame[name] = state.get_variable(name)
103
+ if sep:
104
+ state.set_variable(name, value)
105
+ elif name not in os.environ:
106
+ state.variables[name] = ""
107
+ return status
108
+
109
+
110
+ # --- read ---
111
+ def builtin_read(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
112
+ """read [-r] [-p PROMPT] [-d DELIM] [-n COUNT] [NAME...]. Without a NAME the line goes to REPLY."""
113
+ raw, prompt, delim, count = False, None, "\n", None
114
+ names: List[str] = []
115
+ i = 0
116
+ while i < len(args):
117
+ a = args[i]
118
+ if a == "-r":
119
+ raw = True
120
+ elif a in ("-p", "-d", "-n"):
121
+ if i + 1 >= len(args):
122
+ print(f"read: {a}: option requires an argument", file=stderr)
123
+ return 2
124
+ i += 1
125
+ if a == "-p":
126
+ prompt = args[i]
127
+ elif a == "-d":
128
+ delim = args[i][:1] or "\0"
129
+ else:
130
+ if not args[i].isdigit():
131
+ print(f"read: {args[i]}: invalid number", file=stderr)
132
+ return 2
133
+ count = int(args[i])
134
+ elif a.startswith("-") and len(a) > 1:
135
+ print(f"read: {a}: invalid option", file=stderr)
136
+ return 2
137
+ else:
138
+ names.append(a)
139
+ i += 1
140
+ bad = [n for n in names if not NAME_RE.fullmatch(n)]
141
+ if bad:
142
+ print(f"read: `{bad[0]}': not a valid identifier", file=stderr)
143
+ return 1
144
+ stream = state.input_stream()
145
+ if prompt is not None and getattr(stream, "isatty", lambda: False)():
146
+ stderr.write(prompt)
147
+ stderr.flush()
148
+ line, got_delim = "", False
149
+ while True:
150
+ if delim == "\n" and count is None:
151
+ chunk = stream.readline()
152
+ if not chunk:
153
+ break
154
+ got_delim = chunk.endswith("\n")
155
+ line += chunk[:-1] if got_delim else chunk
156
+ if not raw and got_delim and re.search(r"(?<!\\)(\\\\)*\\$", line):
157
+ line = line[:-1] # a trailing backslash joins the next line
158
+ continue
159
+ break
160
+ ch = stream.read(1)
161
+ if not ch:
162
+ break
163
+ if ch == delim:
164
+ got_delim = True
165
+ break
166
+ line += ch
167
+ if count is not None and len(line) >= count:
168
+ got_delim = True
169
+ break
170
+ if not raw:
171
+ line = re.sub(r"\\(.)", r"\1", line, flags=re.DOTALL)
172
+ names = names or ["REPLY"]
173
+ ifs = state.get_variable("IFS")
174
+ ifs = " \t\n" if ifs is None else ifs
175
+ if ifs.strip(" \t\n") == "" and ifs:
176
+ fields = line.split(None, len(names) - 1) if len(names) > 1 else [line.strip()]
177
+ elif ifs:
178
+ pattern = "[" + re.escape(ifs) + "]"
179
+ fields = re.split(pattern, line, maxsplit=len(names) - 1)
180
+ else:
181
+ fields = [line]
182
+ for k, name in enumerate(names):
183
+ state.set_variable(name, fields[k] if k < len(fields) else "")
184
+ return 0 if got_delim else 1
185
+
186
+
187
+ # --- printf ---
188
+ SPEC_RE = re.compile(r"%([-+ #0]*)(\*|\d+)?(?:\.(\*|\d+))?([diouxXeEfFgGcsb%q])")
189
+
190
+
191
+ def to_int(text: str) -> int:
192
+ if text[:1] in ("'", '"') and len(text) > 1:
193
+ return ord(text[1])
194
+ if re.fullmatch(r"[+-]?0[0-7]+", text):
195
+ return int(text, 8) # a leading zero means octal, as in other shells
196
+ try:
197
+ return int(text, 0)
198
+ except ValueError:
199
+ if re.fullmatch(r"[+-]?\d+", text):
200
+ return int(text, 10)
201
+ raise ValueError(text)
202
+
203
+
204
+ def format_once(fmt: str, args: List[str], pos: int, stderr: TextIO, errors: List[bool]):
205
+ """Format fmt once. Returns (text, next argument position, arguments used)."""
206
+ out: List[str] = []
207
+ used = 0
208
+ i = 0
209
+ while i < len(fmt):
210
+ c = fmt[i]
211
+ if c == "\\":
212
+ m = re.compile(r"\\(0[0-7]{0,3}|x[0-9a-fA-F]{1,2}|[1-7][0-7]{0,2}|.)", re.DOTALL).match(fmt, i)
213
+ if m:
214
+ code = m.group(1)
215
+ out.append(chr(int(code, 8)) if code[0] in "1234567" and len(code) > 0
216
+ and code.isdigit() else unescape(m.group()))
217
+ i = m.end()
218
+ else:
219
+ out.append(c)
220
+ i += 1
221
+ continue
222
+ if c != "%":
223
+ out.append(c)
224
+ i += 1
225
+ continue
226
+ m = SPEC_RE.match(fmt, i)
227
+ if not m:
228
+ out.append(c)
229
+ i += 1
230
+ continue
231
+ i = m.end()
232
+ flags, width, prec, conv = m.groups()
233
+ if conv == "%":
234
+ out.append("%")
235
+ continue
236
+
237
+ def next_arg() -> Optional[str]:
238
+ nonlocal pos, used
239
+ if pos < len(args):
240
+ pos += 1
241
+ used += 1
242
+ return args[pos - 1]
243
+ return None
244
+ if width == "*":
245
+ width = next_arg() or "0"
246
+ if prec == "*":
247
+ prec = next_arg() or "0"
248
+ arg = next_arg()
249
+ spec = "%" + flags + (width or "") + ("." + prec if prec is not None else "")
250
+ try:
251
+ if conv in "di":
252
+ out.append((spec + "d") % to_int(arg or "0"))
253
+ elif conv in "ouxX":
254
+ out.append((spec + conv) % to_int(arg or "0"))
255
+ elif conv in "eEfFgG":
256
+ out.append((spec + conv) % float(arg or "0"))
257
+ elif conv == "c":
258
+ out.append((spec + "s") % (arg or "")[:1])
259
+ elif conv == "b":
260
+ out.append((spec + "s") % unescape(arg or ""))
261
+ elif conv == "q":
262
+ out.append((spec + "s") % ("'" + (arg or "").replace("'", "'\\''") + "'"))
263
+ else:
264
+ out.append((spec + "s") % (arg or ""))
265
+ except (ValueError, TypeError):
266
+ print(f"printf: {arg}: invalid number", file=stderr)
267
+ errors.append(True)
268
+ out.append((spec + "s") % "0" if conv not in "csbq" else "")
269
+ return "".join(out), pos, used
270
+
271
+
272
+ def builtin_printf(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
273
+ var = None
274
+ if len(args) >= 2 and args[0] == "-v":
275
+ var, args = args[1], args[2:]
276
+ if not args:
277
+ print("printf: usage: printf [-v var] format [arguments]", file=stderr)
278
+ return 2
279
+ fmt, rest = args[0], args[1:]
280
+ errors: List[bool] = []
281
+ pieces: List[str] = []
282
+ pos = 0
283
+ while True:
284
+ text, pos, used = format_once(fmt, rest, pos, stderr, errors)
285
+ pieces.append(text)
286
+ if pos >= len(rest) or used == 0:
287
+ break
288
+ result = "".join(pieces)
289
+ if var:
290
+ state.set_variable(var, result)
291
+ else:
292
+ stdout.write(result)
293
+ return 1 if errors else 0
294
+
295
+
296
+ # --- set ---
297
+ OPTION_NAMES = {"e": "errexit", "u": "nounset", "x": "xtrace"}
298
+
299
+
300
+ def builtin_set(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
301
+ if not args:
302
+ names = {**{k: v for k, v in os.environ.items()}, **state.variables}
303
+ for k in sorted(names):
304
+ print(f"{k}={names[k]}", file=stdout)
305
+ return 0
306
+ i = 0
307
+ while i < len(args):
308
+ a = args[i]
309
+ if a == "--":
310
+ state.positional = list(args[i + 1:])
311
+ return 0
312
+ if a in ("-o", "+o"):
313
+ if i + 1 >= len(args):
314
+ for name in OPTION_NAMES.values():
315
+ print(f"{name:<10}{'on' if name in state.options else 'off'}", file=stdout)
316
+ return 0
317
+ name = args[i + 1]
318
+ if name not in OPTION_NAMES.values():
319
+ print(f"set: {name}: invalid option name", file=stderr)
320
+ return 2
321
+ (state.options.add if a == "-o" else state.options.discard)(name)
322
+ i += 2
323
+ continue
324
+ if re.fullmatch(r"[-+][a-zA-Z]+", a):
325
+ for ch in a[1:]:
326
+ if ch not in OPTION_NAMES:
327
+ print(f"set: {a[0]}{ch}: invalid option", file=stderr)
328
+ return 2
329
+ (state.options.add if a[0] == "-" else state.options.discard)(OPTION_NAMES[ch])
330
+ i += 1
331
+ continue
332
+ break
333
+ if i < len(args):
334
+ state.positional = list(args[i:])
335
+ return 0
336
+
337
+
338
+ # --- env, which, unalias, exec ---
339
+ def builtin_env(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
340
+ """env [-i] [-u NAME] [NAME=VALUE]... [COMMAND [ARGS]]"""
341
+ saved = dict(os.environ)
342
+ clear: bool = False
343
+ unset: List[str] = []
344
+ i = 0
345
+ while i < len(args) and args[i].startswith("-") and args[i] != "-":
346
+ if args[i] == "-i":
347
+ clear = True
348
+ elif args[i] == "-u" and i + 1 < len(args):
349
+ i += 1
350
+ unset.append(args[i])
351
+ else:
352
+ print(f"env: invalid option -- '{args[i]}'", file=stderr)
353
+ return 125
354
+ i += 1
355
+ assigns: Dict[str, str] = {}
356
+ while i < len(args) and "=" in args[i] and not args[i].startswith("="):
357
+ k, _, v = args[i].partition("=")
358
+ assigns[k] = v
359
+ i += 1
360
+ command = args[i:]
361
+ if not command:
362
+ env = {} if clear else dict(saved)
363
+ for k in unset:
364
+ env.pop(k, None)
365
+ env.update(assigns)
366
+ for k, v in env.items():
367
+ print(f"{k}={v}", file=stdout)
368
+ return 0
369
+ try:
370
+ if clear:
371
+ os.environ.clear()
372
+ for k in unset:
373
+ os.environ.pop(k, None)
374
+ os.environ.update(assigns)
375
+ stdout.flush()
376
+ return state.executor.run_argv(command)
377
+ finally:
378
+ os.environ.clear()
379
+ os.environ.update(saved)
380
+
381
+
382
+ def builtin_which(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
383
+ from .builtins import find_builtin
384
+ show_all = False
385
+ if args and args[0] == "-a":
386
+ show_all, args = True, args[1:]
387
+ status = 0
388
+ for name in args:
389
+ found = False
390
+ if name in state.aliases:
391
+ print(f"{name}: aliased to {state.aliases[name]}", file=stdout)
392
+ found = True
393
+ if name in state.functions:
394
+ print(f"{name}: shell function", file=stdout)
395
+ found = True
396
+ if find_builtin(name):
397
+ print(f"{name}: shell built-in command", file=stdout)
398
+ found = True
399
+ if not found or show_all:
400
+ paths = []
401
+ exts = [""] + [e for e in os.environ.get("PATHEXT", "").split(os.pathsep) if e] \
402
+ if os.name == "nt" else [""]
403
+ for folder in os.environ.get("PATH", "").split(os.pathsep):
404
+ for ext in exts:
405
+ full = os.path.join(folder or ".", name + ext)
406
+ if os.path.isfile(full) and os.access(full, os.X_OK) and full not in paths:
407
+ paths.append(full)
408
+ for full in (paths if show_all else paths[:1]):
409
+ print(full, file=stdout)
410
+ found = True
411
+ if not found:
412
+ print(f"which: no {name} in ({os.environ.get('PATH', '')})", file=stderr)
413
+ status = 1
414
+ return status
415
+
416
+
417
+ def builtin_unalias(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
418
+ if not args:
419
+ print("unalias: usage: unalias [-a] name [name ...]", file=stderr)
420
+ return 2
421
+ if args[0] == "-a":
422
+ state.aliases.clear()
423
+ return 0
424
+ status = 0
425
+ for name in args:
426
+ if name in state.aliases:
427
+ del state.aliases[name]
428
+ else:
429
+ print(f"unalias: {name}: not found", file=stderr)
430
+ status = 1
431
+ return status
432
+
433
+
434
+ def builtin_exec(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
435
+ """exec COMMAND [ARGS]: run it in place of the shell, then exit."""
436
+ if not args:
437
+ return 0
438
+ stdout.flush()
439
+ stderr.flush()
440
+ from .builtins import find_builtin
441
+ name = args[0]
442
+ if name not in state.functions and not find_builtin(name):
443
+ path = shutil.which(name)
444
+ if path is None:
445
+ print(f"exec: {name}: not found", file=stderr)
446
+ return 127
447
+ if hasattr(os, "execv") and os.name != "nt":
448
+ history_save = getattr(state, "save_history", None)
449
+ if history_save:
450
+ history_save()
451
+ try:
452
+ os.execv(path, args)
453
+ except OSError as e:
454
+ print(f"exec: {name}: {e.strerror}", file=stderr)
455
+ return 126
456
+ status = state.executor.run_argv(args)
457
+ raise ShellExit(status)
458
+
459
+
460
+ # --- trap ---
461
+ def signal_table() -> Dict[str, int]:
462
+ table = {"EXIT": 0}
463
+ for name in ("HUP", "INT", "QUIT", "USR1", "USR2", "TERM"):
464
+ sig = getattr(signal, "SIG" + name, None)
465
+ if sig is not None:
466
+ table[name] = int(sig)
467
+ return table
468
+
469
+
470
+ def signal_name(text: str) -> Optional[str]:
471
+ table = signal_table()
472
+ t = text.upper()
473
+ if t.startswith("SIG"):
474
+ t = t[3:]
475
+ if t in table:
476
+ return t
477
+ if t.isdigit():
478
+ for name, number in table.items():
479
+ if number == int(t):
480
+ return name
481
+ return None
482
+
483
+
484
+ def builtin_trap(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
485
+ """trap 'COMMAND' SIGNAL... trap - SIGNAL... trap trap -l"""
486
+ table = signal_table()
487
+ if not args or args == ["-p"]:
488
+ for name, cmd in state.traps.items():
489
+ print(f"trap -- '{cmd}' {name}", file=stdout)
490
+ return 0
491
+ if args[0] == "-l":
492
+ print(" ".join(n for n in table if n != "EXIT"), file=stdout)
493
+ return 0
494
+ if len(args) == 1:
495
+ action, names = "-", args # trap SIGNAL resets it
496
+ else:
497
+ action, names = args[0], args[1:]
498
+ status = 0
499
+ for text in names:
500
+ name = signal_name(text)
501
+ if name is None:
502
+ print(f"trap: {text}: invalid signal specification", file=stderr)
503
+ status = 1
504
+ continue
505
+ if action == "-":
506
+ state.traps.pop(name, None)
507
+ if name != "EXIT":
508
+ try:
509
+ signal.signal(table[name], signal.default_int_handler
510
+ if name == "INT" else signal.SIG_DFL)
511
+ except (ValueError, OSError):
512
+ pass
513
+ continue
514
+ state.traps[name] = action
515
+ if name == "EXIT":
516
+ continue
517
+ try:
518
+ if action == "":
519
+ signal.signal(table[name], signal.SIG_IGN)
520
+ else:
521
+ signal.signal(table[name], lambda n, f, label=name: state.pending_traps.append(label))
522
+ except (ValueError, OSError) as e:
523
+ print(f"trap: {text}: {e}", file=stderr)
524
+ state.traps.pop(name, None)
525
+ status = 1
526
+ return status
527
+
528
+
529
+ EXTRA_BUILTINS: Dict[str, Builtin] = {
530
+ "true": builtin_true,
531
+ "false": builtin_false,
532
+ ":": builtin_true,
533
+ "return": builtin_return,
534
+ "shift": builtin_shift,
535
+ "local": builtin_local,
536
+ "read": builtin_read,
537
+ "printf": builtin_printf,
538
+ "set": builtin_set,
539
+ "env": builtin_env,
540
+ "which": builtin_which,
541
+ "unalias": builtin_unalias,
542
+ "exec": builtin_exec,
543
+ "trap": builtin_trap,
544
+ }