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.
- myshell/__init__.py +1 -0
- myshell/__main__.py +5 -0
- myshell/aliases.py +22 -0
- myshell/arith.py +273 -0
- myshell/builtins.py +490 -0
- myshell/cli.py +155 -0
- myshell/compat.py +14 -0
- myshell/completion.py +137 -0
- myshell/coreutils.py +837 -0
- myshell/editor.py +218 -0
- myshell/errors.py +41 -0
- myshell/executor.py +752 -0
- myshell/expand.py +704 -0
- myshell/guide.py +609 -0
- myshell/heredoc.py +26 -0
- myshell/highlight.py +227 -0
- myshell/history.py +123 -0
- myshell/jobs.py +254 -0
- myshell/lexer.py +246 -0
- myshell/more_builtins.py +544 -0
- myshell/parser.py +437 -0
- myshell/paths.py +18 -0
- myshell/progress.py +98 -0
- myshell/prompt.py +197 -0
- myshell/quiz.py +148 -0
- myshell/state.py +107 -0
- myshell_py-0.2.0.dist-info/METADATA +195 -0
- myshell_py-0.2.0.dist-info/RECORD +30 -0
- myshell_py-0.2.0.dist-info/WHEEL +4 -0
- myshell_py-0.2.0.dist-info/entry_points.txt +2 -0
myshell/builtins.py
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
"""Builtin commands. Each takes (state, args, stdout, stderr) and returns a status."""
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import shutil
|
|
5
|
+
from typing import Callable, Dict, List, Optional, TextIO
|
|
6
|
+
|
|
7
|
+
from .paths import expand_user
|
|
8
|
+
from . import compat, history
|
|
9
|
+
from .coreutils import PORTABLE
|
|
10
|
+
from .more_builtins import EXTRA_BUILTINS, unescape
|
|
11
|
+
from .errors import BreakLoop, ContinueLoop, ReturnFromFunction, ShellError, ShellExit
|
|
12
|
+
from .state import ShellState
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# Signature: (state, args, stdout, stderr) -> exit status
|
|
16
|
+
Builtin = Callable[[ShellState, List[str], TextIO, TextIO], int]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def builtin_echo(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
20
|
+
newline, escapes = True, False
|
|
21
|
+
while args and re.fullmatch(r"-[neE]+", args[0]):
|
|
22
|
+
newline = newline and "n" not in args[0]
|
|
23
|
+
if "e" in args[0]:
|
|
24
|
+
escapes = True
|
|
25
|
+
if "E" in args[0]:
|
|
26
|
+
escapes = False
|
|
27
|
+
args = args[1:]
|
|
28
|
+
text = " ".join(args)
|
|
29
|
+
stdout.write((unescape(text) if escapes else text) + ("\n" if newline else ""))
|
|
30
|
+
return 0
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def builtin_pwd(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
34
|
+
if args:
|
|
35
|
+
print("pwd: too many arguments", file=stderr)
|
|
36
|
+
return 1
|
|
37
|
+
print(os.getcwd(), file=stdout)
|
|
38
|
+
return 0
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def builtin_cd(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
42
|
+
if len(args) > 1:
|
|
43
|
+
print("cd: too many arguments", file=stderr)
|
|
44
|
+
return 1
|
|
45
|
+
if not args:
|
|
46
|
+
target = os.environ.get("HOME", "")
|
|
47
|
+
if not target:
|
|
48
|
+
print("cd: HOME not set", file=stderr)
|
|
49
|
+
return 1
|
|
50
|
+
elif args[0] == "-":
|
|
51
|
+
target = os.environ.get("OLDPWD", "")
|
|
52
|
+
if not target:
|
|
53
|
+
print("cd: OLDPWD not set", file=stderr)
|
|
54
|
+
return 1
|
|
55
|
+
else:
|
|
56
|
+
target = args[0]
|
|
57
|
+
try:
|
|
58
|
+
old = os.getcwd()
|
|
59
|
+
except OSError:
|
|
60
|
+
old = os.environ.get("PWD", "")
|
|
61
|
+
try:
|
|
62
|
+
os.chdir(expand_user(target))
|
|
63
|
+
except OSError as e:
|
|
64
|
+
print(f"cd: {target}: {e.strerror}", file=stderr)
|
|
65
|
+
return 1
|
|
66
|
+
os.environ["OLDPWD"] = old
|
|
67
|
+
os.environ["PWD"] = os.getcwd()
|
|
68
|
+
if args and args[0] == "-":
|
|
69
|
+
print(os.getcwd(), file=stdout)
|
|
70
|
+
return 0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def builtin_exit(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
74
|
+
if len(args) > 1:
|
|
75
|
+
print("exit: too many arguments", file=stderr)
|
|
76
|
+
return 1
|
|
77
|
+
code = state.last_status
|
|
78
|
+
if args:
|
|
79
|
+
try:
|
|
80
|
+
code = int(args[0]) & 0xFF
|
|
81
|
+
except ValueError:
|
|
82
|
+
print(f"exit: {args[0]}: numeric argument required", file=stderr)
|
|
83
|
+
code = 2
|
|
84
|
+
raise ShellExit(code)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def builtin_alias(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
88
|
+
if not args:
|
|
89
|
+
for k, v in state.aliases.items():
|
|
90
|
+
print(f"alias {k}='{v}'", file=stdout)
|
|
91
|
+
return 0
|
|
92
|
+
status = 0
|
|
93
|
+
for arg in args:
|
|
94
|
+
if "=" in arg:
|
|
95
|
+
k, v = arg.split("=", 1)
|
|
96
|
+
state.aliases[k] = v
|
|
97
|
+
elif arg in state.aliases:
|
|
98
|
+
print(f"alias {arg}='{state.aliases[arg]}'", file=stdout)
|
|
99
|
+
else:
|
|
100
|
+
print(f"alias: {arg}: not found", file=stderr)
|
|
101
|
+
status = 1
|
|
102
|
+
return status
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def find_builtin(name: str) -> Optional[Builtin]:
|
|
106
|
+
"""A builtin by name. The portable commands (ls, cat, ...) only count when the system
|
|
107
|
+
has no program of that name, or when MYSHELL_PORTABLE=1 asks for them."""
|
|
108
|
+
func = BUILTINS.get(name)
|
|
109
|
+
if func is not None:
|
|
110
|
+
return func
|
|
111
|
+
func = PORTABLE.get(name)
|
|
112
|
+
if func is not None and (os.environ.get("MYSHELL_PORTABLE") == "1"
|
|
113
|
+
or shutil.which(name) is None):
|
|
114
|
+
return func
|
|
115
|
+
return None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def builtin_names() -> List[str]:
|
|
119
|
+
return sorted(set(BUILTINS) | {n for n in PORTABLE if find_builtin(n)})
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def describe(state: ShellState, name: str) -> Optional[str]:
|
|
123
|
+
"""How the shell would run name: an alias, a function, a builtin or a program."""
|
|
124
|
+
if name in state.aliases:
|
|
125
|
+
return f"{name} is an alias for '{state.aliases[name]}'"
|
|
126
|
+
if name in state.functions:
|
|
127
|
+
return f"{name} is a shell function"
|
|
128
|
+
if find_builtin(name):
|
|
129
|
+
return f"{name} is a shell builtin"
|
|
130
|
+
exe = shutil.which(name)
|
|
131
|
+
return f"{name} is {exe}" if exe else None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def builtin_type(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
135
|
+
if not args:
|
|
136
|
+
print("type: missing argument", file=stderr)
|
|
137
|
+
return 1
|
|
138
|
+
text = describe(state, args[0])
|
|
139
|
+
if text is None:
|
|
140
|
+
print(f"{args[0]}: not found", file=stderr)
|
|
141
|
+
return 1
|
|
142
|
+
print(text, file=stdout)
|
|
143
|
+
return 0
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def builtin_jobs(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
147
|
+
if not compat.HAS_FORK:
|
|
148
|
+
return 0
|
|
149
|
+
jc = state.jobs
|
|
150
|
+
jc.refresh()
|
|
151
|
+
for job in jc.numbered():
|
|
152
|
+
print(jc.format(job), file=stdout)
|
|
153
|
+
for job in [j for j in jc.numbered() if j.completed]:
|
|
154
|
+
jc.remove(job) # a finished job is listed once
|
|
155
|
+
return 0
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _job_builtin_ready(name: str, stderr: TextIO) -> bool:
|
|
159
|
+
if compat.HAS_FORK:
|
|
160
|
+
return True
|
|
161
|
+
print(f"{name}: job control is not supported on this platform", file=stderr)
|
|
162
|
+
return False
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def builtin_fg(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
166
|
+
if not _job_builtin_ready("fg", stderr):
|
|
167
|
+
return 1
|
|
168
|
+
jc = state.jobs
|
|
169
|
+
jc.refresh()
|
|
170
|
+
try:
|
|
171
|
+
job = jc.find(args[0] if args else None)
|
|
172
|
+
except ShellError as e:
|
|
173
|
+
print(f"fg: {e}", file=stderr)
|
|
174
|
+
return 1
|
|
175
|
+
if job.completed:
|
|
176
|
+
jc.remove(job)
|
|
177
|
+
print("fg: job has terminated", file=stderr)
|
|
178
|
+
return 1
|
|
179
|
+
print(job.command, file=stdout)
|
|
180
|
+
stdout.flush()
|
|
181
|
+
return jc.put_in_foreground(job, cont=True)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def builtin_bg(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
185
|
+
if not _job_builtin_ready("bg", stderr):
|
|
186
|
+
return 1
|
|
187
|
+
jc = state.jobs
|
|
188
|
+
jc.refresh()
|
|
189
|
+
try:
|
|
190
|
+
job = jc.find(args[0] if args else None)
|
|
191
|
+
except ShellError as e:
|
|
192
|
+
print(f"bg: {e}", file=stderr)
|
|
193
|
+
return 1
|
|
194
|
+
if job.completed:
|
|
195
|
+
jc.remove(job)
|
|
196
|
+
print("bg: job has terminated", file=stderr)
|
|
197
|
+
return 1
|
|
198
|
+
if not job.stopped:
|
|
199
|
+
print(f"bg: job {job.number} already in background", file=stderr)
|
|
200
|
+
return 0
|
|
201
|
+
jc.put_in_background(job, cont=True)
|
|
202
|
+
return 0
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def builtin_wait(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
206
|
+
if not _job_builtin_ready("wait", stderr):
|
|
207
|
+
return 1
|
|
208
|
+
jc = state.jobs
|
|
209
|
+
jc.refresh()
|
|
210
|
+
try:
|
|
211
|
+
targets = [jc.find(a) for a in args] if args else \
|
|
212
|
+
[j for j in jc.numbered() if not j.completed]
|
|
213
|
+
except ShellError as e:
|
|
214
|
+
print(f"wait: {e}", file=stderr)
|
|
215
|
+
return 127
|
|
216
|
+
status = 0
|
|
217
|
+
for job in targets:
|
|
218
|
+
if jc.wait_for(job, interruptible=True):
|
|
219
|
+
print()
|
|
220
|
+
return 130
|
|
221
|
+
if job.completed:
|
|
222
|
+
status = job.last_status if args else 0
|
|
223
|
+
jc.remove(job)
|
|
224
|
+
return status
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def builtin_export(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
231
|
+
if not args:
|
|
232
|
+
for k in sorted(os.environ):
|
|
233
|
+
v = os.environ[k].replace("\\", "\\\\").replace('"', '\\"')
|
|
234
|
+
print(f'declare -x {k}="{v}"', file=stdout)
|
|
235
|
+
return 0
|
|
236
|
+
status = 0
|
|
237
|
+
for arg in args:
|
|
238
|
+
name, sep, value = arg.partition("=")
|
|
239
|
+
if not NAME_RE.fullmatch(name):
|
|
240
|
+
print(f"export: `{arg}': not a valid identifier", file=stderr)
|
|
241
|
+
status = 1
|
|
242
|
+
elif sep:
|
|
243
|
+
state.export_variable(name, value)
|
|
244
|
+
else:
|
|
245
|
+
state.export_variable(name)
|
|
246
|
+
return status
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def builtin_unset(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
250
|
+
status = 0
|
|
251
|
+
functions = False
|
|
252
|
+
if args and args[0] in ("-f", "-v"):
|
|
253
|
+
functions, args = args[0] == "-f", args[1:]
|
|
254
|
+
for name in args:
|
|
255
|
+
if functions:
|
|
256
|
+
state.functions.pop(name, None)
|
|
257
|
+
elif NAME_RE.fullmatch(name):
|
|
258
|
+
state.unset_variable(name)
|
|
259
|
+
else:
|
|
260
|
+
print(f"unset: `{name}': not a valid identifier", file=stderr)
|
|
261
|
+
status = 1
|
|
262
|
+
return status
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
FILE_TESTS = {
|
|
266
|
+
"-e": os.path.exists, "-f": os.path.isfile, "-d": os.path.isdir,
|
|
267
|
+
"-L": os.path.islink, "-h": os.path.islink,
|
|
268
|
+
"-r": lambda p: os.access(p, os.R_OK), "-w": lambda p: os.access(p, os.W_OK),
|
|
269
|
+
"-x": lambda p: os.access(p, os.X_OK),
|
|
270
|
+
"-s": lambda p: os.path.exists(p) and os.path.getsize(p) > 0,
|
|
271
|
+
}
|
|
272
|
+
INT_TESTS = {
|
|
273
|
+
"-eq": lambda a, b: a == b, "-ne": lambda a, b: a != b, "-lt": lambda a, b: a < b,
|
|
274
|
+
"-le": lambda a, b: a <= b, "-gt": lambda a, b: a > b, "-ge": lambda a, b: a >= b,
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def evaluate_test(args: List[str]) -> bool:
|
|
279
|
+
n = len(args)
|
|
280
|
+
if n == 0:
|
|
281
|
+
return False
|
|
282
|
+
if n >= 2 and args[0] == "!":
|
|
283
|
+
return not evaluate_test(args[1:])
|
|
284
|
+
if n == 1:
|
|
285
|
+
return args[0] != ""
|
|
286
|
+
if n == 2:
|
|
287
|
+
op, value = args
|
|
288
|
+
if op == "-z":
|
|
289
|
+
return value == ""
|
|
290
|
+
if op == "-n":
|
|
291
|
+
return value != ""
|
|
292
|
+
if op in FILE_TESTS:
|
|
293
|
+
return bool(FILE_TESTS[op](value))
|
|
294
|
+
raise ShellError(f"{op}: unary operator expected")
|
|
295
|
+
if n == 3:
|
|
296
|
+
a, op, b = args
|
|
297
|
+
if op in ("=", "=="):
|
|
298
|
+
return a == b
|
|
299
|
+
if op == "!=":
|
|
300
|
+
return a != b
|
|
301
|
+
if op in INT_TESTS:
|
|
302
|
+
try:
|
|
303
|
+
return INT_TESTS[op](int(a), int(b))
|
|
304
|
+
except ValueError:
|
|
305
|
+
raise ShellError("integer expression expected")
|
|
306
|
+
raise ShellError(f"{op}: binary operator expected")
|
|
307
|
+
raise ShellError("too many arguments")
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def run_test(name: str, args: List[str], stderr: TextIO) -> int:
|
|
311
|
+
"""Status 0 when true, 1 when false, 2 on a bad expression."""
|
|
312
|
+
try:
|
|
313
|
+
return 0 if evaluate_test(args) else 1
|
|
314
|
+
except ShellError as e:
|
|
315
|
+
print(f"{name}: {e}", file=stderr)
|
|
316
|
+
return 2
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def builtin_test(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
320
|
+
return run_test("test", args, stderr)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def builtin_bracket(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
324
|
+
if not args or args[-1] != "]":
|
|
325
|
+
print("[: missing `]'", file=stderr)
|
|
326
|
+
return 2
|
|
327
|
+
return run_test("[", args[:-1], stderr)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def loop_control(name: str, exc, state: ShellState, args: List[str], stderr: TextIO) -> int:
|
|
331
|
+
if len(args) > 1:
|
|
332
|
+
print(f"{name}: too many arguments", file=stderr)
|
|
333
|
+
return 1
|
|
334
|
+
count = 1
|
|
335
|
+
if args:
|
|
336
|
+
if not args[0].isdigit() or int(args[0]) == 0:
|
|
337
|
+
print(f"{name}: {args[0]}: loop count out of range", file=stderr)
|
|
338
|
+
return 1
|
|
339
|
+
count = int(args[0])
|
|
340
|
+
if state.loop_depth == 0:
|
|
341
|
+
print(f"{name}: only meaningful in a `for', `while', or `until' loop", file=stderr)
|
|
342
|
+
return 0
|
|
343
|
+
raise exc(min(count, state.loop_depth))
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def builtin_break(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
347
|
+
return loop_control("break", BreakLoop, state, args, stderr)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def builtin_continue(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
351
|
+
return loop_control("continue", ContinueLoop, state, args, stderr)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def builtin_guide(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
355
|
+
from .guide import guide_main # imported here: guide needs BUILTINS from this module
|
|
356
|
+
return guide_main(state, args, stdout, stderr)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
class LineSource:
|
|
360
|
+
"""Hands out the lines of a script one at a time. A command that needs more lines
|
|
361
|
+
(a here-document) takes them from the same source."""
|
|
362
|
+
|
|
363
|
+
def __init__(self, text: str):
|
|
364
|
+
self.lines = text.splitlines()
|
|
365
|
+
self.number = 0 # lines handed out so far
|
|
366
|
+
|
|
367
|
+
def next(self) -> Optional[str]:
|
|
368
|
+
if self.number >= len(self.lines):
|
|
369
|
+
return None
|
|
370
|
+
line = self.lines[self.number]
|
|
371
|
+
self.number += 1
|
|
372
|
+
return line
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def run_script(state: ShellState, text: str, label: str, stderr: TextIO) -> int:
|
|
376
|
+
"""Run each line of text in the current shell. Returns the last status."""
|
|
377
|
+
status = 0
|
|
378
|
+
source = LineSource(text)
|
|
379
|
+
while True:
|
|
380
|
+
line = source.next()
|
|
381
|
+
if line is None:
|
|
382
|
+
return status
|
|
383
|
+
number = source.number # the line where this command starts
|
|
384
|
+
if not line.strip():
|
|
385
|
+
continue
|
|
386
|
+
try:
|
|
387
|
+
status = state.execute(line, source.next)
|
|
388
|
+
except ShellError as e:
|
|
389
|
+
print(f"{label}: line {number}: {e}", file=stderr)
|
|
390
|
+
status = state.last_status = 2
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def builtin_history(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
394
|
+
"""history [N] | -c | -d N | -w [file] | -r [file]"""
|
|
395
|
+
total = history.length()
|
|
396
|
+
if not args or args[0].isdigit():
|
|
397
|
+
if len(args) > 1:
|
|
398
|
+
print("history: too many arguments", file=stderr)
|
|
399
|
+
return 1
|
|
400
|
+
start = max(0, total - int(args[0])) if args else 0
|
|
401
|
+
for k in range(start + 1, total + 1):
|
|
402
|
+
print(f"{k:5d} {history.item(k)}", file=stdout)
|
|
403
|
+
return 0
|
|
404
|
+
flag = args[0]
|
|
405
|
+
if flag == "-c":
|
|
406
|
+
history.clear()
|
|
407
|
+
return 0
|
|
408
|
+
if flag == "-d":
|
|
409
|
+
if len(args) < 2:
|
|
410
|
+
print("history: -d: option requires an argument", file=stderr)
|
|
411
|
+
return 2
|
|
412
|
+
if not args[1].isdigit():
|
|
413
|
+
print(f"history: {args[1]}: numeric argument required", file=stderr)
|
|
414
|
+
return 1
|
|
415
|
+
position = int(args[1])
|
|
416
|
+
if not 1 <= position <= total:
|
|
417
|
+
print(f"history: {position}: history position out of range", file=stderr)
|
|
418
|
+
return 1
|
|
419
|
+
history.remove(position)
|
|
420
|
+
return 0
|
|
421
|
+
if flag in ("-w", "-r"):
|
|
422
|
+
path = args[1] if len(args) > 1 else state.history_file
|
|
423
|
+
try:
|
|
424
|
+
if flag == "-w":
|
|
425
|
+
history.write(path)
|
|
426
|
+
else:
|
|
427
|
+
history.read(path)
|
|
428
|
+
except OSError as e:
|
|
429
|
+
print(f"history: {path}: {e.strerror}", file=stderr)
|
|
430
|
+
return 1
|
|
431
|
+
return 0
|
|
432
|
+
if flag.startswith("-") and len(flag) > 1:
|
|
433
|
+
print(f"history: {flag}: invalid option", file=stderr)
|
|
434
|
+
return 2
|
|
435
|
+
print(f"history: {flag}: numeric argument required", file=stderr)
|
|
436
|
+
return 1
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def source_file(state: ShellState, path: str, stderr: TextIO,
|
|
440
|
+
args: Optional[List[str]] = None) -> int:
|
|
441
|
+
"""Run each line of a file in the current shell. Extra args become $1, $2, ... meanwhile."""
|
|
442
|
+
try:
|
|
443
|
+
with open(path) as f:
|
|
444
|
+
text = f.read()
|
|
445
|
+
except OSError as e:
|
|
446
|
+
print(f"source: {path}: {e.strerror}", file=stderr)
|
|
447
|
+
return 1
|
|
448
|
+
saved = state.positional
|
|
449
|
+
if args:
|
|
450
|
+
state.positional = list(args)
|
|
451
|
+
state.func_depth += 1 # return works inside a sourced file
|
|
452
|
+
try:
|
|
453
|
+
return run_script(state, text, path, stderr)
|
|
454
|
+
except ReturnFromFunction as r:
|
|
455
|
+
return r.status
|
|
456
|
+
finally:
|
|
457
|
+
state.func_depth -= 1
|
|
458
|
+
state.positional = saved
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def builtin_source(state: ShellState, args: List[str], stdout: TextIO, stderr: TextIO) -> int:
|
|
462
|
+
if not args:
|
|
463
|
+
print("source: filename argument required", file=stderr)
|
|
464
|
+
return 2
|
|
465
|
+
return source_file(state, args[0], stderr, args[1:])
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
BUILTINS: Dict[str, Builtin] = {
|
|
469
|
+
"echo": builtin_echo,
|
|
470
|
+
"pwd": builtin_pwd,
|
|
471
|
+
"cd": builtin_cd,
|
|
472
|
+
"alias": builtin_alias,
|
|
473
|
+
"exit": builtin_exit,
|
|
474
|
+
"type": builtin_type,
|
|
475
|
+
"export": builtin_export,
|
|
476
|
+
"unset": builtin_unset,
|
|
477
|
+
"source": builtin_source,
|
|
478
|
+
".": builtin_source,
|
|
479
|
+
"jobs": builtin_jobs,
|
|
480
|
+
"fg": builtin_fg,
|
|
481
|
+
"bg": builtin_bg,
|
|
482
|
+
"wait": builtin_wait,
|
|
483
|
+
"history": builtin_history,
|
|
484
|
+
"test": builtin_test,
|
|
485
|
+
"[": builtin_bracket,
|
|
486
|
+
"guide": builtin_guide,
|
|
487
|
+
"break": builtin_break,
|
|
488
|
+
"continue": builtin_continue,
|
|
489
|
+
}
|
|
490
|
+
BUILTINS.update(EXTRA_BUILTINS)
|
myshell/cli.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Entry point.
|
|
2
|
+
|
|
3
|
+
python -m myshell interactive shell
|
|
4
|
+
python -m myshell -c "cmd" run a command string and exit
|
|
5
|
+
python -m myshell script.sh run a script file and exit
|
|
6
|
+
"""
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
from typing import List, Optional
|
|
11
|
+
|
|
12
|
+
from . import history
|
|
13
|
+
from .builtins import run_script
|
|
14
|
+
from .completion import setup_readline
|
|
15
|
+
from .errors import ShellError, ShellExit
|
|
16
|
+
from .executor import Executor
|
|
17
|
+
from .guide import greeting, guide_enabled, missing_hint, say, syntax_hint
|
|
18
|
+
from .editor import make_reader
|
|
19
|
+
from .prompt import build_continuation_prompt, build_prompt, slow_notice
|
|
20
|
+
from .state import ShellState
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def new_shell() -> ShellState:
|
|
24
|
+
sys.setrecursionlimit(max(sys.getrecursionlimit(), 6000)) # deep shell functions need it
|
|
25
|
+
if not os.environ.get("HOME") and os.environ.get("USERPROFILE"):
|
|
26
|
+
os.environ["HOME"] = os.environ["USERPROFILE"] # Windows has no HOME
|
|
27
|
+
state = ShellState()
|
|
28
|
+
state.executor = Executor(state)
|
|
29
|
+
try:
|
|
30
|
+
os.environ["PWD"] = os.getcwd()
|
|
31
|
+
except OSError:
|
|
32
|
+
pass
|
|
33
|
+
return state
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def run_exit_trap(state: ShellState) -> None:
|
|
37
|
+
"""Run the command set with `trap '...' EXIT`, once."""
|
|
38
|
+
cmd = state.traps.pop("EXIT", None)
|
|
39
|
+
if cmd:
|
|
40
|
+
try:
|
|
41
|
+
state.execute(cmd)
|
|
42
|
+
except (ShellExit, ShellError):
|
|
43
|
+
pass
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def run_noninteractive(state: ShellState, text: str, label: str) -> int:
|
|
47
|
+
"""Run a command string or script. No prompt, no rc file, no job control."""
|
|
48
|
+
try:
|
|
49
|
+
run_script(state, text, label, sys.stderr)
|
|
50
|
+
code = state.last_status
|
|
51
|
+
except ShellExit as e:
|
|
52
|
+
code = e.code
|
|
53
|
+
except KeyboardInterrupt:
|
|
54
|
+
code = 130
|
|
55
|
+
state.last_status = code
|
|
56
|
+
run_exit_trap(state)
|
|
57
|
+
return code
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def run_interactive(state: ShellState) -> int:
|
|
61
|
+
state.jobs.init_terminal()
|
|
62
|
+
state.load_history()
|
|
63
|
+
setup_readline(state)
|
|
64
|
+
reader = make_reader(state) # None means plain input() with readline
|
|
65
|
+
code = 0
|
|
66
|
+
try:
|
|
67
|
+
if os.path.isfile(state.rc_file):
|
|
68
|
+
from .builtins import source_file
|
|
69
|
+
source_file(state, state.rc_file, sys.stderr)
|
|
70
|
+
state.last_status = 0
|
|
71
|
+
interactive = sys.stdin.isatty() # scripts piped in keep the plain "$ " prompt
|
|
72
|
+
if interactive and guide_enabled(state):
|
|
73
|
+
greeting(state, sys.stdout)
|
|
74
|
+
while True:
|
|
75
|
+
state.reap_jobs()
|
|
76
|
+
try:
|
|
77
|
+
try:
|
|
78
|
+
prompt = build_prompt(state) if interactive else "$ "
|
|
79
|
+
except Exception:
|
|
80
|
+
prompt = "$ "
|
|
81
|
+
line = reader.read(prompt) if reader else input(prompt)
|
|
82
|
+
except EOFError:
|
|
83
|
+
print("exit")
|
|
84
|
+
code = state.last_status
|
|
85
|
+
break
|
|
86
|
+
except KeyboardInterrupt:
|
|
87
|
+
print()
|
|
88
|
+
continue
|
|
89
|
+
if not line.strip():
|
|
90
|
+
continue
|
|
91
|
+
if not interactive or not history.records_input():
|
|
92
|
+
history.add(line) # otherwise input() records the line itself
|
|
93
|
+
|
|
94
|
+
def read_more() -> Optional[str]:
|
|
95
|
+
try:
|
|
96
|
+
text = build_continuation_prompt(state) if interactive else ""
|
|
97
|
+
return reader.read_continuation(text) if reader else input(text)
|
|
98
|
+
except EOFError:
|
|
99
|
+
return None
|
|
100
|
+
state.missing_command = None
|
|
101
|
+
started = time.monotonic()
|
|
102
|
+
try:
|
|
103
|
+
state.execute(line, read_more)
|
|
104
|
+
except ShellError as e:
|
|
105
|
+
print(e, file=sys.stderr)
|
|
106
|
+
state.last_status = 2
|
|
107
|
+
if interactive and guide_enabled(state):
|
|
108
|
+
hint = syntax_hint(str(e))
|
|
109
|
+
if hint:
|
|
110
|
+
say(hint, "worried")
|
|
111
|
+
except KeyboardInterrupt:
|
|
112
|
+
print()
|
|
113
|
+
state.last_duration = time.monotonic() - started
|
|
114
|
+
if interactive:
|
|
115
|
+
state.save_history() # saved after every line, so a killed shell loses nothing
|
|
116
|
+
if state.pending_traps:
|
|
117
|
+
state.run_pending_traps()
|
|
118
|
+
if interactive and line.split()[0] != "guide":
|
|
119
|
+
notice = slow_notice(state)
|
|
120
|
+
if notice:
|
|
121
|
+
print(notice)
|
|
122
|
+
if interactive and state.missing_command and guide_enabled(state):
|
|
123
|
+
hint = missing_hint(state.missing_command, state)
|
|
124
|
+
if hint:
|
|
125
|
+
say(hint, "worried")
|
|
126
|
+
except ShellExit as e:
|
|
127
|
+
code = e.code
|
|
128
|
+
state.last_status = code
|
|
129
|
+
run_exit_trap(state)
|
|
130
|
+
state.save_history()
|
|
131
|
+
return code
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
135
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
136
|
+
state = new_shell()
|
|
137
|
+
if argv and argv[0] == "-c":
|
|
138
|
+
if len(argv) < 2:
|
|
139
|
+
print("myshell: -c: option requires an argument", file=sys.stderr)
|
|
140
|
+
return 2
|
|
141
|
+
if len(argv) > 2: # myshell -c 'cmd' NAME ARG... sets $0 and $1, $2, ...
|
|
142
|
+
state.script_name = argv[2]
|
|
143
|
+
state.positional = list(argv[3:])
|
|
144
|
+
return run_noninteractive(state, argv[1], "-c")
|
|
145
|
+
if argv:
|
|
146
|
+
try:
|
|
147
|
+
with open(argv[0]) as f:
|
|
148
|
+
text = f.read()
|
|
149
|
+
except OSError as e:
|
|
150
|
+
print(f"myshell: {argv[0]}: {e.strerror}", file=sys.stderr)
|
|
151
|
+
return 127
|
|
152
|
+
state.script_name = argv[0]
|
|
153
|
+
state.positional = list(argv[1:])
|
|
154
|
+
return run_noninteractive(state, text, argv[0])
|
|
155
|
+
return run_interactive(state)
|
myshell/compat.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Platform checks.
|
|
2
|
+
|
|
3
|
+
Other modules read compat.HAS_FORK when they run, never at import time,
|
|
4
|
+
so tests can switch the portable code path on and off."""
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
import termios
|
|
9
|
+
except ImportError: # Windows
|
|
10
|
+
termios = None
|
|
11
|
+
|
|
12
|
+
# True on Unix. The shell then runs commands with fork, pipe and process groups.
|
|
13
|
+
# Without it the shell falls back to the subprocess module.
|
|
14
|
+
HAS_FORK = all(hasattr(os, n) for n in ("fork", "setpgid", "killpg", "tcsetpgrp"))
|