xmyshell 0.2.23__tar.gz → 0.2.25__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 (29) hide show
  1. {xmyshell-0.2.23/xmyshell.egg-info → xmyshell-0.2.25}/PKG-INFO +1 -1
  2. {xmyshell-0.2.23 → xmyshell-0.2.25}/pyproject.toml +1 -1
  3. xmyshell-0.2.25/xmyshell/__init__.py +19 -0
  4. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/__main__.py +1 -1
  5. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/completer.py +85 -64
  6. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/data/commands.json +1347 -0
  7. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/init.py +15 -5
  8. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/kernel.py +0 -1
  9. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/main.py +23 -15
  10. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/meta.py +58 -2
  11. {xmyshell-0.2.23 → xmyshell-0.2.25/xmyshell.egg-info}/PKG-INFO +1 -1
  12. xmyshell-0.2.23/xmyshell/__init__.py +0 -7
  13. {xmyshell-0.2.23 → xmyshell-0.2.25}/LICENSE +0 -0
  14. {xmyshell-0.2.23 → xmyshell-0.2.25}/README.md +0 -0
  15. {xmyshell-0.2.23 → xmyshell-0.2.25}/setup.cfg +0 -0
  16. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/environment.py +0 -0
  17. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/injection.py +0 -0
  18. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/keybindings.py +0 -0
  19. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/stubs/__init__.py +0 -0
  20. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/stubs/__init__.pyi +0 -0
  21. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/stubs/py.typed +0 -0
  22. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/themes.py +0 -0
  23. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/update.py +0 -0
  24. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell/utils.py +0 -0
  25. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell.egg-info/SOURCES.txt +0 -0
  26. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell.egg-info/dependency_links.txt +0 -0
  27. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell.egg-info/entry_points.txt +0 -0
  28. {xmyshell-0.2.23 → xmyshell-0.2.25}/xmyshell.egg-info/requires.txt +0 -0
  29. {xmyshell-0.2.23 → xmyshell-0.2.25}/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.23
3
+ Version: 0.2.25
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.23"
3
+ version = "0.2.25"
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"
@@ -0,0 +1,19 @@
1
+ from .meta import NAME, VERSION, AUTHOR, EMAIL
2
+
3
+ __title__ = NAME
4
+ __version__ = VERSION
5
+ __author__ = AUTHOR
6
+ __author_email__ = EMAIL
7
+
8
+ __all__ = ["xmyshell_main"]
9
+
10
+ xmyshell_main = ...
11
+
12
+ def __getattr__(name: str):
13
+ # Importing the shell runtime pulls in prompt_toolkit (~350ms), so keep it
14
+ # lazy: `import xmyshell`, `from xmyshell.themes import ...` and the
15
+ # `--version` / `--help` paths must not pay for it.
16
+ if name == "xmyshell_main":
17
+ from .main import xmyshell_main
18
+ return xmyshell_main
19
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -10,7 +10,7 @@ def main() -> None:
10
10
  xmyshell_main()
11
11
  elif argv[1] == "--update":
12
12
  subprocess.run([sys.executable, "-m", "xmyshell.update"] + argv[2:])
13
- elif argv[1] == "--version":
13
+ elif argv[1] == "--version" or argv[1] == "-v":
14
14
  from .meta import WELCOME_MESSAGE
15
15
  print(WELCOME_MESSAGE)
16
16
  elif argv[1] == "--help":
@@ -1,22 +1,23 @@
1
- from collections.abc import Generator, Iterable
1
+ from collections.abc import Generator
2
2
  import os
3
3
  import shlex
4
4
  import sys
5
5
  import re
6
6
  import time
7
- import json
8
7
  import keyword
9
- import pkgutil
10
8
  from string import whitespace
11
9
  from prompt_toolkit.completion import CompleteEvent, Completer, Completion
12
10
  from prompt_toolkit.document import Document
13
11
  from .environment import localspace, aliases
14
12
  from .utils import truncate
15
- from pathlib import Path
16
13
 
17
14
  MAX_DISPLAY_LEN = 24
18
15
  MAX_META_LEN = 12
19
16
 
17
+ WIN_EXEC_EXTS = frozenset({".exe", ".bat", ".cmd", ".ps1", ".py", ".com"})
18
+ NON_EXEC_SUFFIXES = (".dll", ".pyd", ".pyc", ".sys", ".msi", ".drv")
19
+ POSIX_NON_EXEC_SUFFIXES = (".so", ".a", ".o")
20
+
20
21
  BUILTINS = ("cd", "cp", "cat", "echo", "exit", "import", "ls", "print", "pyexec", "pwd", "source",
21
22
  "clear", "grep", "find", "from", "mkdir", "rm", "reload", "mv", "help",
22
23
  "update", "alias", "unalias")
