xmyshell 0.2.20__tar.gz → 0.2.22__tar.gz

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.
Files changed (28) hide show
  1. {xmyshell-0.2.20/xmyshell.egg-info → xmyshell-0.2.22}/PKG-INFO +1 -1
  2. {xmyshell-0.2.20 → xmyshell-0.2.22}/pyproject.toml +1 -1
  3. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/completer.py +40 -28
  4. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/environment.py +14 -4
  5. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/kernel.py +21 -21
  6. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/keybindings.py +5 -3
  7. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/main.py +10 -12
  8. {xmyshell-0.2.20 → xmyshell-0.2.22/xmyshell.egg-info}/PKG-INFO +1 -1
  9. {xmyshell-0.2.20 → xmyshell-0.2.22}/LICENSE +0 -0
  10. {xmyshell-0.2.20 → xmyshell-0.2.22}/README.md +0 -0
  11. {xmyshell-0.2.20 → xmyshell-0.2.22}/setup.cfg +0 -0
  12. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/__init__.py +0 -0
  13. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/__main__.py +0 -0
  14. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/data/commands.json +0 -0
  15. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/init.py +0 -0
  16. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/injection.py +0 -0
  17. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/meta.py +0 -0
  18. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/stubs/__init__.py +0 -0
  19. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/stubs/__init__.pyi +0 -0
  20. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/stubs/py.typed +0 -0
  21. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/themes.py +0 -0
  22. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/update.py +0 -0
  23. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell/utils.py +0 -0
  24. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell.egg-info/SOURCES.txt +0 -0
  25. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell.egg-info/dependency_links.txt +0 -0
  26. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell.egg-info/entry_points.txt +0 -0
  27. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell.egg-info/requires.txt +0 -0
  28. {xmyshell-0.2.20 → xmyshell-0.2.22}/xmyshell.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: xmyshell
3
- Version: 0.2.20
3
+ Version: 0.2.22
4
4
  Summary: XmyShell is a shell-like tool built on top of prompt_toolkit which provides a persistent Python runtime.
5
5
  Requires-Python: >=3.12
6
6
  Description-Content-Type: text/markdown
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "xmyshell"
3
- version = "0.2.20"
3
+ version = "0.2.22"
4
4
  description = "XmyShell is a shell-like tool built on top of prompt_toolkit which provides a persistent Python runtime."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -10,7 +10,7 @@ import pkgutil
10
10
  from string import whitespace
11
11
  from prompt_toolkit.completion import CompleteEvent, Completer, Completion
12
12
  from prompt_toolkit.document import Document
13
- from .environment import namespace, aliases
13
+ from .environment import localspace, aliases
14
14
  from .utils import truncate
15
15
  from pathlib import Path
16
16
 
@@ -122,7 +122,7 @@ class ShellCompleter(Completer):
122
122
  def _path_completions(self, text: str, max_results: int = 100, in_string: bool=False):
123
123
  if text and text[-1] in whitespace: return
124
124
 
125
- def last_token_raw(text: str) -> str:
125
+ def last_token_raw(text: str) -> tuple[str, bool]:
126
126
  quote = None
127
127
  start = 0
128
128
  i = 0
@@ -141,26 +141,38 @@ class ShellCompleter(Completer):
141
141
  elif ch == "\\":
142
142
  i += 1
143
143
  i += 1
