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/highlight.py ADDED
@@ -0,0 +1,227 @@
1
+ """Syntax coloring for the line editor. No prompt_toolkit import here.
2
+
3
+ tokenize_for_color() cuts a line into (style_class, text) pieces. The pieces always join
4
+ back to the exact input, and half-typed input (an open quote, "$(", a trailing
5
+ backslash) never raises."""
6
+ import re
7
+ from typing import Callable, Dict, List, Tuple
8
+
9
+ STYLES: Dict[str, str] = {
10
+ "command": "fg:ansigreen",
11
+ "badcommand": "fg:ansired",
12
+ "keyword": "fg:ansiblue bold",
13
+ "string": "fg:ansiyellow",
14
+ "variable": "fg:ansicyan",
15
+ "operator": "fg:ansimagenta",
16
+ "comment": "fg:ansibrightblack",
17
+ "plain": "",
18
+ }
19
+
20
+ KEYWORDS = frozenset("if then elif else fi while until for do done in case esac function { }".split())
21
+ # After these, the next word is a command again.
22
+ OPENERS = frozenset("then do else if elif while until {".split())
23
+ OPERATORS = ("&>>", "2>&1", "1>&2", "<<<", "<<-", "2>>", "1>>", "&&", "||", ";;", "&>", "<<",
24
+ ">>", ">&", "<&", "2>", "1>", "|", "&", ";", ">", "<")
25
+ WORD_END = " \t\r\n|&;<>()"
26
+ VAR_RE = re.compile(r"\$(\{[^}]*\}?|[A-Za-z_][A-Za-z0-9_]*|[0-9@?$!#*-])")
27
+ ASSIGN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\+?=")
28
+
29
+ Fragment = Tuple[str, str]
30
+
31
+
32
+ def _skip_parens(text: str, i: int) -> int:
33
+ """text[i] is '(' after '$'. Return the index just past the matching ')' (or the end)."""
34
+ depth = 0
35
+ quote = ""
36
+ n = len(text)
37
+ while i < n:
38
+ c = text[i]
39
+ if quote:
40
+ if c == "\\" and quote == '"':
41
+ i += 1
42
+ elif c == quote:
43
+ quote = ""
44
+ elif c == "\\":
45
+ i += 1
46
+ elif c in "'\"":
47
+ quote = c
48
+ elif c == "(":
49
+ depth += 1
50
+ elif c == ")":
51
+ depth -= 1
52
+ if depth == 0:
53
+ return i + 1
54
+ i += 1
55
+ return n
56
+
57
+
58
+ def _read_word(text: str, i: int) -> Tuple[int, List[Fragment], bool]:
59
+ """Read one shell word starting at i. Returns (end, fragments, is_simple); simple
60
+ means no quotes, escapes or expansions."""
61
+ frags: List[Fragment] = []
62
+ n = len(text)
63
+ simple = True
64
+ plain_start = i
65
+
66
+ def flush(upto: int) -> None:
67
+ if upto > plain_start:
68
+ frags.append(("plain", text[plain_start:upto]))
69
+
70
+ while i < n:
71
+ c = text[i]
72
+ if c in WORD_END:
73
+ break
74
+ if c == "\\":
75
+ simple = False
76
+ i = min(i + 2, n)
77
+ elif c == "'":
78
+ simple = False
79
+ flush(i)
80
+ end = text.find("'", i + 1)
81
+ end = n if end < 0 else end + 1
82
+ frags.append(("string", text[i:end]))
83
+ i = plain_start = end
84
+ elif c == '"':
85
+ simple = False
86
+ flush(i)
87
+ j = i + 1
88
+ seg = i
89
+ while j < n and text[j] != '"':
90
+ if text[j] == "\\":
91
+ j += 2
92
+ continue
93
+ m = VAR_RE.match(text, j) if text[j] == "$" else None
94
+ if m:
95
+ if j > seg:
96
+ frags.append(("string", text[seg:j]))
97
+ frags.append(("variable", m.group()))
98
+ j = seg = m.end()
99
+ elif text.startswith("$(", j):
100
+ j = _skip_parens(text, j + 1)
101
+ else:
102
+ j += 1
103
+ end = min(j + 1, n)
104
+ if end > seg:
105
+ frags.append(("string", text[seg:end]))
106
+ i = plain_start = end
107
+ elif c == "`":
108
+ simple = False
109
+ end = text.find("`", i + 1)
110
+ i = n if end < 0 else end + 1
111
+ elif c == "$":
112
+ simple = False
113
+ if text.startswith("$(", i):
114
+ i = _skip_parens(text, i + 1)
115
+ continue
116
+ m = VAR_RE.match(text, i)
117
+ if m:
118
+ flush(i)
119
+ frags.append(("variable", m.group()))
120
+ i = plain_start = m.end()
121
+ else:
122
+ i += 1
123
+ else:
124
+ i += 1
125
+ flush(i)
126
+ return i, frags, simple
127
+
128
+
129
+ def _merge(frags: List[Fragment]) -> List[Fragment]:
130
+ out: List[Fragment] = []
131
+ for cls, s in frags:
132
+ if not s:
133
+ continue
134
+ if out and out[-1][0] == cls:
135
+ out[-1] = (cls, out[-1][1] + s)
136
+ else:
137
+ out.append((cls, s))
138
+ return out
139
+
140
+
141
+ def _tokenize(text: str, kind_of: Callable[[str], str]) -> List[Fragment]:
142
+ out: List[Fragment] = []
143
+ n = len(text)
144
+ i = 0
145
+ at_cmd = True
146
+ pending = 0 # for/case: variable word, then "in"
147
+ after_function = False
148
+ while i < n:
149
+ c = text[i]
150
+ if c in " \t\r":
151
+ j = i
152
+ while j < n and text[j] in " \t\r":
153
+ j += 1
154
+ out.append(("plain", text[i:j]))
155
+ i = j
156
+ continue
157
+ if c == "\n":
158
+ out.append(("plain", c))
159
+ i += 1
160
+ at_cmd = True
161
+ pending = 0
162
+ continue
163
+ if c == "#":
164
+ j = text.find("\n", i)
165
+ j = n if j < 0 else j
166
+ out.append(("comment", text[i:j]))
167
+ i = j
168
+ continue
169
+ op = next((o for o in OPERATORS if text.startswith(o, i)), None)
170
+ if op:
171
+ out.append(("operator", op))
172
+ i += len(op)
173
+ if op in ("|", "||", "&&", ";", ";;", "&"):
174
+ at_cmd = True
175
+ pending = 0
176
+ continue
177
+ if c in "()":
178
+ out.append(("plain", c))
179
+ i += 1
180
+ at_cmd = True # after "(" or "f()" a command follows
181
+ continue
182
+ end, frags, simple = _read_word(text, i)
183
+ if end == i: # cannot happen, but never loop forever
184
+ end = i + 1
185
+ frags = [("plain", text[i:end])]
186
+ word = text[i:end]
187
+ i = end
188
+ if pending == 2:
189
+ out.extend(frags)
190
+ pending = 1
191
+ at_cmd = False
192
+ elif pending == 1 and word == "in":
193
+ out.append(("keyword", word))
194
+ pending = 0
195
+ elif after_function:
196
+ out.extend(frags)
197
+ after_function = False
198
+ at_cmd = True # "{" or "()" follows
199
+ elif at_cmd and simple and word in KEYWORDS:
200
+ out.append(("keyword", word))
201
+ at_cmd = word in OPENERS
202
+ if word in ("for", "case"):
203
+ pending = 2
204
+ at_cmd = False
205
+ elif word == "function":
206
+ after_function = True
207
+ elif at_cmd and simple and ASSIGN_RE.match(word):
208
+ out.extend(frags) # NAME=value stays at command position
209
+ elif at_cmd and simple:
210
+ out.append(("command" if kind_of(word) == "command" else "badcommand", word))
211
+ at_cmd = False
212
+ else:
213
+ out.extend(frags)
214
+ at_cmd = False
215
+ return out
216
+
217
+
218
+ def tokenize_for_color(text: str, kind_of: Callable[[str], str]) -> List[Tuple[str, str]]:
219
+ """Cut `text` into (style_class, text) pieces that join back to `text`.
220
+ kind_of(word) returns "command" for a known command and anything else otherwise."""
221
+ try:
222
+ result = _merge(_tokenize(text, kind_of))
223
+ if "".join(s for _, s in result) == text:
224
+ return result
225
+ except Exception:
226
+ pass
227
+ return [("plain", text)] if text else []
myshell/history.py ADDED
@@ -0,0 +1,123 @@
1
+ """Command history that works with or without a full readline.
2
+
3
+ On Linux and macOS the readline module keeps the history, and input() records each
4
+ line itself. On Windows the readline module comes from pyreadline3 and lacks several
5
+ functions, or is missing. There the shell keeps its own list and file.
6
+
7
+ Code elsewhere reads `native` when it runs, so tests can switch modes."""
8
+ import os
9
+ from typing import List, Optional
10
+
11
+ try:
12
+ import readline as _rl
13
+ except ImportError: # no readline at all
14
+ _rl = None
15
+
16
+ MAX_ENTRIES = 1000
17
+ _NEEDED = ("get_current_history_length", "get_history_item", "add_history",
18
+ "clear_history", "remove_history_item", "read_history_file",
19
+ "write_history_file", "set_history_length")
20
+
21
+ # True when readline can do everything, and the platform is not Windows.
22
+ native = (_rl is not None and os.name != "nt"
23
+ and all(hasattr(_rl, name) for name in _NEEDED))
24
+
25
+ _entries: List[str] = [] # used when native is False
26
+
27
+
28
+ def use_builtin() -> None:
29
+ """Switch to the shell's own list, so a line editor other than readline can use it."""
30
+ global native
31
+ if native: # keep what readline already holds
32
+ _entries[:] = [_rl.get_history_item(i)
33
+ for i in range(1, _rl.get_current_history_length() + 1)][-MAX_ENTRIES:]
34
+ native = False
35
+
36
+
37
+ def entries() -> List[str]:
38
+ """All entries, oldest first."""
39
+ if native:
40
+ return [_rl.get_history_item(i) for i in range(1, _rl.get_current_history_length() + 1)]
41
+ return list(_entries)
42
+
43
+
44
+ def records_input() -> bool:
45
+ """True when input() adds each typed line to the history by itself."""
46
+ return native
47
+
48
+
49
+ def add(line: str) -> None:
50
+ if native:
51
+ _rl.add_history(line)
52
+ else:
53
+ _entries.append(line)
54
+ del _entries[:-MAX_ENTRIES]
55
+
56
+
57
+ def length() -> int:
58
+ return _rl.get_current_history_length() if native else len(_entries)
59
+
60
+
61
+ def item(position: int) -> str:
62
+ """The entry at a 1-based position."""
63
+ return _rl.get_history_item(position) if native else _entries[position - 1]
64
+
65
+
66
+ def clear() -> None:
67
+ if native:
68
+ _rl.clear_history()
69
+ else:
70
+ _entries.clear()
71
+
72
+
73
+ def remove(position: int) -> None:
74
+ """Remove the entry at a 1-based position."""
75
+ if native:
76
+ _rl.remove_history_item(position - 1)
77
+ else:
78
+ del _entries[position - 1]
79
+
80
+
81
+ def forget_last() -> None:
82
+ """Drop the newest entry. The guide uses it to keep menu answers out of the history."""
83
+ if length():
84
+ remove(length())
85
+
86
+
87
+ def write(path: str) -> None:
88
+ if native:
89
+ try:
90
+ _rl.write_history_file(path)
91
+ except Exception:
92
+ pass # some readline builds fail here or write nothing. Check below.
93
+ if os.path.exists(path):
94
+ return
95
+ with open(path, "w", encoding="utf-8") as f:
96
+ f.writelines(line.replace("\n", " ") + "\n" for line in entries())
97
+
98
+
99
+ def read(path: str) -> None:
100
+ """Add the entries of a history file to the current history."""
101
+ if native:
102
+ try:
103
+ _rl.read_history_file(path)
104
+ return
105
+ except OSError:
106
+ if not os.path.exists(path):
107
+ raise # no file yet
108
+ with open(path, encoding="utf-8") as f:
109
+ for line in f.read().splitlines():
110
+ if line:
111
+ add(line)
112
+
113
+
114
+ def set_limit(limit: int = MAX_ENTRIES) -> None:
115
+ if native:
116
+ _rl.set_history_length(limit)
117
+ else:
118
+ del _entries[:-limit]
119
+
120
+
121
+ def readline_module() -> Optional[object]:
122
+ """The readline module for completion, or None."""
123
+ return _rl
myshell/jobs.py ADDED
@@ -0,0 +1,254 @@
1
+ """Job control for Unix: process groups, the terminal, fg, bg and wait."""
2
+ import os
3
+ import signal
4
+ import sys
5
+ from dataclasses import dataclass, field
6
+ from typing import Dict, List, Optional, Set
7
+
8
+ from . import compat
9
+ from .errors import ShellError
10
+
11
+
12
+ # Signals the shell ignores or handles itself. Children must restore the defaults.
13
+ CHILD_RESET_SIGNALS = [
14
+ getattr(signal, n) for n in
15
+ ("SIGINT", "SIGQUIT", "SIGTSTP", "SIGTTIN", "SIGTTOU", "SIGCHLD", "SIGPIPE", "SIGXFSZ")
16
+ if hasattr(signal, n)
17
+ ]
18
+
19
+
20
+ @dataclass
21
+ class Job:
22
+ pgid: int
23
+ pids: List[int]
24
+ command: str
25
+ status: Dict[int, Optional[int]] # pid -> exit status, None while alive
26
+ number: int = 0 # assigned when the job goes to the background
27
+ background: bool = False
28
+ notified: bool = False
29
+ term_signal: Optional[int] = None # signal that killed the last process
30
+ stopped_pids: Set[int] = field(default_factory=set)
31
+ tmodes: Optional[list] = None # terminal modes saved when the job stopped
32
+
33
+ @property
34
+ def completed(self) -> bool:
35
+ return all(s is not None for s in self.status.values())
36
+
37
+ @property
38
+ def stopped(self) -> bool:
39
+ if self.completed:
40
+ return False
41
+ return all(self.status[p] is not None or p in self.stopped_pids for p in self.pids)
42
+
43
+ @property
44
+ def last_status(self) -> int:
45
+ return self.status[self.pids[-1]] or 0
46
+
47
+ def state_text(self) -> str:
48
+ if self.completed:
49
+ if self.term_signal is not None:
50
+ return signal.strsignal(self.term_signal) or f"Signal {self.term_signal}"
51
+ return "Done" if self.last_status == 0 else f"Exit {self.last_status}"
52
+ return "Stopped" if self.stopped else "Running"
53
+
54
+
55
+ class JobControl:
56
+ def __init__(self):
57
+ self.jobs: List[Job] = []
58
+ self.interactive = False
59
+ self.tty = -1
60
+ self.shell_pgid = 0
61
+ self.shell_tmodes = None
62
+
63
+ # --- terminal setup ---
64
+ def init_terminal(self) -> None:
65
+ """Take control of the terminal. Skipped when stdin is not a terminal."""
66
+ if not compat.HAS_FORK or compat.termios is None:
67
+ return
68
+ try:
69
+ tty = sys.stdin.fileno()
70
+ if not os.isatty(tty):
71
+ return
72
+ # If the shell was started in the background, stop until it is foreground.
73
+ while os.tcgetpgrp(tty) != os.getpgrp():
74
+ os.killpg(os.getpgrp(), signal.SIGTTIN)
75
+ for sig in (signal.SIGQUIT, signal.SIGTSTP, signal.SIGTTIN, signal.SIGTTOU):
76
+ signal.signal(sig, signal.SIG_IGN)
77
+ pid = os.getpid()
78
+ try:
79
+ os.setpgid(pid, pid) # fails with EPERM for a session leader, which is fine
80
+ except OSError:
81
+ pass
82
+ self.shell_pgid = os.getpgrp()
83
+ os.tcsetpgrp(tty, self.shell_pgid)
84
+ self.shell_tmodes = compat.termios.tcgetattr(tty)
85
+ self.tty = tty
86
+ self.interactive = True
87
+ except (OSError, compat.termios.error):
88
+ self.interactive = False
89
+
90
+ # --- table ---
91
+ def add(self, pgid: int, pids: List[int], command: str, background: bool) -> Job:
92
+ job = Job(pgid, pids, command, {p: None for p in pids}, background=background)
93
+ self.jobs.append(job)
94
+ return job
95
+
96
+ def remove(self, job: Job) -> None:
97
+ if job in self.jobs:
98
+ self.jobs.remove(job)
99
+
100
+ def assign_number(self, job: Job) -> None:
101
+ if not job.number:
102
+ job.number = max([j.number for j in self.jobs], default=0) + 1
103
+
104
+ def numbered(self) -> List[Job]:
105
+ return [j for j in self.jobs if j.number]
106
+
107
+ def marker(self, job: Job) -> str:
108
+ nums = self.numbered()
109
+ if nums and job is nums[-1]:
110
+ return "+"
111
+ if len(nums) > 1 and job is nums[-2]:
112
+ return "-"
113
+ return " "
114
+
115
+ def format(self, job: Job) -> str:
116
+ suffix = " &" if job.background and not job.completed and not job.stopped else ""
117
+ return f"[{job.number}]{self.marker(job)} {job.state_text():<24}{job.command}{suffix}"
118
+
119
+ def find(self, spec: Optional[str]) -> Job:
120
+ nums = self.numbered()
121
+ if spec is None or spec in ("%", "%%", "%+"):
122
+ if not nums:
123
+ raise ShellError("no current job")
124
+ return nums[-1]
125
+ if spec == "%-":
126
+ if len(nums) < 2:
127
+ raise ShellError("no previous job")
128
+ return nums[-2]
129
+ text = spec[1:] if spec.startswith("%") else spec
130
+ if text.isdigit():
131
+ for j in nums:
132
+ if j.number == int(text):
133
+ return j
134
+ raise ShellError(f"{spec}: no such job")
135
+
136
+ # --- status tracking ---
137
+ def update(self, pid: int, st: int) -> None:
138
+ for job in self.jobs:
139
+ if pid not in job.status:
140
+ continue
141
+ if os.WIFSTOPPED(st):
142
+ job.stopped_pids.add(pid)
143
+ job.notified = False
144
+ elif os.WIFSIGNALED(st):
145
+ job.status[pid] = 128 + os.WTERMSIG(st)
146
+ if pid == job.pids[-1]:
147
+ job.term_signal = os.WTERMSIG(st)
148
+ else:
149
+ job.status[pid] = os.WEXITSTATUS(st)
150
+ return
151
+
152
+ def refresh(self) -> None:
153
+ """Collect finished or stopped children without blocking."""
154
+ if not compat.HAS_FORK:
155
+ return
156
+ while True:
157
+ try:
158
+ pid, st = os.waitpid(-1, os.WUNTRACED | os.WNOHANG)
159
+ except ChildProcessError:
160
+ break
161
+ if pid == 0:
162
+ break
163
+ self.update(pid, st)
164
+
165
+ def wait_for(self, job: Job, interruptible: bool = False) -> bool:
166
+ """Block until the job completes or stops. Returns True if interrupted."""
167
+ while not job.completed and not job.stopped:
168
+ try:
169
+ pid, st = os.waitpid(-1, os.WUNTRACED)
170
+ except ChildProcessError:
171
+ for p in job.pids: # children were reaped elsewhere
172
+ if job.status[p] is None:
173
+ job.status[p] = 0
174
+ break
175
+ except KeyboardInterrupt:
176
+ # Without a terminal the shell shares the job's process group, so it
177
+ # receives Ctrl+C too. The job dies from the same signal.
178
+ if interruptible:
179
+ return True
180
+ continue
181
+ self.update(pid, st)
182
+ return False
183
+
184
+ def notify(self) -> None:
185
+ """Report finished and stopped jobs. Called before each prompt."""
186
+ self.refresh()
187
+ for job in self.jobs[:]:
188
+ if job.completed:
189
+ if job.background and job.number:
190
+ print(self.format(job))
191
+ self.jobs.remove(job)
192
+ elif job.stopped and job.number and not job.notified:
193
+ print(self.format(job))
194
+ job.notified = True
195
+
196
+ # --- moving jobs between foreground and background ---
197
+ def _continue(self, job: Job) -> None:
198
+ job.stopped_pids.clear()
199
+ job.notified = False
200
+ try:
201
+ os.killpg(job.pgid, signal.SIGCONT)
202
+ except OSError:
203
+ pass
204
+
205
+ def put_in_foreground(self, job: Job, cont: bool = False) -> int:
206
+ job.background = False
207
+ if self.interactive:
208
+ try:
209
+ os.tcsetpgrp(self.tty, job.pgid)
210
+ except OSError:
211
+ pass
212
+ if cont:
213
+ if self.interactive and job.tmodes:
214
+ try:
215
+ compat.termios.tcsetattr(self.tty, compat.termios.TCSADRAIN, job.tmodes)
216
+ except compat.termios.error:
217
+ pass
218
+ self._continue(job)
219
+ self.wait_for(job)
220
+ if self.interactive:
221
+ try:
222
+ os.tcsetpgrp(self.tty, self.shell_pgid)
223
+ if job.stopped:
224
+ job.tmodes = compat.termios.tcgetattr(self.tty)
225
+ compat.termios.tcsetattr(self.tty, compat.termios.TCSADRAIN, self.shell_tmodes)
226
+ except (OSError, compat.termios.error):
227
+ pass
228
+
229
+ if job.completed:
230
+ self.remove(job)
231
+ sig = job.term_signal
232
+ # These notices go to stderr so they never end up in captured output.
233
+ if sig == signal.SIGINT:
234
+ if self.interactive:
235
+ print(file=sys.stderr)
236
+ elif sig is not None and sig != signal.SIGPIPE:
237
+ print(signal.strsignal(sig), file=sys.stderr)
238
+ return job.last_status
239
+
240
+ # The job stopped (Ctrl+Z). Keep it in the table.
241
+ self.assign_number(job)
242
+ job.notified = True
243
+ print()
244
+ print(self.format(job))
245
+ return 128 + signal.SIGTSTP
246
+
247
+ def put_in_background(self, job: Job, cont: bool = False) -> None:
248
+ job.background = True
249
+ self.assign_number(job)
250
+ if cont:
251
+ self._continue(job)
252
+ print(f"[{job.number}]{self.marker(job)} {job.command} &")
253
+ else:
254
+ print(f"[{job.number}] {job.pids[-1]}")