xmyshell 0.2.24__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.24/xmyshell.egg-info → xmyshell-0.2.25}/PKG-INFO +1 -1
  2. {xmyshell-0.2.24 → xmyshell-0.2.25}/pyproject.toml +1 -1
  3. xmyshell-0.2.25/xmyshell/__init__.py +19 -0
  4. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/completer.py +82 -59
  5. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/init.py +15 -5
  6. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/kernel.py +0 -1
  7. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/main.py +23 -15
  8. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/meta.py +58 -2
  9. {xmyshell-0.2.24 → xmyshell-0.2.25/xmyshell.egg-info}/PKG-INFO +1 -1
  10. xmyshell-0.2.24/xmyshell/__init__.py +0 -7
  11. {xmyshell-0.2.24 → xmyshell-0.2.25}/LICENSE +0 -0
  12. {xmyshell-0.2.24 → xmyshell-0.2.25}/README.md +0 -0
  13. {xmyshell-0.2.24 → xmyshell-0.2.25}/setup.cfg +0 -0
  14. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/__main__.py +0 -0
  15. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/data/commands.json +0 -0
  16. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/environment.py +0 -0
  17. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/injection.py +0 -0
  18. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/keybindings.py +0 -0
  19. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/stubs/__init__.py +0 -0
  20. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/stubs/__init__.pyi +0 -0
  21. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/stubs/py.typed +0 -0
  22. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/themes.py +0 -0
  23. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/update.py +0 -0
  24. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell/utils.py +0 -0
  25. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell.egg-info/SOURCES.txt +0 -0
  26. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell.egg-info/dependency_links.txt +0 -0
  27. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell.egg-info/entry_points.txt +0 -0
  28. {xmyshell-0.2.24 → xmyshell-0.2.25}/xmyshell.egg-info/requires.txt +0 -0
  29. {xmyshell-0.2.24 → 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.24
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.24"
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}")
@@ -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"):
@@ -463,8 +488,7 @@ class ShellCompleter(Completer):
463
488
  if not lstripped.endswith(parts[-1]):
464
489
  parts.append("")
465
490
  elif len(parts) == 2:
466
- mods = set(sys.builtin_module_names)
467
- mods |= {m.name for m in pkgutil.iter_modules()}
491
+ mods = _module_names()
468
492
  for name in sorted(mods):
469
493
  if not name.startswith(parts[-1]):
470
494
  continue
@@ -487,8 +511,7 @@ class ShellCompleter(Completer):
487
511
  if not lstripped.endswith(parts[-1]):
488
512
  parts.append("")
489
513
  elif len(parts) == 2:
490
- mods = set(sys.builtin_module_names)
491
- mods |= {m.name for m in pkgutil.iter_modules()}
514
+ mods = _module_names()
492
515
  for name in sorted(mods):
493
516
  if not name.startswith(parts[-1]):
494
517
  continue
@@ -2,17 +2,16 @@ import os
2
2
  import sys
3
3
  from .environment import load_init_namespace, init_environ, aliases
4
4
  from .themes import load_theme, THEME_DEFAULT
5
- from .completer import completer_init
6
5
  from .utils import pywarning
7
6
  from .kernel import xmyshell_source
8
7
 
9
8
 
10
- def xmyshell_load() -> None:
9
+ def _load_core() -> None:
10
+ """Namespace, theme and user config. No prompt_toolkit, no PATH scan."""
11
11
  if "" not in sys.path:
12
12
  sys.path.insert(0, "")
13
13
 
14
14
  load_init_namespace()
15
- completer_init()
16
15
  load_theme(THEME_DEFAULT)
17
16
 
18
17
  try:
@@ -28,11 +27,22 @@ def xmyshell_load() -> None:
28
27
 
29
28
  def xmyshell_init() -> None:
30
29
  os.makedirs(os.path.expanduser("~/.xmyshell/"), exist_ok=True)
31
- xmyshell_load()
30
+ _load_core()
31
+
32
+
33
+ def xmyshell_init_completer() -> None:
34
+ """Load the completer, i.e. the first part of the stack needing prompt_toolkit.
35
+
36
+ Kept separate from `xmyshell_init()` so the caller can show the welcome
37
+ message before paying for prompt_toolkit imports.
38
+ """
39
+ from .completer import completer_init
40
+ completer_init()
32
41
 
33
42
 
34
43
  def xmyshell_reload() -> None:
35
44
  os.environ.clear()
36
45
  os.environ.update(init_environ)
37
46
  aliases.clear()
38
- xmyshell_load()
47
+ _load_core()
48
+ xmyshell_init_completer()
@@ -7,7 +7,6 @@ import runpy
7
7
  import subprocess
8
8
  import signal
9
9
  import shlex
10
- from webbrowser import get
11
10
  from .environment import localspace, aliases, xmyshell_alias, xmyshell_unalias, SHELL_CMD
12
11
  from .utils import pywarning, pyerror, getcwd
13
12
  from .meta import HELP_MESSAGE
@@ -4,30 +4,35 @@ _start_time = time_ns()
4
4
 
5
5
 
6
6
  import os
7
- from prompt_toolkit.application import get_app
8
- from prompt_toolkit.styles import Style
9
- from prompt_toolkit import HTML, PromptSession
10
- from prompt_toolkit.history import FileHistory
11
- from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
12
7
  from .meta import WELCOME_MESSAGE