144
- return text[start:]
145
-
146
- def start_pos(text: str, prefix: str) -> int:
147
- original_len = len(text)
148
- if text and text[-1] in ("'", '"') and not text.endswith(prefix):
149
- text = text[:-1]
150
- if not prefix or not text.endswith(prefix):
151
- return -len(prefix)
152
- start = len(text) - len(prefix)
153
- if start > 0 and text[start - 1] in ("'", '"'):
154
- start -= 1
155
- return start - original_len
156
-
157
- last = last_token_raw(text)
158
- in_string = in_string or last.startswith('"') or last.startswith("'")
159
- last = last.lstrip('"\'')
144
+ return text[start:], quote is not None
145
+
146
+ def split_lenient(s: str) -> list[str] | None:
147
+ try:
148
+ return shlex.split(s)
149
+ except ValueError:
150
+ pass
151
+ quote = None
152
+ i = 0
153
+ while i < len(s):
154
+ ch = s[i]
155
+ if quote:
156
+ if ch == quote: quote = None
157
+ elif ch == '\\' and quote == '"': i += 1
158
+ else:
159
+ if ch in ('"', "'"): quote = ch
160
+ elif ch == '\\': i += 1
161
+ i += 1
162
+ if quote:
163
+ try:
164
+ return shlex.split(s + quote)
165
+ except ValueError:
166
+ pass
167
+ return None
168
+
169
+ last, still_in = last_token_raw(text)
170
+ in_string = in_string or still_in
160
171
  if last == '~': return # don't remove this
161
- try:
162
- path = os.path.expanduser(shlex.split(last)[0])
163
- except (ValueError, IndexError):
172
+ parts = split_lenient(last)
173
+ if parts:
174
+ path = os.path.expanduser(parts[0])
175
+ else:
164
176
  path = os.path.expanduser(last)
165
177
  dirname = os.path.dirname(path) or "."
166
178
  prefix = os.path.basename(path).strip('"\'')
@@ -183,7 +195,7 @@ class ShellCompleter(Completer):
183
195
  yield Completion(
184
196
  name,
185
197
  display=truncate(item, MAX_DISPLAY_LEN),
186
- start_position=start_pos(text, prefix),
198
+ start_position=-len(prefix),
187
199
  display_meta="directory" if is_dir else "file",
188
200
  )
189
201
  except OSError:
@@ -273,8 +285,8 @@ class ShellCompleter(Completer):
273
285
 
274
286
  obj = None
275
287
  root = self._last_identifier(parts[start])
276
- if root in namespace:
277
- obj = namespace[root]
288
+ if root in localspace:
289
+ obj = localspace[root]
278
290
  elif hasattr(__builtins__, root):
279
291
  obj = getattr(__builtins__, root)
280
292
  elif isinstance(__builtins__, dict) and root in __builtins__:
@@ -323,10 +335,10 @@ class ShellCompleter(Completer):
323
335
  else:
324
336
  builtins_candidates = []
325
337
 
326
- candidates = set(namespace.keys()) | set(builtins_candidates)
338
+ candidates = set(localspace.keys()) | set(builtins_candidates)
327
339
  for name in sorted(candidates) + KEYWORDS:
328
- if name in namespace:
329
- meta = truncate(type(namespace[name]).__name__, MAX_META_LEN)
340
+ if name in localspace:
341
+ meta = truncate(type(localspace[name]).__name__, MAX_META_LEN)
330
342
  elif name in __builtins__:
331
343
  meta = truncate(type(__builtins__[name]).__name__, MAX_META_LEN)
332
344
  else:
@@ -518,4 +530,4 @@ class ShellCompleter(Completer):
518
530
  return completions
519
531
 
520
532
  def completer_init() -> None:
521
- namespace["shell_completer"] = ShellCompleter()
533
+ localspace["shell_completer"] = ShellCompleter()
@@ -7,7 +7,17 @@ from typing import Any
7
7
  from collections.abc import Mapping
8
8
  from .utils import XMYSHELL_MAGIC, getcwd, getlogin, HOME_DIR, xmyshell_cat
9
9
 
10
- namespace: dict[str, Any] = {}
10
+ class LocalSpace(dict):
11
+ def __init__(self, readonly):
12
+ super().__init__()
13
+ self._readonly = readonly
14
+
15
+ def __missing__(self, key):
16
+ if key in self._readonly:
17
+ return self._readonly[key]
18
+ raise KeyError(key)
19
+
20
+ localspace: dict[str, Any] = LocalSpace(os.environ)
11
21
  aliases: dict[str, str] = {}
12
22
  init_environ: dict[str, str] = dict(os.environ)
13
23
  SHELL_CMD = ["cmd", "/c"] if os.name == "nt" else ["/bin/sh", "-c"]
@@ -52,8 +62,8 @@ _init_namespace: dict[str, Any] = {
52
62
 
53
63
 
54
64
  def load_init_namespace() -> None:
55
- namespace.clear()
56
- namespace.update(_init_namespace)
65
+ localspace.clear()
66
+ localspace.update(_init_namespace)
57
67
 
58
68
 
59
69
  def update_namespace(values: Mapping[str, object]) -> None:
@@ -71,5 +81,5 @@ def update_namespace(values: Mapping[str, object]) -> None:
71
81
  frame.f_locals.update(values)
72
82
  return
73
83
  depth += 1
74
- namespace.update(values) # kernal
84
+ localspace.update(values) # kernal
75
85
 
@@ -7,7 +7,7 @@ import runpy
7
7
  import subprocess
8
8
  import signal
9
9
  import shlex
10
- from .environment import namespace, aliases, xmyshell_alias, xmyshell_unalias, SHELL_CMD
10
+ from .environment import localspace, aliases, xmyshell_alias, xmyshell_unalias, SHELL_CMD
11
11
  from .utils import pywarning, pyerror, getcwd
12
12
  from .meta import HELP_MESSAGE
13
13
 
@@ -45,7 +45,7 @@ def _run(cmd_line: list[str] | str, **kwargs) -> subprocess.CompletedProcess:
45
45
  return subprocess.run(cmd_line, **_kwargs_preexec, **kwargs)
46
46
  else:
47
47
  return subprocess.run(
48
- namespace.get("SHELL_CMD", SHELL_CMD) + [cmd_line],
48
+ localspace.get("SHELL_CMD", SHELL_CMD) + [cmd_line],
49
49
  **_kwargs_preexec,
50
50
  **kwargs,
51
51
  )
@@ -53,11 +53,11 @@ def _run(cmd_line: list[str] | str, **kwargs) -> subprocess.CompletedProcess:
53
53
  def xmyshell_source(path: str) -> None:
54
54
  _updated = runpy.run_path(
55
55
  path_name=os.path.expanduser(path),
56
- init_globals=namespace,
56
+ init_globals=localspace,
57
57
  run_name="__main__",
58
58
  )
59
- namespace.clear()
60
- namespace.update(_updated)
59
+ localspace.clear()
60
+ localspace.update(_updated)
61
61
 
62
62
 
63
63
  def pyeval(cmd_line: str) -> str:
@@ -89,7 +89,7 @@ def pyeval(cmd_line: str) -> str:
89
89
  expr = cmd_line[i+1:j-1].strip()
90
90
  if expr:
91
91
  try:
92
- val = eval(expr, dict(os.environ), namespace)
92
+ val = eval(expr, localspace, localspace)
93
93
  if not isinstance(
94
94
  val, (str, bytes, bytearray, memoryview)
95
95
  ) and isinstance(val, (Sequence, Generator)):
@@ -133,14 +133,14 @@ def xmyshell_raw_command(cmd_line: str) -> int | None:
133
133
  pyerror("pyexec: missing code")
134
134
  return -1
135
135
  try:
136
- exec(code, dict(os.environ), namespace)
137
- namespace["last_error"] = None
136
+ exec(code, localspace, localspace)
137
+ localspace["last_error"] = None
138
138
  return 0
139
139
  except Exception as e:
140
140
  import traceback
141
141
 
142
- namespace["last_error"] = e
143
- namespace["last_traceback"] = traceback.format_exc()
142
+ localspace["last_error"] = e
143
+ localspace["last_traceback"] = traceback.format_exc()
144
144
  pyerror(f"{type(e).__name__}: {e}")
145
145
  return -1
146
146
 
@@ -166,7 +166,7 @@ def xmyshell_raw_command(cmd_line: str) -> int | None:
166
166
  try:
167
167
  altname, alias_target = code.split('=', 1)
168
168
  altname = altname.strip()
169
- xmyshell_alias(altname, eval(alias_target, namespace, {}))
169
+ xmyshell_alias(altname, eval(alias_target, localspace, {}))
170
170
  return 0
171
171
  except Exception as e:
172
172
  pyerror(f"{type(e).__name__}: {e}")
@@ -186,15 +186,15 @@ def xmyshell_raw_command(cmd_line: str) -> int | None:
186
186
  pyerror("print: missing expression")
187
187
  return -1
188
188
  try:
189
- result = eval(expr, dict(os.environ), namespace)
189
+ result = eval(expr, localspace, localspace)
190
190
  print(result)
191
- namespace["last_error"] = None
192
- namespace["ans"] = result
191
+ localspace["last_error"] = None
192
+ localspace["ans"] = result
193
193
  return 0
194
194
  except Exception as e:
195
195
  import traceback
196
- namespace["last_error"] = e
197
- namespace["last_traceback"] = traceback.format_exc()
196
+ localspace["last_error"] = e
197
+ localspace["last_traceback"] = traceback.format_exc()
198
198
  pyerror(f"{type(e).__name__}: {e}")
199
199
  return -1
200
200
 
@@ -226,7 +226,7 @@ def xmyshell_raw_command(cmd_line: str) -> int | None:
226
226
 
227
227
  if command.startswith("import") or command.startswith("from"):
228
228
  try:
229
- exec(cmd_line, dict(os.environ), namespace)
229
+ exec(cmd_line, localspace, localspace)
230
230
  return 0
231
231
  except Exception as e:
232
232
  pyerror(f"{type(e).__name__}: {e}")
@@ -248,7 +248,7 @@ def xmyshell(cmd_line: str) -> int:
248
248
  if sh_cmd:
249
249
  with _no_interrupt():
250
250
  proc = subprocess.Popen(
251
- namespace.get("SHELL_CMD", SHELL_CMD) + [sh_cmd],
251
+ localspace.get("SHELL_CMD", SHELL_CMD) + [sh_cmd],
252
252
  env=os.environ,
253
253
  stdin=subprocess.PIPE,
254
254
  stdout=subprocess.PIPE,
@@ -266,7 +266,7 @@ def xmyshell(cmd_line: str) -> int:
266
266
  sys.stdout = old_stdout
267
267
  if target_var:
268
268
  result, _ = proc.communicate()
269
- namespace[target_var] = result
269
+ localspace[target_var] = result
270
270
  return proc.returncode
271
271
  else:
272
272
  return proc.wait()
@@ -278,7 +278,7 @@ def xmyshell(cmd_line: str) -> int:
278
278
  with redirect_stdout(f):
279
279
  return_code = xmyshell_raw_command(cmd_line)
280
280
  if return_code is not None:
281
- namespace[target_var] = f.getvalue()
281
+ localspace[target_var] = f.getvalue()
282
282
  return return_code
283
283
  else:
284
284
  return_code = xmyshell_raw_command(cmd_line)
@@ -349,7 +349,7 @@ def xmyshell(cmd_line: str) -> int:
349
349
  result = _run(
350
350
  cmd_line, env=os.environ, capture_output=True, text=True
351
351
  )
352
- namespace[target_var] = result.stdout
352
+ localspace[target_var] = result.stdout
353
353
  else:
354
354
  result = _run(cmd_line, env=os.environ)
355
355
 
@@ -371,9 +371,11 @@ def _(event: KeyPressEvent) -> None:
371
371
  text = buffer.complete_state.current_completion.text
372
372
  buffer.complete_state.current_completion.text = text.rstrip()
373
373
  buffer.apply_completion(buffer.complete_state.current_completion)
374
+ else:
375
+ buffer.insert_text(" ")
374
376
 
375
377
  @bindings.add(Keys.Enter)
376
- def handle_enter(event):
378
+ def _(event: KeyPressEvent):
377
379
  buffer = event.current_buffer
378
380
  current_line = buffer.document.current_line_before_cursor
379
381
 
@@ -384,6 +386,6 @@ def handle_enter(event):
384
386
  else:
385
387
  buffer.validate_and_handle()
386
388
 
387
- @bindings.add("escape", filter=has_completions, eager=True)
388
- def cancel_completion(event):
389
+ @bindings.add(Keys.Escape, filter=has_completions, eager=True)
390
+ def _(event: KeyPressEvent):
389
391
  event.current_buffer.cancel_completion()
@@ -10,7 +10,7 @@ from prompt_toolkit import HTML, PromptSession
10
10
  from prompt_toolkit.history import FileHistory
11
11
  from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
12
12
  from .meta import WELCOME_MESSAGE
13
- from .environment import namespace
13
+ from .environment import localspace
14
14
  from .keybindings import (
15
15
  bindings,
16
16
  on_cursor_position_changed,
@@ -21,13 +21,11 @@ from .init import xmyshell_init
21
21
  from .kernel import pyeval, xmyshell
22
22
  from .injection import inject
23
23
 
24
- def _continuation(width, line_number, is_soft_wrap):
25
- return HTML("<style fg='ansidarkgray'>" + '.' * width + "</style>")
26
24
 
27
25
  def xmyshell_main() -> None:
28
26
  xmyshell_init()
29
27
 
30
- if namespace.get("SHOW_WELCOME"):
28
+ if localspace.get("SHOW_WELCOME"):
31
29
  print(WELCOME_MESSAGE)
32
30
  print(f"Initialized with {(time_ns() - _start_time) // 1_000_000}ms.")
33
31
 
@@ -38,7 +36,7 @@ def xmyshell_main() -> None:
38
36
  complete_while_typing=True,
39
37
  key_bindings=bindings,
40
38
  multiline=True,
41
- prompt_continuation=_continuation,
39
+ prompt_continuation="",
42
40
  )
43
41
  session.default_buffer.on_cursor_position_changed += on_cursor_position_changed
44
42
  session.default_buffer.on_text_changed += on_text_changed
@@ -47,16 +45,16 @@ def xmyshell_main() -> None:
47
45
  while True:
48
46
  try:
49
47
  cmd_line: str = session.prompt(
50
- HTML(pyeval(namespace["shell_prompt"])),
51
- rprompt=HTML(pyeval(namespace["shell_rprompt"])),
52
- completer=namespace["shell_completer"],
53
- placeholder=HTML(namespace["prompt_placeholder"]),
54
- style=Style.from_dict(namespace["prompt_style"]),
48
+ HTML(pyeval(localspace["shell_prompt"])),
49
+ rprompt=HTML(pyeval(localspace["shell_rprompt"])),
50
+ completer=localspace["shell_completer"],
51
+ placeholder=HTML(localspace["prompt_placeholder"]),
52
+ style=Style.from_dict(localspace["prompt_style"]),
55
53
  pre_run=inject,
56
54
  )
57
55
  start_time = time_ns()
58
- namespace["exit_code"] = xmyshell(cmd_line)
59
- namespace["exec_duration"] = time_ns() - start_time
56
+ localspace["exit_code"] = xmyshell(cmd_line)
57
+ localspace["exec_duration"] = time_ns() - start_time
60
58
  clean_buffer()
61
59
  except KeyboardInterrupt:
62
60
  print("Ctrl-C")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: xmyshell
3
- Version: 0.2.20
3
+ Version: 0.2.22
4
4
  Summary: XmyShell is a shell-like tool built on top of prompt_toolkit which provides a persistent Python runtime.
5
5
  Requires-Python: >=3.12
6
6
  Description-Content-Type: text/markdown
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes