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/editor.py ADDED
@@ -0,0 +1,218 @@
1
+ """Optional line editor built on prompt_toolkit 3.x: Ctrl+R search, history suggestions,
2
+ syntax colors and Tab completion. Without prompt_toolkit, make_reader() returns None and
3
+ the shell keeps using input() with readline. prompt_toolkit is imported lazily."""
4
+ import importlib
5
+ import os
6
+ import shutil
7
+ import sys
8
+ from typing import Any, Callable, Dict, List, Optional, Tuple
9
+
10
+ from . import history
11
+ from .completion import complete_line
12
+ from .highlight import STYLES, tokenize_for_color
13
+ from .state import ShellState
14
+
15
+ SUGGESTION_STYLE = "fg:#888888"
16
+ _CACHE_LIMIT = 4000
17
+
18
+
19
+ def strip_markers(prompt: str) -> str:
20
+ """Drop the readline markers \\x01 and \\x02 that wrap raw color codes."""
21
+ return prompt.replace("\x01", "").replace("\x02", "")
22
+
23
+
24
+ def make_kind_of(state: ShellState) -> Callable[[str], str]:
25
+ """A function word -> "command" or "unknown", with PATH lookups cached by name and PATH."""
26
+ cache: Dict[Tuple[str, str], bool] = {}
27
+
28
+ def kind_of(word: str) -> str:
29
+ from .builtins import find_builtin
30
+ functions = getattr(state, "functions", None) or {}
31
+ if find_builtin(word) or word in state.aliases or word in functions:
32
+ return "command"
33
+ key = (word, os.environ.get("PATH", ""))
34
+ found = cache.get(key)
35
+ if found is None:
36
+ if len(cache) >= _CACHE_LIMIT:
37
+ cache.clear()
38
+ try:
39
+ found = bool(shutil.which(word))
40
+ except Exception:
41
+ found = False
42
+ cache[key] = found
43
+ return "command" if found else "unknown"
44
+
45
+ return kind_of
46
+
47
+
48
+ def _wanted(force: bool) -> bool:
49
+ mode = os.environ.get("MYSHELL_EDITOR", "").strip().lower()
50
+ if mode == "basic":
51
+ return False
52
+ if force or mode == "fancy":
53
+ return True
54
+ try:
55
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
56
+ return False
57
+ except (AttributeError, ValueError):
58
+ return False
59
+ return os.environ.get("TERM", "") not in ("", "dumb")
60
+
61
+
62
+ def _build(state: ShellState, input: Any, output: Any) -> Any:
63
+ """Create the PromptSession and its helpers. Returns (session, history_obj)."""
64
+ from prompt_toolkit import PromptSession
65
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
66
+ from prompt_toolkit.application import get_app
67
+ from prompt_toolkit.filters import Condition
68
+ from prompt_toolkit.key_binding import KeyBindings
69
+ from prompt_toolkit.completion import Completer, Completion
70
+ from prompt_toolkit.history import History
71
+ from prompt_toolkit.lexers import Lexer
72
+ from prompt_toolkit.shortcuts import CompleteStyle
73
+ from prompt_toolkit.styles import Style
74
+
75
+ class ShellHistory(History):
76
+ """The shell's own history list, newest first. Lines are added by the shell."""
77
+
78
+ def __init__(self) -> None:
79
+ super().__init__()
80
+ self.suspended = False # true while reading continuation lines
81
+
82
+ async def load(self): # type: ignore[override]
83
+ self._loaded = False # re-read the shell's list on every prompt
84
+ async for item in super().load():
85
+ yield item
86
+
87
+ def refresh(self) -> None:
88
+ """Reload now, so suggestions see the newest lines before the first key."""
89
+ self._loaded_strings = list(self.load_history_strings())
90
+ self._loaded = True
91
+
92
+ def load_history_strings(self): # type: ignore[override]
93
+ if self.suspended:
94
+ return iter(())
95
+ return iter(list(reversed(history.entries())))
96
+
97
+ def append_string(self, string: str) -> None:
98
+ if not self.suspended:
99
+ super().append_string(string)
100
+
101
+ def store_string(self, string: str) -> None:
102
+ pass
103
+
104
+ class ShellLexer(Lexer):
105
+ def __init__(self) -> None:
106
+ self.kind_of = make_kind_of(state)
107
+
108
+ def lex_document(self, document): # type: ignore[override]
109
+ lines: List[List[Tuple[str, str]]] = [[]]
110
+ for cls, text in tokenize_for_color(document.text, self.kind_of):
111
+ style = "class:" + cls
112
+ for n, part in enumerate(text.split("\n")):
113
+ if n:
114
+ lines.append([])
115
+ if part:
116
+ lines[-1].append((style, part))
117
+
118
+ def get_line(lineno: int):
119
+ return lines[lineno] if 0 <= lineno < len(lines) else []
120
+ return get_line
121
+
122
+ class ShellCompleter(Completer):
123
+ def get_completions(self, document, complete_event): # type: ignore[override]
124
+ before = document.text_before_cursor
125
+ start, found = complete_line(state, before)
126
+ for candidate in found:
127
+ yield Completion(candidate, start_position=start - len(before))
128
+
129
+ shell_history = ShellHistory()
130
+ suggester = AutoSuggestFromHistory()
131
+
132
+ # prompt_toolkit computes suggestions in a background task. When keys arrive faster
133
+ # than that task runs (fast typing, pasted text), Right/End would find none. These
134
+ # bindings compute the suggestion on the spot instead.
135
+ bindings = KeyBindings()
136
+
137
+ @Condition
138
+ def at_end_without_suggestion() -> bool:
139
+ buf = get_app().current_buffer
140
+ return (buf.suggestion is None and buf.document.is_cursor_at_the_end
141
+ and bool(buf.text))
142
+
143
+ def accept_now(event) -> None:
144
+ buf = event.current_buffer
145
+ found = suggester.get_suggestion(buf, buf.document)
146
+ if found:
147
+ buf.insert_text(found.text)
148
+
149
+ bindings.add("right", filter=at_end_without_suggestion)(accept_now)
150
+ bindings.add("end", filter=at_end_without_suggestion)(accept_now)
151
+ style = Style.from_dict(dict(STYLES, **{"auto-suggestion": SUGGESTION_STYLE}))
152
+ kwargs: Dict[str, Any] = {}
153
+ if input is not None:
154
+ kwargs["input"] = input
155
+ if output is not None:
156
+ kwargs["output"] = output
157
+ session = PromptSession(
158
+ history=shell_history,
159
+ auto_suggest=suggester,
160
+ key_bindings=bindings,
161
+ lexer=ShellLexer(),
162
+ completer=ShellCompleter(),
163
+ complete_while_typing=False,
164
+ complete_style=CompleteStyle.READLINE_LIKE,
165
+ enable_history_search=False,
166
+ mouse_support=False,
167
+ style=style,
168
+ **kwargs)
169
+ return session, shell_history
170
+
171
+
172
+ class LineReader:
173
+ """input()-like reader over one PromptSession. Attributes `session`, `history`,
174
+ `lexer`, `completer` are exposed for tests."""
175
+
176
+ def __init__(self, state: ShellState, input: Any = None, output: Any = None):
177
+ self.state = state
178
+ self.session, self.history = _build(state, input, output)
179
+ self.lexer = self.session.lexer
180
+ self.completer = self.session.completer
181
+
182
+ def read(self, prompt: str = "") -> str:
183
+ """Like input(): raises EOFError on Ctrl+D at an empty line, KeyboardInterrupt on Ctrl+C."""
184
+ from prompt_toolkit.formatted_text import ANSI
185
+ self.history.refresh()
186
+ return self.session.prompt(ANSI(strip_markers(prompt)))
187
+
188
+ def read_continuation(self, prompt: str = "> ") -> str:
189
+ """Read an extra line (a here-document body or a continued command): no
190
+ suggestions, and the line is not added to the history."""
191
+ from prompt_toolkit.auto_suggest import DummyAutoSuggest
192
+ from prompt_toolkit.formatted_text import ANSI
193
+ suggest = self.session.auto_suggest
194
+ self.history.suspended = True
195
+ self.session.auto_suggest = DummyAutoSuggest()
196
+ try:
197
+ return self.session.prompt(ANSI(strip_markers(prompt)))
198
+ finally:
199
+ self.history.suspended = False
200
+ self.session.auto_suggest = suggest
201
+
202
+
203
+ def make_reader(state: ShellState, input: Any = None, output: Any = None,
204
+ force: bool = False) -> Optional[LineReader]:
205
+ """A LineReader, or None when the basic input()/readline path should be used:
206
+ prompt_toolkit missing, MYSHELL_EDITOR=basic, stdin or stdout not a terminal, or TERM
207
+ empty or dumb. MYSHELL_EDITOR=fancy or force=True skips the terminal checks."""
208
+ if not _wanted(force):
209
+ return None
210
+ try:
211
+ importlib.import_module("prompt_toolkit")
212
+ except ImportError:
213
+ return None
214
+ history.use_builtin()
215
+ try:
216
+ return LineReader(state, input, output)
217
+ except Exception:
218
+ return None
myshell/errors.py ADDED
@@ -0,0 +1,41 @@
1
+ """Exceptions used across the shell."""
2
+
3
+
4
+ class ShellError(Exception):
5
+ """A user-facing error. The message is printed and the shell keeps running."""
6
+
7
+
8
+ class ShellSyntaxError(ShellError):
9
+ def __str__(self) -> str:
10
+ return f"syntax error: {self.args[0]}"
11
+
12
+
13
+ class ShellExit(Exception):
14
+ """Raised by the exit builtin. The main loop catches it and shuts down."""
15
+ def __init__(self, code: int):
16
+ super().__init__(code)
17
+ self.code = code
18
+
19
+
20
+ class LoopControl(Exception):
21
+ """Raised by break and continue. `levels` is how many enclosing loops it affects."""
22
+
23
+ def __init__(self, levels: int = 1):
24
+ super().__init__(levels)
25
+ self.levels = levels
26
+
27
+
28
+ class BreakLoop(LoopControl):
29
+ pass
30
+
31
+
32
+ class ContinueLoop(LoopControl):
33
+ pass
34
+
35
+
36
+ class ReturnFromFunction(Exception):
37
+ """Raised by return. The function call or sourced file catches it."""
38
+
39
+ def __init__(self, status: int):
40
+ super().__init__(status)
41
+ self.status = status