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/executor.py ADDED
@@ -0,0 +1,752 @@
1
+ """Executor: runs the parsed tree with fork and pipes, or with subprocess."""
2
+ import io
3
+ import os
4
+ import signal
5
+ import subprocess
6
+ import sys
7
+ import tempfile
8
+ from contextlib import contextmanager
9
+ from dataclasses import dataclass
10
+ from typing import Dict, List, Optional, Set, Tuple
11
+
12
+ from . import compat
13
+ from .aliases import expand_aliases
14
+ from .builtins import find_builtin
15
+ from .errors import ReturnFromFunction, ShellError, ShellExit
16
+ from .expand import (expand_heredoc, expand_pattern, expand_tokens, expand_value, expand_word,
17
+ glob_match, split_assignment)
18
+ from .heredoc import ReadLine, read_heredoc_body
19
+ from .jobs import CHILD_RESET_SIGNALS
20
+ from .errors import BreakLoop, ContinueLoop, ShellSyntaxError
21
+ from .lexer import SEMI, WORD, Token, lex
22
+ from .parser import (CaseClause, ForClause, FuncDef, Group, IfClause, ListItem, WhileClause,
23
+ Pipeline, Redirect, compound_open, is_word, iter_commands, parse)
24
+ from .state import ShellState
25
+
26
+
27
+ SIGINT_STATUS = 128 + signal.SIGINT # a command killed by Ctrl+C
28
+
29
+
30
+ @dataclass
31
+ class RedirectOp:
32
+ # One of: < <<< 1> 1>> 2> 2>> &> &>> 2>&1 1>&2 1>&1
33
+ # A here-document becomes <<< with the body as its text.
34
+ op: str
35
+ arg: str = "" # file name, or the text for <<<
36
+
37
+
38
+ def apply_redirects(ops: List[RedirectOp], table: Dict[int, object], opened: list) -> None:
39
+ """Apply redirections left to right, the way a shell does.
40
+
41
+ `table` maps fd 0, 1 and 2 to a handle: a file object or a raw fd number.
42
+ A duplication such as 2>&1 copies what the other fd points to at that moment,
43
+ so `> f 2>&1` sends both streams to f, while `2>&1 > f` sends only stdout there.
44
+ Files opened here go into `opened`. The caller closes them."""
45
+ def open_file(path: str, mode: str):
46
+ f = open(path, mode)
47
+ opened.append(f)
48
+ return f
49
+
50
+ for r in ops:
51
+ op = r.op
52
+ if op == "<":
53
+ table[0] = open_file(r.arg, "r")
54
+ elif op == "<<<":
55
+ f = tempfile.TemporaryFile("w+") # a file, not a pipe, so long text cannot block
56
+ opened.append(f)
57
+ f.write(r.arg)
58
+ f.seek(0)
59
+ table[0] = f
60
+ elif op in ("1>", "1>>"):
61
+ table[1] = open_file(r.arg, "a" if op.endswith(">>") else "w")
62
+ elif op in ("2>", "2>>"):
63
+ table[2] = open_file(r.arg, "a" if op.endswith(">>") else "w")
64
+ elif op in ("&>", "&>>"):
65
+ table[1] = table[2] = open_file(r.arg, "a" if op.endswith(">>") else "w")
66
+ elif op == "2>&1":
67
+ # subprocess has no fd to copy when stdout is a fresh pipe, so it uses STDOUT.
68
+ table[2] = subprocess.STDOUT if table[1] == subprocess.PIPE else table[1]
69
+ elif op == "1>&2":
70
+ if table[2] != subprocess.STDOUT:
71
+ table[1] = table[2]
72
+ # 1>&1 changes nothing.
73
+
74
+
75
+ def exit_status(returncode: int) -> int:
76
+ # Popen reports death by signal as a negative number. Shells use 128 + signal.
77
+ return 128 + -returncode if returncode < 0 else returncode
78
+
79
+
80
+ class Executor:
81
+ def __init__(self, state: ShellState):
82
+ self.state = state
83
+
84
+ # --- lines ---
85
+ def run_line(self, line: str, read_line: Optional[ReadLine] = None) -> int:
86
+ """Run one line. Here-document bodies are read from read_line, which returns
87
+ the next input line or None at the end of input."""
88
+ tokens = lex(line)
89
+ while compound_open(tokens): # an if block continues on the next lines
90
+ more = read_line() if read_line is not None else None
91
+ if more is None:
92
+ raise ShellSyntaxError("unexpected end of file")
93
+ extra = lex(more)
94
+ last = tokens[-1]
95
+ joins = last.kind == WORD and not is_word(last, ("then", "else", "elif", "if", "do", "while", "until", "{"))
96
+ if extra and joins:
97
+ tokens.append(Token(SEMI, [(";", "plain")]))
98
+ tokens.extend(extra)
99
+ items = parse(expand_aliases(tokens, self.state.aliases))
100
+ for cmd in iter_commands(items):
101
+ for red in cmd.redirects:
102
+ if red.op in ("<<", "<<-"):
103
+ red.body = read_heredoc_body(red.target.text, red.op == "<<-", read_line)
104
+ return self.run_list(items)
105
+
106
+ # --- lists ---
107
+ def run_list(self, items: List[ListItem]) -> int:
108
+ state = self.state
109
+ status = state.last_status
110
+ for idx, item in enumerate(items):
111
+ if item.op == "&&" and status != 0:
112
+ continue
113
+ if item.op == "||" and status == 0:
114
+ continue
115
+ try:
116
+ node = item.pipeline
117
+ if isinstance(node, IfClause):
118
+ status = self.run_if(node)
119
+ elif isinstance(node, WhileClause):
120
+ status = self.run_while(node)
121
+ elif isinstance(node, ForClause):
122
+ status = self.run_for(node)
123
+ elif isinstance(node, CaseClause):
124
+ status = self.run_case(node)
125
+ elif isinstance(node, Group):
126
+ status = self.run_list(node.body)
127
+ elif isinstance(node, FuncDef):
128
+ state.functions[node.name] = node.body
129
+ status = 0
130
+ else:
131
+ status = self.run_pipeline(node)
132
+ except ShellError as e:
133
+ print(e, file=sys.stderr)
134
+ status = 2
135
+ state.last_status = status
136
+ if state.pending_traps:
137
+ state.run_pending_traps()
138
+ if status != 0 and "errexit" in state.options and state.no_errexit == 0:
139
+ nxt = items[idx + 1] if idx + 1 < len(items) else None
140
+ if nxt is None or nxt.op not in ("&&", "||"):
141
+ raise ShellExit(status)
142
+ return status
143
+
144
+ def run_condition(self, items: List[ListItem]) -> int:
145
+ """Run the test of an if or while. A failure here must not trigger set -e."""
146
+ self.state.no_errexit += 1
147
+ try:
148
+ return self.run_list(items)
149
+ finally:
150
+ self.state.no_errexit -= 1
151
+
152
+ def run_if(self, node: IfClause) -> int:
153
+ for cond, body in node.clauses:
154
+ if self.run_condition(cond) == 0:
155
+ return self.run_list(body)
156
+ if node.else_body is not None:
157
+ return self.run_list(node.else_body)
158
+ return 0
159
+
160
+ def run_case(self, node: CaseClause) -> int:
161
+ word = "".join(expand_word(node.word, self.state, globbing=False,
162
+ splitting=False, braces=False))
163
+ for patterns, body in node.arms:
164
+ for pattern in patterns:
165
+ if glob_match(expand_pattern(pattern, self.state), word):
166
+ return self.run_list(body) if body else 0
167
+ return 0
168
+
169
+ # --- functions ---
170
+ def call_function(self, name: str, args: List[str]) -> int:
171
+ state = self.state
172
+ if state.func_depth >= 200:
173
+ raise ShellError(f"{name}: maximum function nesting level exceeded")
174
+ body = state.functions[name]
175
+ saved = state.positional
176
+ state.positional = list(args)
177
+ frame: Dict[str, Optional[str]] = {}
178
+ state.local_frames.append(frame)
179
+ state.func_depth += 1
180
+ try:
181
+ return self.run_list(body)
182
+ except ReturnFromFunction as r:
183
+ return r.status
184
+ finally:
185
+ state.func_depth -= 1
186
+ state.local_frames.pop()
187
+ for var, old in frame.items():
188
+ if old is None:
189
+ state.unset_variable(var)
190
+ else:
191
+ state.set_variable(var, old)
192
+ state.positional = saved
193
+
194
+ def run_argv(self, argv: List[str]) -> int:
195
+ """Run one command whose words are already expanded. Used by env and exec."""
196
+ name = argv[0]
197
+ if name in self.state.functions:
198
+ return self.call_function(name, argv[1:])
199
+ func = find_builtin(name)
200
+ if func is not None:
201
+ return func(self.state, argv[1:], sys.stdout, sys.stderr)
202
+ return self.dispatch([argv], [None], [[]], False)
203
+
204
+ def dispatch(self, argvs, envs, ops, background) -> int:
205
+ try:
206
+ if compat.HAS_FORK:
207
+ command = " | ".join(" ".join(a) for a in argvs)
208
+ return self.run_forked(argvs, envs, ops, background, command)
209
+ return self.run_portable(argvs, envs, ops, background)
210
+ except OSError as e:
211
+ print(f"{e.filename or 'error'}: {e.strerror}", file=sys.stderr)
212
+ return 1
213
+
214
+ def is_inprocess(self, name: str) -> bool:
215
+ return name in self.state.functions or find_builtin(name) is not None
216
+
217
+ def run_body(self, body: List[ListItem]) -> Optional[int]:
218
+ """Run one pass of a loop. Returns the status, or None when the loop must stop.
219
+ break and continue arrive as exceptions. Counts above 1 reach the outer loop."""
220
+ try:
221
+ return self.run_list(body)
222
+ except BreakLoop as e:
223
+ if e.levels > 1:
224
+ raise BreakLoop(e.levels - 1)
225
+ return None
226
+ except ContinueLoop as e:
227
+ if e.levels > 1:
228
+ raise ContinueLoop(e.levels - 1)
229
+ return self.state.last_status
230
+
231
+ def run_while(self, node: WhileClause) -> int:
232
+ status = 0
233
+ self.state.loop_depth += 1
234
+ try:
235
+ while True:
236
+ cond = self.run_condition(node.cond)
237
+ if cond == SIGINT_STATUS:
238
+ return cond # Ctrl+C killed the command, so the loop stops too
239
+ if (cond == 0) == node.until:
240
+ break
241
+ result = self.run_body(node.body)
242
+ if result is None:
243
+ return 0
244
+ status = result
245
+ if status == SIGINT_STATUS:
246
+ break
247
+ finally:
248
+ self.state.loop_depth -= 1
249
+ return status
250
+
251
+ def run_for(self, node: ForClause) -> int:
252
+ status = 0
253
+ values = (list(self.state.positional) if node.words is None
254
+ else expand_tokens(node.words, self.state))
255
+ self.state.loop_depth += 1
256
+ try:
257
+ for value in values:
258
+ self.state.set_variable(node.name, value)
259
+ result = self.run_body(node.body)
260
+ if result is None:
261
+ return 0
262
+ status = result
263
+ if status == SIGINT_STATUS:
264
+ break
265
+ finally:
266
+ self.state.loop_depth -= 1
267
+ return status
268
+
269
+ # --- pipelines ---
270
+ def run_pipeline(self, pipeline: Pipeline) -> int:
271
+ commands = pipeline.commands
272
+
273
+ # Peel leading NAME=value words off each command.
274
+ assigns: List[List[Tuple[str, Token]]] = []
275
+ word_tokens: List[List[Token]] = []
276
+ for cmd in commands:
277
+ found: List[Tuple[str, Token]] = []
278
+ rest = list(cmd.argv)
279
+ while rest:
280
+ parsed = split_assignment(rest[0])
281
+ if parsed is None:
282
+ break
283
+ found.append(parsed)
284
+ rest.pop(0)
285
+ assigns.append(found)
286
+ word_tokens.append(rest)
287
+
288
+ argvs = [expand_tokens(t, self.state) for t in word_tokens]
289
+ if "xtrace" in self.state.options:
290
+ for argv in argvs:
291
+ if argv:
292
+ print("+ " + " ".join(argv), file=sys.stderr)
293
+ envs: List[Optional[Dict[str, str]]] = [
294
+ {name: expand_value(tok, self.state) for name, tok in found} or None
295
+ for found in assigns
296
+ ]
297
+ ops = [self.resolve_redirects(c.redirects) for c in commands]
298
+
299
+ try:
300
+ if len(argvs) == 1:
301
+ argv = argvs[0]
302
+ if not argv:
303
+ # Only assignments and/or redirects. `> file` creates the file and
304
+ # `NAME=value` sets a shell variable.
305
+ opened: list = []
306
+ try:
307
+ apply_redirects(ops[0], {0: None, 1: None, 2: None}, opened)
308
+ finally:
309
+ for f in opened:
310
+ f.close()
311
+ for name, value in (envs[0] or {}).items():
312
+ self.state.set_variable(name, value)
313
+ return 0
314
+ # A lone builtin or function runs in the shell itself, so cd, alias and exit work.
315
+ if not pipeline.background or not compat.HAS_FORK:
316
+ if argv[0] in self.state.functions:
317
+ return self.run_function(argv[0], argv[1:], ops[0], envs[0])
318
+ func = find_builtin(argv[0])
319
+ if func is not None:
320
+ return self.run_builtin(func, argv[1:], ops[0], envs[0])
321
+ if any(not argv for argv in argvs):
322
+ return 0
323
+ if compat.HAS_FORK:
324
+ command = " | ".join(" ".join(a) for a in argvs)
325
+ return self.run_forked(argvs, envs, ops, pipeline.background, command)
326
+ return self.run_portable(argvs, envs, ops, pipeline.background)
327
+ except OSError as e:
328
+ # A redirect target could not be opened, or fork failed.
329
+ print(f"{e.filename or 'error'}: {e.strerror}", file=sys.stderr)
330
+ return 1
331
+
332
+ def resolve_redirects(self, redirects: List[Redirect]) -> List[RedirectOp]:
333
+ """Expand file names and here-strings. Runs in the shell, before any fork."""
334
+ ops: List[RedirectOp] = []
335
+ for red in redirects:
336
+ if red.target is None:
337
+ ops.append(RedirectOp({">&2": "1>&2", ">&1": "1>&1"}.get(red.op, red.op)))
338
+ elif red.op == "<<<":
339
+ ops.append(RedirectOp("<<<", expand_value(red.target, self.state) + "\n"))
340
+ elif red.op in ("<<", "<<-"):
341
+ # A quoted delimiter means the body is taken literally.
342
+ body = red.body if red.target.quoted else expand_heredoc(red.body, self.state)
343
+ ops.append(RedirectOp("<<<", body))
344
+ else:
345
+ names = expand_word(red.target, self.state)
346
+ if len(names) != 1:
347
+ raise ShellError(f"{red.target.text}: ambiguous redirect")
348
+ ops.append(RedirectOp({">": "1>", ">>": "1>>"}.get(red.op, red.op), names[0]))
349
+ return ops
350
+
351
+ # --- a lone builtin runs inside the shell process ---
352
+ def run_builtin(self, func, args: List[str], ops: List[RedirectOp],
353
+ env: Optional[Dict[str, str]] = None) -> int:
354
+ opened: list = []
355
+ saved = {k: os.environ.get(k) for k in env} if env else {}
356
+ saved_stdin = self.state.stdin
357
+ try:
358
+ table: Dict[int, object] = {0: self.state.input_stream(), 1: sys.stdout, 2: sys.stderr}
359
+ apply_redirects(ops, table, opened)
360
+ if env:
361
+ os.environ.update(env) # NAME=value before a builtin lasts for that call only
362
+ self.state.stdin = table[0]
363
+ return func(self.state, args, table[1], table[2])
364
+ finally:
365
+ self.state.stdin = saved_stdin
366
+ self.restore_env(saved)
367
+ for f in opened:
368
+ f.close()
369
+
370
+ @staticmethod
371
+ def restore_env(saved: Dict[str, Optional[str]]) -> None:
372
+ for k, v in saved.items():
373
+ if v is None:
374
+ os.environ.pop(k, None)
375
+ else:
376
+ os.environ[k] = v
377
+
378
+ def run_function(self, name: str, args: List[str], ops: List[RedirectOp],
379
+ env: Optional[Dict[str, str]] = None) -> int:
380
+ """A function runs in the shell. Redirects apply to file descriptors 0, 1 and 2,
381
+ so the programs it starts see them too."""
382
+ saved = {k: os.environ.get(k) for k in env} if env else {}
383
+ try:
384
+ if env:
385
+ os.environ.update(env)
386
+ with self.fd_redirects(ops):
387
+ return self.call_function(name, args)
388
+ finally:
389
+ self.restore_env(saved)
390
+
391
+ @contextmanager
392
+ def fd_redirects(self, ops: List[RedirectOp]):
393
+ if not ops:
394
+ yield
395
+ return
396
+ opened: list = []
397
+ table: Dict[int, object] = {0: 0, 1: 1, 2: 2}
398
+ copies: List[int] = []
399
+ saved: Dict[int, int] = {}
400
+ try:
401
+ apply_redirects(ops, table, opened)
402
+ sys.stdout.flush()
403
+ sys.stderr.flush()
404
+ sources: Dict[int, int] = {}
405
+ for target in (0, 1, 2):
406
+ handle = table[target]
407
+ src = handle if isinstance(handle, int) else handle.fileno()
408
+ if src in (0, 1, 2) and src != target:
409
+ src = os.dup(src) # copy first, so 2>&1 > f keeps the old stdout
410
+ copies.append(src)
411
+ sources[target] = src
412
+ for target in (0, 1, 2):
413
+ if sources[target] != target:
414
+ saved[target] = os.dup(target)
415
+ os.dup2(sources[target], target)
416
+ yield
417
+ finally:
418
+ try:
419
+ sys.stdout.flush()
420
+ sys.stderr.flush()
421
+ except Exception:
422
+ pass
423
+ for target, fd in saved.items():
424
+ os.dup2(fd, target)
425
+ os.close(fd)
426
+ for fd in copies:
427
+ os.close(fd)
428
+ for f in opened:
429
+ f.close()
430
+
431
+ # --- Unix: fork, pipe, process groups ---
432
+ def run_forked(self, cmds: List[List[str]], envs: List[Optional[Dict[str, str]]],
433
+ ops: List[List[RedirectOp]], background: bool, command: str) -> int:
434
+ jc = self.state.jobs
435
+ # Flush first so buffered text is not copied into every child.
436
+ sys.stdout.flush()
437
+ sys.stderr.flush()
438
+
439
+ n = len(cmds)
440
+ pipes: List[Tuple[int, int]] = []
441
+ opened: list = []
442
+ devnull: Optional[int] = None
443
+ pids: List[int] = []
444
+ pgid = 0
445
+ try:
446
+ for _ in range(n - 1):
447
+ pipes.append(os.pipe())
448
+ if background and not jc.interactive:
449
+ devnull = os.open(os.devnull, os.O_RDONLY) # background jobs get no input
450
+
451
+ # Work out what fds 0, 1 and 2 of each command point to. Every redirect target
452
+ # opens before anything starts, so one bad file name stops the whole pipeline.
453
+ tables: List[Dict[int, int]] = []
454
+ for i in range(n):
455
+ table: Dict[int, object] = {
456
+ 0: pipes[i - 1][0] if i else (devnull if devnull is not None else 0),
457
+ 1: pipes[i][1] if i < n - 1 else 1,
458
+ 2: 2,
459
+ }
460
+ apply_redirects(ops[i], table, opened)
461
+ tables.append({fd: h if isinstance(h, int) else h.fileno()
462
+ for fd, h in table.items()})
463
+
464
+ # Children close every pipe end and file they do not use, or readers
465
+ # would never see end of input.
466
+ inherited = {fd for pair in pipes for fd in pair}
467
+ inherited.update(f.fileno() for f in opened)
468
+ if devnull is not None:
469
+ inherited.add(devnull)
470
+ inherited = {fd for fd in inherited if fd > 2}
471
+
472
+ for i, argv in enumerate(cmds):
473
+ pid = os.fork()
474
+ if pid == 0:
475
+ self._run_child(argv, tables[i], inherited, pgid,
476
+ not background, envs[i]) # never returns
477
+
478
+ # Parent. Both sides call setpgid so the group exists whoever runs first.
479
+ if pgid == 0:
480
+ pgid = pid
481
+ if jc.interactive:
482
+ try:
483
+ os.setpgid(pid, pgid)
484
+ except OSError:
485
+ pass
486
+ pids.append(pid)
487
+ finally:
488
+ for pair in pipes:
489
+ for fd in pair:
490
+ try:
491
+ os.close(fd)
492
+ except OSError:
493
+ pass
494
+ if devnull is not None:
495
+ os.close(devnull)
496
+ for f in opened:
497
+ f.close()
498
+
499
+ job = jc.add(pgid, pids, command, background)
500
+ if background:
501
+ jc.put_in_background(job)
502
+ return 0
503
+ status = jc.put_in_foreground(job)
504
+ if status == 127 and n == 1:
505
+ self.state.missing_command = cmds[0][0] # lets the guide offer a hint
506
+ return status
507
+
508
+ def _run_child(self, argv: List[str], table: Dict[int, int],
509
+ inherited: Set[int], pgid: int, foreground: bool,
510
+ env: Optional[Dict[str, str]] = None) -> None:
511
+ """Runs in the forked child. Never returns."""
512
+ status = 1
513
+ try:
514
+ jc = self.state.jobs
515
+ if jc.interactive:
516
+ os.setpgid(0, pgid) # pgid 0 makes this process the group leader
517
+ if foreground:
518
+ try:
519
+ os.tcsetpgrp(jc.tty, os.getpgrp())
520
+ except OSError:
521
+ pass
522
+ for sig in CHILD_RESET_SIGNALS:
523
+ signal.signal(sig, signal.SIG_DFL)
524
+
525
+ # table[t] is the parent fd that becomes fd t. When a source is itself fd 0, 1
526
+ # or 2, copy it first. Otherwise `2>&1 > file` would lose the original stdout.
527
+ sources: Dict[int, int] = {}
528
+ copies: Set[int] = set()
529
+ for target in (0, 1, 2):
530
+ src = table[target]
531
+ if src in (0, 1, 2) and src != target:
532
+ src = os.dup(src)
533
+ copies.add(src)
534
+ sources[target] = src
535
+ for target in (0, 1, 2):
536
+ if sources[target] != target:
537
+ os.dup2(sources[target], target)
538
+ for fd in inherited | copies:
539
+ try:
540
+ os.close(fd) # open pipe ends would keep readers from seeing EOF
541
+ except OSError:
542
+ pass
543
+ # Fresh file objects, so builtins and error messages reach fds 1 and 2
544
+ # even if sys.stdout or sys.stderr were replaced.
545
+ sys.stdout = os.fdopen(1, "w", closefd=False)
546
+ sys.stderr = os.fdopen(2, "w", buffering=1, closefd=False)
547
+
548
+ sys.stdin = os.fdopen(0, "r", closefd=False)
549
+ self.state.stdin = None
550
+ self.state.jobs.interactive = False
551
+ func = find_builtin(argv[0]) if argv[0] not in self.state.functions else None
552
+ if func is not None or argv[0] in self.state.functions:
553
+ if env:
554
+ os.environ.update(env) # this is a child, so no need to restore
555
+ try:
556
+ if func is not None:
557
+ status = func(self.state, argv[1:], sys.stdout, sys.stderr)
558
+ else:
559
+ status = self.call_function(argv[0], argv[1:])
560
+ except ShellExit as e:
561
+ status = e.code
562
+ except ShellError as e:
563
+ print(e, file=sys.stderr)
564
+ status = 2
565
+ elif env:
566
+ os.execvpe(argv[0], argv, {**os.environ, **env})
567
+ else:
568
+ os.execvp(argv[0], argv)
569
+ except FileNotFoundError:
570
+ reason = "No such file or directory" if "/" in argv[0] else "command not found"
571
+ try:
572
+ print(f"{argv[0]}: {reason}", file=sys.stderr)
573
+ except Exception:
574
+ pass
575
+ status = 127
576
+ except OSError as e:
577
+ try:
578
+ print(f"{argv[0]}: {e.strerror}", file=sys.stderr)
579
+ except Exception:
580
+ pass
581
+ status = 126
582
+ except BaseException:
583
+ status = 1
584
+ finally:
585
+ try:
586
+ sys.stdout.flush()
587
+ sys.stderr.flush()
588
+ except Exception:
589
+ pass
590
+ os._exit(status & 0xFF)
591
+
592
+ # --- Windows and other platforms without fork ---
593
+ def run_portable(self, cmds: List[List[str]], envs: List[Optional[Dict[str, str]]],
594
+ ops: List[List[RedirectOp]], background: bool) -> int:
595
+ sys.stdout.flush()
596
+ sys.stderr.flush()
597
+ if any(self.is_inprocess(c[0]) for c in cmds):
598
+ return self.run_portable_buffered(cmds, envs, ops)
599
+ n = len(cmds)
600
+ opened: list = []
601
+ processes: List[subprocess.Popen] = []
602
+ prev = None # stdin for the next command
603
+ last_failure = None # status when the last command could not start
604
+ try:
605
+ # Open every redirect target first, so a bad file name starts nothing.
606
+ tables: List[Dict[int, object]] = []
607
+ for i in range(n):
608
+ table: Dict[int, object] = {
609
+ 0: None, # None means the previous pipe, or the shell's own stdin
610
+ 1: subprocess.PIPE if i < n - 1 else sys.stdout,
611
+ 2: sys.stderr,
612
+ }
613
+ apply_redirects(ops[i], table, opened)
614
+ tables.append(table)
615
+
616
+ for i, cmd in enumerate(cmds):
617
+ is_last = i == n - 1
618
+ table = tables[i]
619
+ try:
620
+ p = subprocess.Popen(
621
+ cmd,
622
+ stdin=table[0] if table[0] is not None else prev,
623
+ stdout=table[1],
624
+ stderr=table[2],
625
+ env={**os.environ, **envs[i]} if envs[i] else None,
626
+ )
627
+ except (FileNotFoundError, PermissionError, NotADirectoryError) as e:
628
+ if isinstance(e, FileNotFoundError):
629
+ reason = ("No such file or directory" if "/" in cmd[0]
630
+ else "command not found")
631
+ status = 127
632
+ else:
633
+ reason = "Permission denied"
634
+ status = 126
635
+ print(f"{cmd[0]}: {reason}", file=sys.stderr)
636
+ p, last_failure = None, (status if is_last else None)
637
+ if hasattr(prev, "close"):
638
+ prev.close()
639
+ if p is None:
640
+ prev = subprocess.DEVNULL # next stage reads empty input
641
+ else:
642
+ prev = p.stdout
643
+ processes.append(p)
644
+ finally:
645
+ if hasattr(prev, "close"):
646
+ prev.close()
647
+ for f in opened:
648
+ f.close()
649
+
650
+ if background:
651
+ if processes:
652
+ self.state.background_jobs.append(processes[-1])
653
+ print(f"[{len(self.state.background_jobs)}] {processes[-1].pid}")
654
+ return last_failure or 0
655
+
656
+ try:
657
+ for p in processes:
658
+ p.wait()
659
+ except KeyboardInterrupt:
660
+ for p in processes:
661
+ p.wait()
662
+ print()
663
+ return 130
664
+
665
+ if last_failure is not None:
666
+ return last_failure
667
+ return exit_status(processes[-1].returncode)
668
+
669
+ def run_portable_buffered(self, cmds: List[List[str]], envs: List[Optional[Dict[str, str]]],
670
+ ops: List[List[RedirectOp]]) -> int:
671
+ """A pipeline with builtins or functions, where there is no fork. Stages run one
672
+ after another and hand their whole output to the next stage."""
673
+ n = len(cmds)
674
+ opened: list = []
675
+ status = 0
676
+ data: Optional[bytes] = None # output of the previous stage
677
+ try:
678
+ tables: List[Dict[int, object]] = []
679
+ for i in range(n):
680
+ table: Dict[int, object] = {
681
+ 0: None,
682
+ 1: subprocess.PIPE if i < n - 1 else sys.stdout,
683
+ 2: sys.stderr,
684
+ }
685
+ apply_redirects(ops[i], table, opened)
686
+ tables.append(table)
687
+ for i, argv in enumerate(cmds):
688
+ table = tables[i]
689
+ piped = table[1] == subprocess.PIPE
690
+ if self.is_inprocess(argv[0]):
691
+ if table[0] is not None:
692
+ stdin = table[0]
693
+ elif data is not None:
694
+ stdin = io.StringIO(data.decode(errors="replace"))
695
+ else:
696
+ stdin = sys.stdin
697
+ out = io.StringIO() if piped else table[1]
698
+ err = out if table[2] == subprocess.STDOUT else table[2]
699
+ saved = {k: os.environ.get(k) for k in envs[i]} if envs[i] else {}
700
+ saved_stdin = self.state.stdin
701
+ self.state.stdin = stdin
702
+ try:
703
+ if envs[i]:
704
+ os.environ.update(envs[i])
705
+ func = None if argv[0] in self.state.functions else find_builtin(argv[0])
706
+ if func is not None:
707
+ status = func(self.state, argv[1:], out, err)
708
+ else:
709
+ status = self.call_function(argv[0], argv[1:])
710
+ except ShellExit as e:
711
+ status = e.code
712
+ finally:
713
+ self.state.stdin = saved_stdin
714
+ self.restore_env(saved)
715
+ try:
716
+ out.flush()
717
+ except Exception:
718
+ pass
719
+ data = out.getvalue().encode() if piped else None
720
+ continue
721
+ feed = table[0] is None and data is not None
722
+ try:
723
+ p = subprocess.Popen(
724
+ argv,
725
+ stdin=subprocess.PIPE if feed else table[0],
726
+ stdout=table[1], stderr=table[2],
727
+ env={**os.environ, **envs[i]} if envs[i] else None,
728
+ )
729
+ except (FileNotFoundError, PermissionError, NotADirectoryError) as e:
730
+ if isinstance(e, FileNotFoundError):
731
+ reason = "No such file or directory" if "/" in argv[0] else "command not found"
732
+ status = 127
733
+ else:
734
+ reason, status = "Permission denied", 126
735
+ print(f"{argv[0]}: {reason}", file=sys.stderr)
736
+ data = b"" if piped else None
737
+ continue
738
+ try:
739
+ out_bytes, _ = p.communicate(data if feed else None)
740
+ except KeyboardInterrupt:
741
+ p.wait()
742
+ print()
743
+ return 130
744
+ status = exit_status(p.returncode)
745
+ data = out_bytes if piped else None
746
+ except KeyboardInterrupt:
747
+ print()
748
+ return 130
749
+ finally:
750
+ for f in opened:
751
+ f.close()
752
+ return status