@@ -42,61 +43,84 @@ COMMON = (
42
43
 
43
44
  KEYWORDS = list(keyword.kwlist)
44
45
 
45
- COMMAND_TREE = {}
46
- json_path = Path(__file__).parent / "data" / "commands.json"
47
- try:
48
- with open(json_path, "r", encoding="utf-8") as f:
49
- COMMAND_TREE = json.load(f)
50
- except (FileNotFoundError, json.JSONDecodeError):
51
- pass
46
+ COMMAND_TREE: dict | None = None
47
+ COMMAND_TREE_PATH = os.path.join(os.path.dirname(__file__), "data", "commands.json")
48
+
49
+
50
+ def _command_tree() -> dict:
51
+ global COMMAND_TREE
52
+ if COMMAND_TREE is None:
53
+ COMMAND_TREE = {}
54
+ try:
55
+ import json
56
+ with open(COMMAND_TREE_PATH, "r", encoding="utf-8") as f:
57
+ COMMAND_TREE = json.load(f)
58
+ except (OSError, ValueError):
59
+ pass
60
+ return COMMAND_TREE or {}
61
+
62
+
63
+ def _module_names() -> set[str]:
64
+ """Module names offered after `import` / `from` (pkgutil is not cheap)."""
65
+ import pkgutil
66
+ return set(sys.builtin_module_names) | {m.name for m in pkgutil.iter_modules()}
67
+
52
68
 
53
69
  class ShellCompleter(Completer):
54
70
 
55
- def __init__(self, cache_duration: int = 3) -> None:
71
+ def __init__(self, cache_duration: int = 30) -> None:
56
72
  self._cache: list[str] = []
57
- self._cache_time: float = 0
73
+ self._cache_time: float = 0.0
58
74
  self._cache_duration = cache_duration
59
- self._get_commands()
75
+ self._loaded = False
76
+ # The PATH scan is deferred to the first completion request: it costs
77
+ # tens of milliseconds and nothing needs it to show the prompt.
60
78
 
61
79
  def _strip_ext(self, name: str) -> str:
62
80
  if os.name == "nt":
63
- ext = os.path.splitext(name)[1].lower()
64
- if ext in {".exe", ".bat", ".cmd", ".ps1", ".py", ".com"}:
65
- return os.path.splitext(name)[0]
81
+ stem, ext = os.path.splitext(name)
82
+ if ext in WIN_EXEC_EXTS:
83
+ return stem
66
84
  return name
67
85
 
68
86
  def _get_commands(self) -> list[str]:
69
- now = time.time()
70
- if self._cache and now - self._cache_time < self._cache_duration:
87
+ now = time.monotonic()
88
+ if self._loaded and now - self._cache_time < self._cache_duration:
71
89
  return self._cache
72
90
 
73
91
  commands: set[str] = set(BUILTINS)
74
92
  for path in os.environ.get("PATH", "").split(os.pathsep):
75
- if not path or not os.path.isdir(path) or path.startswith("/mnt/"):
93
+ if not path or path.startswith("/mnt/"):
76
94
  continue
77
95
  try:
78
- for name in os.listdir(path):
79
- if os.name == "nt":
80
- name = name.lower()
81
- full = os.path.join(path, name)
82
- if os.path.isfile(full) and self._is_executable(name, full):
96
+ with os.scandir(path) as entries:
97
+ for entry in entries:
98
+ name = entry.name.lower() if os.name == "nt" else entry.name
99
+ if not self._is_executable(name):
100
+ continue
101
+ try:
102
+ if not entry.is_file():
103
+ continue
104
+ except OSError:
105
+ continue
106
+ if os.name != "nt" and not os.access(entry.path, os.X_OK):
107
+ continue
83
108
  commands.add(self._strip_ext(name))
84
- except (OSError, PermissionError):
109
+ except OSError:
85
110
  continue
86
111
 
87
112
  self._cache = self._sort_commands(commands)
88
113
  self._cache_time = now
114
+ self._loaded = True
89
115
  return self._cache
90
116
 
91
- def _is_executable(self, name: str, full_path: str) -> bool:
92
- if name.endswith((".dll", ".pyd", ".pyc", ".sys", ".msi", ".drv")):
117
+ def _is_executable(self, name: str) -> bool:
118
+ """Name-only filter, applied before any filesystem access."""
119
+ if name.endswith(NON_EXEC_SUFFIXES):
93
120
  return False
94
-
95
121
  if os.name == "nt":
96
- ext = os.path.splitext(name)[1].lower()
97
- return ext in {".exe", ".bat", ".cmd", ".ps1", ".py", ".com"}
98
-
99
- return os.access(full_path, os.X_OK) and not name.endswith((".so", ".a", ".o"))
122
+ return os.path.splitext(name)[1] in WIN_EXEC_EXTS
123
+ return not name.endswith(POSIX_NON_EXEC_SUFFIXES)
100
124
 
101
125
  def _inside_braces(self, text: str) -> bool:
102
126
  count = 0
@@ -178,28 +202,29 @@ class ShellCompleter(Completer):
178
202
  prefix = os.path.basename(path).strip('"\'')
179
203
 
180
204
  try:
181
- matches: list[str] = []
182
- for item in os.listdir(dirname):
183
- if item.startswith(prefix):
184
- matches.append(item)
185
- if len(matches) >= max_results:
186
- break
187
-
188
- for item in sorted(matches):
189
- full = os.path.join(dirname, item)
190
- is_dir = os.path.isdir(full)
191
- if ' ' in item and not in_string:
192
- name = f'"{item}"'
193
- else:
194
- name = item
195
- yield Completion(
196
- name,
197
- display=truncate(item, MAX_DISPLAY_LEN),
198
- start_position=-len(prefix),
199
- display_meta="directory" if is_dir else "file",
200
- )
205
+ entries = sorted(os.listdir(dirname))
201
206
  except OSError:
202
- pass
207
+ return
208
+
209
+ exact = [e for e in entries if e.startswith(prefix)]
210
+ fuzzy = [e for e in entries if not e.startswith(prefix) and prefix in e]
211
+
212
+ budget = max_results - len(exact[:max_results])
213
+ selected = exact[:max_results] + fuzzy[:max(0, budget)]
214
+
215
+ for item in selected:
216
+ full = os.path.join(dirname, item)
217
+ is_dir = os.path.isdir(full)
218
+ if ' ' in item and not in_string:
219
+ name = f'"{item}"'
220
+ else:
221
+ name = item
222
+ yield Completion(
223
+ name,
224
+ display=truncate(item, MAX_DISPLAY_LEN),
225
+ start_position=-len(prefix),
226
+ display_meta="directory" if is_dir else "file",
227
+ )
203
228
 
204
229
  @staticmethod
205
230
  def _last_identifier(text: str) -> str:
@@ -358,7 +383,7 @@ class ShellCompleter(Completer):
358
383
  except ValueError:
359
384
  parts = text.split()
360
385
  if not parts: return
361
- sub_cmd = COMMAND_TREE.get(parts[0])
386
+ sub_cmd = _command_tree().get(parts[0])
362
387
  if not sub_cmd: return
363
388
  global_flags: set[str] = set()
364
389
  if sub_cmd.get("_global"):
@@ -368,15 +393,10 @@ class ShellCompleter(Completer):
368
393
  last_word = parts[-1]
369
394
 
370
395
  for part in parts[1:-1]:
371
- if part.startswith("-"):
372
- continue
373
396
  if sub_cmd.get("_global"):
374
397
  global_flags.update(sub_cmd["_global"])
375
398
  if sub_cmd.get(part):
376
399
  sub_cmd = sub_cmd[part]
377
- else:
378
- sub_cmd = {}
379
- break
380
400
 
381
401
  for name in sorted(sub_cmd.keys()):
382
402
  if name == "_global" or name == "_flags": continue
@@ -389,6 +409,9 @@ class ShellCompleter(Completer):
389
409
  display_meta="subcommand"
390
410
  )
391
411
 
412
+ # not auto complete flags unless user types them
413
+ if last_word == "": return
414
+
392
415
  for name in sorted(sub_cmd.get("_flags") or set()):
393
416
  if name in parts[:-1]: continue
394
417
  if name.startswith(last_word):
@@ -465,8 +488,7 @@ class ShellCompleter(Completer):
465
488
  if not lstripped.endswith(parts[-1]):
466
489
  parts.append("")
467
490
  elif len(parts) == 2:
468
- mods = set(sys.builtin_module_names)
469
- mods |= {m.name for m in pkgutil.iter_modules()}
491
+ mods = _module_names()
470
492
  for name in sorted(mods):
471
493
  if not name.startswith(parts[-1]):
472
494
  continue
@@ -489,8 +511,7 @@ class ShellCompleter(Completer):
489
511
  if not lstripped.endswith(parts[-1]):
490
512
  parts.append("")
491
513
  elif len(parts) == 2:
492
- mods = set(sys.builtin_module_names)
493
- mods |= {m.name for m in pkgutil.iter_modules()}
514
+ mods = _module_names()
494
515
  for name in sorted(mods):
495
516
  if not name.startswith(parts[-1]):
496
517
  continue