13
8
  from .environment import localspace
14
- from .keybindings import (
15
- bindings,
16
- on_cursor_position_changed,
17
- on_text_changed,
18
- clean_buffer,
19
- )
20
- from .init import xmyshell_init
21
- from .kernel import pyeval, xmyshell
22
- from .injection import inject
23
9
 
24
10
 
25
11
  def xmyshell_main() -> None:
12
+ # Startup is import-bound, and prompt_toolkit is by far the most expensive
13
+ # import we have. Everything below is imported as late as possible so that
14
+ # initialization (and the welcome message) can happen first.
15
+ from .init import xmyshell_init, xmyshell_init_completer
16
+
26
17
  xmyshell_init()
27
18
 
28
19
  if localspace.get("SHOW_WELCOME"):
29
20
  print(WELCOME_MESSAGE)
30
- print(f"Initialized with {(time_ns() - _start_time) // 1_000_000}ms.")
21
+
22
+ xmyshell_init_completer()
23
+
24
+ from prompt_toolkit import HTML, PromptSession
25
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
26
+ from prompt_toolkit.history import FileHistory
27
+ from prompt_toolkit.styles import Style
28
+ from .injection import inject
29
+ from .kernel import pyeval, xmyshell
30
+ from .keybindings import (
31
+ bindings,
32
+ clean_buffer,
33
+ on_cursor_position_changed,
34
+ on_text_changed,
35
+ )
31
36
 
32
37
  session = PromptSession(
33
38
  history=FileHistory(os.path.expanduser("~/.xmyshell/history.txt")),
@@ -41,6 +46,9 @@ def xmyshell_main() -> None:
41
46
  session.default_buffer.on_cursor_position_changed += on_cursor_position_changed
42
47
  session.default_buffer.on_text_changed += on_text_changed
43
48
 
49
+ if localspace.get("SHOW_WELCOME"):
50
+ print(f"Initialized with {(time_ns() - _start_time) // 1_000_000}ms.")
51
+
44
52
  try:
45
53
  while True:
46
54
  try:
@@ -1,4 +1,5 @@
1
- from importlib.metadata import version
1
+ import os
2
+ import sys
2
3
 
3
4
  # ANSI color codes
4
5
  RESET = "\033[0m"
@@ -12,9 +13,64 @@ MAGENTA = "\033[95m"
12
13
 
13
14
  NAME = "xmyshell"
14
15
  DISPLAY_NAME = "XmyShell"
15
- VERSION = version(NAME)
16
16
  AUTHOR = "CaptainSuo"
17
17
  EMAIL = "captainsuo@outlook.com"
18
+
19
+
20
+ def _version_from_metadata() -> str | None:
21
+ """Read VERSION straight from the installed metadata file.
22
+
23
+ `importlib.metadata` costs 60-90ms on import because it drags in
24
+ `email`, `zipfile` and friends, and this module is imported on every
25
+ startup just to print the banner. Reading one small file is enough;
26
+ anything unusual (no metadata, several of them) falls back.
27
+ """
28
+ roots = [os.path.dirname(os.path.dirname(os.path.abspath(__file__)))]
29
+ roots += [entry for entry in sys.path if entry]
30
+
31
+ candidates: list[str] = []
32
+ seen: set[str] = set()
33
+ for root in roots:
34
+ root = os.path.abspath(root)
35
+ if root in seen:
36
+ continue
37
+ seen.add(root)
38
+ try:
39
+ names = os.listdir(root)
40
+ except OSError:
41
+ continue
42
+ for name in names:
43
+ if name.startswith(f"{NAME}-") and name.endswith(".dist-info"):
44
+ candidates.append(os.path.join(root, name, "METADATA"))
45
+ elif name == f"{NAME}.egg-info":
46
+ candidates.append(os.path.join(root, name, "PKG-INFO"))
47
+ if len(candidates) > 1:
48
+ return None
49
+
50
+ if len(candidates) != 1:
51
+ return None
52
+
53
+ try:
54
+ with open(candidates[0], "r", encoding="utf-8", errors="replace") as f:
55
+ for line in f:
56
+ if line.startswith("Version:"):
57
+ return line[len("Version:"):].strip() or None
58
+ if not line.strip(): # end of the header block
59
+ return None
60
+ except OSError:
61
+ pass
62
+ return None
63
+
64
+
65
+ def _installed_version() -> str:
66
+ version = _version_from_metadata()
67
+ if version is not None:
68
+ return version
69
+ from importlib.metadata import version as metadata_version
70
+ return metadata_version(NAME)
71
+
72
+
73
+ VERSION = _installed_version()
18
74
  WELCOME_MESSAGE = f"""{BOLD}{BLUE}{DISPLAY_NAME} {CYAN}{VERSION}{RESET}"""
19
75
 
20
76
  HELP_MESSAGE = f"""{BOLD}{CYAN}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: xmyshell
3
- Version: 0.2.24
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,7 +0,0 @@
1
- from .main import xmyshell_main
2
- from .meta import NAME, VERSION, AUTHOR, EMAIL
3
-
4
- __title__ = NAME
5
- __version__ = VERSION
6
- __author__ = AUTHOR
7
- __author_email__ = EMAIL
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes