slashed 0.10.0__tar.gz → 0.11.3__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 (55) hide show
  1. {slashed-0.10.0 → slashed-0.11.3}/.pre-commit-config.yaml +2 -2
  2. {slashed-0.10.0 → slashed-0.11.3}/PKG-INFO +1 -1
  3. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/__init__.py +1 -1
  4. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/base.py +17 -6
  5. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/builtin/help_cmd.py +14 -12
  6. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/completers.py +73 -39
  7. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/completion.py +10 -15
  8. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/output.py +3 -0
  9. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/prompt_toolkit_completer.py +15 -14
  10. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/router.py +11 -5
  11. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/textual_adapter/app.py +2 -1
  12. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/textual_adapter/command_input.py +6 -6
  13. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/textual_adapter/command_textarea.py +6 -6
  14. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/textual_adapter/suggester.py +3 -1
  15. slashed-0.11.3/tests/test_completion.py +108 -0
  16. {slashed-0.10.0 → slashed-0.11.3}/tests/test_router.py +12 -16
  17. {slashed-0.10.0 → slashed-0.11.3}/.copier-answers.yml +0 -0
  18. {slashed-0.10.0 → slashed-0.11.3}/.github/FUNDING.yml +0 -0
  19. {slashed-0.10.0 → slashed-0.11.3}/.github/copilot-instructions.md +0 -0
  20. {slashed-0.10.0 → slashed-0.11.3}/.github/dependabot.yml +0 -0
  21. {slashed-0.10.0 → slashed-0.11.3}/.github/workflows/build.yml +0 -0
  22. {slashed-0.10.0 → slashed-0.11.3}/.github/workflows/documentation.yml +0 -0
  23. {slashed-0.10.0 → slashed-0.11.3}/.gitignore +0 -0
  24. {slashed-0.10.0 → slashed-0.11.3}/LICENSE +0 -0
  25. {slashed-0.10.0 → slashed-0.11.3}/README.md +0 -0
  26. {slashed-0.10.0 → slashed-0.11.3}/docs/.empty +0 -0
  27. {slashed-0.10.0 → slashed-0.11.3}/duties.py +0 -0
  28. {slashed-0.10.0 → slashed-0.11.3}/mkdocs.yml +0 -0
  29. {slashed-0.10.0 → slashed-0.11.3}/overrides/_dummy.txt +0 -0
  30. {slashed-0.10.0 → slashed-0.11.3}/pyproject.toml +0 -0
  31. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/builtin/__init__.py +0 -0
  32. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/builtin/system.py +0 -0
  33. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/commands.py +0 -0
  34. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/context.py +0 -0
  35. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/events.py +0 -0
  36. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/exceptions.py +0 -0
  37. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/log.py +0 -0
  38. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/py.typed +0 -0
  39. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/registry.py +0 -0
  40. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/slashed_types.py +0 -0
  41. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/store.py +0 -0
  42. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/textual_adapter/__init__.py +0 -0
  43. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/textual_adapter/command_base.py +0 -0
  44. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/textual_adapter/dropdown.py +0 -0
  45. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/textual_adapter/log.py +0 -0
  46. {slashed-0.10.0 → slashed-0.11.3}/src/slashed/utils.py +0 -0
  47. {slashed-0.10.0 → slashed-0.11.3}/src/slashed_examples/__init__.py +0 -0
  48. {slashed-0.10.0 → slashed-0.11.3}/src/slashed_examples/prompt_toolkit_example.py +0 -0
  49. {slashed-0.10.0 → slashed-0.11.3}/src/slashed_examples/textual_command_input.py +0 -0
  50. {slashed-0.10.0 → slashed-0.11.3}/src/slashed_examples/textual_commands_example.py +0 -0
  51. {slashed-0.10.0 → slashed-0.11.3}/tests/__init__.py +0 -0
  52. {slashed-0.10.0 → slashed-0.11.3}/tests/conftest.py +0 -0
  53. {slashed-0.10.0 → slashed-0.11.3}/tests/test_context.py +0 -0
  54. {slashed-0.10.0 → slashed-0.11.3}/tests/test_slashed.py +0 -0
  55. {slashed-0.10.0 → slashed-0.11.3}/tests/test_slashedcommand.py +0 -0
@@ -35,13 +35,13 @@ repos:
35
35
  additional_dependencies: [orjson]
36
36
 
37
37
  - repo: https://github.com/charliermarsh/ruff-pre-commit
38
- rev: v0.9.2
38
+ rev: v0.9.3
39
39
  hooks:
40
40
  - id: ruff
41
41
  - id: ruff-format
42
42
 
43
43
  - repo: https://github.com/commitizen-tools/commitizen
44
- rev: v4.1.0
44
+ rev: v4.1.1
45
45
  hooks:
46
46
  - id: commitizen
47
47
  stages: [commit-msg]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: slashed
3
- Version: 0.10.0
3
+ Version: 0.11.3
4
4
  Summary: Slash commands and autocompletions
5
5
  Project-URL: Documentation, https://phil65.github.io/slashed/
6
6
  Project-URL: Source, https://github.com/phil65/slashed
@@ -35,7 +35,7 @@ from slashed.store import CommandStore
35
35
  from slashed.registry import CommandRegistry
36
36
 
37
37
 
38
- __version__ = "0.10.0"
38
+ __version__ = "0.11.3"
39
39
 
40
40
  __all__ = [ # noqa: RUF022
41
41
  # Core
@@ -3,22 +3,26 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from abc import ABC, abstractmethod
6
- from collections.abc import Callable
6
+ from collections.abc import Awaitable, Callable
7
7
  from dataclasses import dataclass, field
8
+ import inspect
8
9
  import shlex
9
- from typing import TYPE_CHECKING, Any, Protocol, TypeVar
10
+ from typing import TYPE_CHECKING, Any, Protocol, TypeVar, cast
10
11
 
11
12
  from slashed.completion import CompletionProvider
12
13
  from slashed.exceptions import CommandError
13
14
 
14
15
 
15
16
  if TYPE_CHECKING:
16
- from collections.abc import Awaitable
17
-
18
17
  from slashed.store import CommandStore
19
18
 
20
19
  TData = TypeVar("TData")
21
20
  type ConditionPredicate = Callable[[], bool]
21
+ type SyncCommandFunc = Callable[[CommandContext, list[str], dict[str, str]], None]
22
+ type AsyncCommandFunc = Callable[
23
+ [CommandContext, list[str], dict[str, str]], Awaitable[None]
24
+ ]
25
+ type CommandFunc = SyncCommandFunc | AsyncCommandFunc
22
26
 
23
27
 
24
28
  class OutputWriter(Protocol):
@@ -137,7 +141,8 @@ class Command(BaseCommand):
137
141
 
138
142
  def __init__(
139
143
  self,
140
- execute_func: ExecuteFunc,
144
+ execute_func: CommandFunc,
145
+ *,
141
146
  name: str | None = None,
142
147
  description: str | None = None,
143
148
  category: str = "general",
@@ -166,6 +171,7 @@ class Command(BaseCommand):
166
171
  self._execute_func = execute_func
167
172
  self._completer = completer
168
173
  self._condition = condition
174
+ self._is_async = inspect.iscoroutinefunction(execute_func)
169
175
 
170
176
  def is_available(self) -> bool:
171
177
  """Check if command is available based on condition."""
@@ -180,7 +186,12 @@ class Command(BaseCommand):
180
186
  kwargs: dict[str, str] | None = None,
181
187
  ):
182
188
  """Execute the command using provided function."""
183
- await self._execute_func(ctx, args or [], kwargs or {})
189
+ args = args or []
190
+ kwargs = kwargs or {}
191
+
192
+ result = self._execute_func(ctx, args, kwargs)
193
+ if inspect.isawaitable(result):
194
+ await cast(Awaitable[None], result)
184
195
 
185
196
  def get_completer(self) -> CompletionProvider | None:
186
197
  """Get completion provider."""
@@ -32,6 +32,7 @@ async def help_command(
32
32
  ):
33
33
  """Show available commands or detailed help for a specific command."""
34
34
  store = ctx.command_store
35
+ output_lines = []
35
36
 
36
37
  if args: # Detail for specific command
37
38
  name = args[0]
@@ -49,19 +50,20 @@ async def help_command(
49
50
  if cmd.help_text:
50
51
  sections.extend(["Help:", cmd.help_text])
51
52
 
52
- await ctx.output.print("\n".join(sections))
53
+ output_lines.extend(sections)
53
54
  else:
54
- await ctx.output.print(f"Unknown command: {name}")
55
- return
56
-
57
- # List all commands grouped by category
58
- categories = store.get_commands_by_category()
59
-
60
- await ctx.output.print("\nAvailable commands:")
61
- for category, commands in categories.items():
62
- await ctx.output.print(f"\n{category.title()}:")
63
- for cmd in commands:
64
- await ctx.output.print(f" /{cmd.name:<16} - {cmd.description}")
55
+ output_lines.append(f"Unknown command: {name}")
56
+ else:
57
+ # List all commands grouped by category
58
+ categories = store.get_commands_by_category()
59
+ output_lines.append("\nAvailable commands:")
60
+ for category, commands in categories.items():
61
+ output_lines.extend([
62
+ f"\n{category.title()}:",
63
+ *[f" /{cmd.name:<16} - {cmd.description}" for cmd in commands],
64
+ ])
65
+
66
+ await ctx.output.print("\n".join(output_lines))
65
67
 
66
68
 
67
69
  def create_help_completer() -> CompletionProvider:
@@ -2,7 +2,9 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from collections.abc import AsyncIterator
5
6
  from copy import copy
7
+ import inspect
6
8
  import os
7
9
  from typing import TYPE_CHECKING, Any
8
10
 
@@ -12,6 +14,9 @@ try:
12
14
  except ImportError:
13
15
  from pathlib import Path
14
16
 
17
+ from collections.abc import Awaitable, Iterable
18
+ from typing import TypeGuard, TypeVar, cast
19
+
15
20
  from slashed import utils
16
21
  from slashed.completion import CompletionItem, CompletionProvider
17
22
  from slashed.log import get_logger
@@ -21,12 +26,22 @@ type PathType = str | os.PathLike[str]
21
26
 
22
27
 
23
28
  if TYPE_CHECKING:
24
- from collections.abc import Callable, Iterable, Iterator, Sequence
29
+ from collections.abc import (
30
+ Awaitable,
31
+ Callable,
32
+ Sequence,
33
+ )
25
34
 
26
35
  from slashed.completion import CompletionContext
27
36
  from slashed.slashed_types import CompletionKind
28
37
 
29
38
  logger = get_logger(__name__)
39
+ T = TypeVar("T")
40
+
41
+
42
+ def is_awaitable(obj: Awaitable[T] | T) -> TypeGuard[Awaitable[T]]:
43
+ """Type guard to check if object is awaitable."""
44
+ return inspect.isawaitable(obj)
30
45
 
31
46
 
32
47
  class PathCompleter(CompletionProvider):
@@ -59,10 +74,10 @@ class PathCompleter(CompletionProvider):
59
74
  self.expanduser = expanduser
60
75
  self.base_path = Path(base_path).resolve() if base_path else None
61
76
 
62
- def get_completions(
77
+ async def get_completions(
63
78
  self,
64
79
  context: CompletionContext,
65
- ) -> Iterator[CompletionItem]:
80
+ ) -> AsyncIterator[CompletionItem]:
66
81
  """Get path completions."""
67
82
  word = context.current_word or "."
68
83
 
@@ -150,10 +165,10 @@ class EnvVarCompleter(CompletionProvider):
150
165
  self.prefixes = prefixes
151
166
  self.include_values = include_values
152
167
 
153
- def get_completions(
168
+ async def get_completions(
154
169
  self,
155
170
  context: CompletionContext,
156
- ) -> Iterator[CompletionItem]:
171
+ ) -> AsyncIterator[CompletionItem]:
157
172
  """Get environment variable completions."""
158
173
  word = context.current_word.lstrip("$")
159
174
 
@@ -188,10 +203,10 @@ class ChoiceCompleter(CompletionProvider):
188
203
  self.choices = list(choices)
189
204
  self.descriptions = {}
190
205
 
191
- def get_completions(
206
+ async def get_completions(
192
207
  self,
193
208
  context: CompletionContext,
194
- ) -> Iterator[CompletionItem]:
209
+ ) -> AsyncIterator[CompletionItem]:
195
210
  """Get matching choices."""
196
211
  word = context.current_word
197
212
  if self.ignore_case:
@@ -225,28 +240,37 @@ class MultiValueCompleter(CompletionProvider):
225
240
  self.delimiter = delimiter
226
241
  self.strip = strip
227
242
 
228
- def get_completions(
243
+ async def get_completions(
229
244
  self,
230
245
  context: CompletionContext,
231
- ) -> Iterator[CompletionItem]:
246
+ ) -> AsyncIterator[CompletionItem]:
232
247
  """Get completions for current value."""
233
- # Split into values and get current value
234
- values = context.current_word.split(self.delimiter)
235
- current = values[-1]
248
+ # Use full text instead of just current_word for splitting
249
+ full_text = context._document.text
250
+ values = full_text.split(self.delimiter)
251
+
252
+ # Current value is what's being typed
253
+ current = context.current_word
236
254
  if self.strip:
237
255
  current = current.strip()
256
+
257
+ # Create modified context with just the current value
238
258
  mod_context = copy(context)
239
259
  mod_context._current_word = current # type: ignore[attr-defined]
240
260
 
241
- # Get completions from base provider
242
- prefix = self.delimiter.join(values[:-1])
243
- if prefix:
261
+ # Build prefix from previous values if we have more than one value
262
+ prefix = ""
263
+ if len(values) > 1:
264
+ prefix = self.delimiter.join(values[:-1])
244
265
  prefix = f"{prefix}{self.delimiter}"
245
266
  if self.strip:
246
267
  prefix = f"{prefix} "
247
268
 
248
- for item in self.provider.get_completions(mod_context):
249
- item.text = f"{prefix}{item.text}"
269
+ # Get completions and add prefix
270
+ async for item in self.provider.get_completions(mod_context):
271
+ item = copy(item) # Don't modify original item
272
+ if prefix:
273
+ item.text = f"{prefix}{item.text}"
250
274
  yield item
251
275
 
252
276
 
@@ -267,10 +291,10 @@ class KeywordCompleter(CompletionProvider):
267
291
  self.keywords = keywords
268
292
  self.value_provider = value_provider
269
293
 
270
- def get_completions(
294
+ async def get_completions(
271
295
  self,
272
296
  context: CompletionContext,
273
- ) -> Iterator[CompletionItem]:
297
+ ) -> AsyncIterator[CompletionItem]:
274
298
  """Get keyword completions."""
275
299
  word = context.current_word
276
300
 
@@ -286,7 +310,8 @@ class KeywordCompleter(CompletionProvider):
286
310
  if self.value_provider and context.arg_position > 0:
287
311
  prev_arg = context.command_args[context.arg_position - 1]
288
312
  if prev_arg.startswith("--"):
289
- yield from self.value_provider.get_completions(context)
313
+ async for item in self.value_provider.get_completions(context):
314
+ yield item
290
315
 
291
316
 
292
317
  class ChainedCompleter(CompletionProvider):
@@ -300,13 +325,14 @@ class ChainedCompleter(CompletionProvider):
300
325
  """
301
326
  self.providers = providers
302
327
 
303
- def get_completions(
328
+ async def get_completions(
304
329
  self,
305
330
  context: CompletionContext,
306
- ) -> Iterator[CompletionItem]:
331
+ ) -> AsyncIterator[CompletionItem]:
307
332
  """Get completions from all providers."""
308
333
  for provider in self.providers:
309
- yield from provider.get_completions(context)
334
+ async for item in provider.get_completions(context):
335
+ yield item
310
336
 
311
337
 
312
338
  class CallbackCompleter(CompletionProvider):
@@ -328,25 +354,33 @@ class CallbackCompleter(CompletionProvider):
328
354
 
329
355
  def __init__(
330
356
  self,
331
- callback: Callable[[CompletionContext], Iterable[str | CompletionItem]],
357
+ callback: (
358
+ Callable[[CompletionContext], Iterable[str | CompletionItem]]
359
+ | Callable[[CompletionContext], Awaitable[Iterable[str | CompletionItem]]]
360
+ ),
332
361
  kind: CompletionKind | None = None,
333
362
  ):
334
- """Initialize callback completer.
363
+ self._callback = callback
364
+ self._kind = kind
365
+ self._is_async = inspect.iscoroutinefunction(callback)
335
366
 
336
- Args:
337
- callback: Function that returns completions as strings or CompletionItems
338
- kind: Optional kind to apply to string completions
339
- """
340
- self.callback = callback
341
- self.kind = kind
342
-
343
- def get_completions(
367
+ async def get_completions(
344
368
  self,
345
369
  context: CompletionContext,
346
- ) -> Iterator[CompletionItem]:
347
- """Get completions by calling the callback function."""
348
- for item in self.callback(context):
349
- if isinstance(item, str):
350
- yield CompletionItem(text=item, kind=self.kind) # pyright: ignore
370
+ ) -> AsyncIterator[CompletionItem]:
371
+ try:
372
+ result = self._callback(context)
373
+
374
+ # Narrow type and handle async/sync appropriately
375
+ if is_awaitable(result):
376
+ items = await result
351
377
  else:
352
- yield item
378
+ items = cast(Iterable[str | CompletionItem], result)
379
+
380
+ for item in items:
381
+ if isinstance(item, str):
382
+ yield CompletionItem(text=item, kind=self._kind) # type: ignore
383
+ else:
384
+ yield item
385
+ except Exception as e: # noqa: BLE001
386
+ logger.debug("Completion callback error: %s", e)
@@ -12,7 +12,7 @@ from slashed.log import get_logger
12
12
 
13
13
 
14
14
  if TYPE_CHECKING:
15
- from collections.abc import Iterator
15
+ from collections.abc import AsyncIterator
16
16
 
17
17
  from prompt_toolkit.document import Document
18
18
 
@@ -142,16 +142,8 @@ class CompletionProvider(ABC):
142
142
  def get_completions(
143
143
  self,
144
144
  context: CompletionContext,
145
- ) -> Iterator[CompletionItem]:
146
- """Get completion suggestions.
147
-
148
- Args:
149
- context: Current completion context
150
-
151
- Returns:
152
- Iterator of completion suggestions
153
- """
154
- ...
145
+ ) -> AsyncIterator[CompletionItem]:
146
+ """Get completion suggestions."""
155
147
 
156
148
 
157
149
  class CommandCompleter:
@@ -170,10 +162,10 @@ class CommandCompleter:
170
162
  """Add a global completion provider."""
171
163
  self._global_providers.append(provider)
172
164
 
173
- def get_completions(
165
+ async def get_completions(
174
166
  self,
175
167
  context: CompletionContext,
176
- ) -> Iterator[CompletionItem]:
168
+ ) -> AsyncIterator[CompletionItem]:
177
169
  """Get completions for the current context."""
178
170
  # If at start of command, complete command names
179
171
  logger.debug("Getting completions for command %s", context.command_name)
@@ -193,12 +185,15 @@ class CommandCompleter:
193
185
  yield CompletionItem(text=name, metadata=meta, kind="command")
194
186
  return
195
187
  # Get command-specific completions
188
+ # Get command-specific completions
196
189
  command = self._commands.get(context.command_name)
197
190
  if command and (completer := command.get_completer()):
198
191
  logger.debug("Fetching completions for command %s", command.name)
199
- yield from completer.get_completions(context) # type: ignore
192
+ async for item in completer.get_completions(context):
193
+ yield item
200
194
 
201
195
  # Get global completions
202
196
  for provider in self._global_providers:
203
197
  logger.debug("Fetching completions for provider %r", provider)
204
- yield from provider.get_completions(context)
198
+ async for item in provider.get_completions(context):
199
+ yield item
@@ -142,3 +142,6 @@ class SignalingOutputWriter(OutputWriter):
142
142
  async def print(self, message: str) -> None:
143
143
  self._output_signal.emit(message)
144
144
  await self._base_writer.print(message)
145
+
146
+ def __getattr__(self, name: str) -> Any:
147
+ return getattr(self._base_writer, name)
@@ -14,7 +14,7 @@ from slashed.utils import get_first_line
14
14
 
15
15
 
16
16
  if TYPE_CHECKING:
17
- from collections.abc import Iterator
17
+ from collections.abc import AsyncGenerator, Iterable
18
18
 
19
19
  from prompt_toolkit.document import Document
20
20
 
@@ -26,12 +26,7 @@ logger = get_logger(__name__)
26
26
 
27
27
 
28
28
  class PromptToolkitCompleter[TContextData](Completer):
29
- """Adapts our completion system to prompt-toolkit.
30
-
31
- Type Parameters:
32
- TContextData: Type of the data in the associated CommandContext. Used when
33
- completions need to access typed context data.
34
- """
29
+ """Adapts our completion system to prompt-toolkit."""
35
30
 
36
31
  def __init__(
37
32
  self,
@@ -55,10 +50,14 @@ class PromptToolkitCompleter[TContextData](Completer):
55
50
  )
56
51
 
57
52
  def get_completions(
58
- self,
59
- document: Document,
60
- complete_event: Any,
61
- ) -> Iterator[Completion]:
53
+ self, document: Document, complete_event: Any
54
+ ) -> Iterable[Completion]:
55
+ """Sync completions - not used but required by interface."""
56
+ return []
57
+
58
+ async def get_completions_async(
59
+ self, document: Document, complete_event: Any
60
+ ) -> AsyncGenerator[Completion, None]:
62
61
  """Get completions for the current context."""
63
62
  text = document.text.lstrip()
64
63
 
@@ -77,13 +76,13 @@ class PromptToolkitCompleter[TContextData](Completer):
77
76
  completer := command.get_completer()
78
77
  ):
79
78
  current_word = completion_context.current_word
80
- for item in completer.get_completions(completion_context):
79
+ async for item in completer.get_completions(completion_context):
81
80
  if current_word and not item.text.startswith(current_word):
82
81
  continue
83
82
  start_pos = -len(current_word) if current_word else 0
84
83
  yield Completion(
85
84
  item.text,
86
- start_pos,
85
+ start_position=start_pos,
87
86
  display_meta=get_first_line(item.metadata),
88
87
  )
89
88
  return
@@ -93,7 +92,9 @@ class PromptToolkitCompleter[TContextData](Completer):
93
92
  for cmd in self._store.list_commands():
94
93
  if cmd.name.startswith(word):
95
94
  yield Completion(
96
- cmd.name, -len(word), display_meta=get_first_line(cmd.description)
95
+ cmd.name,
96
+ start_position=-len(word),
97
+ display_meta=get_first_line(cmd.description),
97
98
  )
98
99
 
99
100
  except RuntimeError as e:
@@ -12,7 +12,7 @@ from slashed.log import get_logger
12
12
 
13
13
 
14
14
  if TYPE_CHECKING:
15
- from collections.abc import Iterator
15
+ from collections.abc import AsyncIterator, Iterator
16
16
 
17
17
  from slashed.base import OutputWriter
18
18
  from slashed.store import CommandStore
@@ -358,10 +358,10 @@ class CommandRouter[TGlobalContext, TRouteContext]:
358
358
  )
359
359
  await self.commands.execute_command(parsed.command, ctx)
360
360
 
361
- def get_completions(
361
+ async def get_completions(
362
362
  self,
363
363
  context: CompletionContext,
364
- ) -> Iterator[CompletionItem]:
364
+ ) -> AsyncIterator[CompletionItem]:
365
365
  """Get completions including route prefixes."""
366
366
  word = context.current_word
367
367
  text = context._document.text
@@ -398,7 +398,10 @@ class CommandRouter[TGlobalContext, TRouteContext]:
398
398
  # Use the command completer
399
399
  if command := self.commands._commands.get(word):
400
400
  if completer := command.get_completer():
401
- yield from completer.get_completions(route_completion_ctx)
401
+ async for item in completer.get_completions(
402
+ route_completion_ctx
403
+ ):
404
+ yield item
402
405
  # Or suggest commands
403
406
  else:
404
407
  commands = self.commands.list_commands()
@@ -425,7 +428,10 @@ class CommandRouter[TGlobalContext, TRouteContext]:
425
428
  # First try command completer if we have a word
426
429
  if word and (command := self.commands._commands.get(word)):
427
430
  if completer := command.get_completer():
428
- yield from completer.get_completions(global_completion_ctx)
431
+ async for item in completer.get_completions(
432
+ global_completion_ctx
433
+ ):
434
+ yield item
429
435
  # Otherwise suggest commands
430
436
  else:
431
437
  for cmd in self.commands.list_commands():
@@ -10,6 +10,7 @@ from textual.widgets import Input, Label
10
10
 
11
11
  from slashed.base import BaseCommand, OutputWriter
12
12
  from slashed.log import get_logger
13
+ from slashed.output import SignalingOutputWriter
13
14
  from slashed.store import CommandStore
14
15
  from slashed.textual_adapter.suggester import SlashedSuggester
15
16
 
@@ -159,7 +160,7 @@ class SlashedApp[TContext, TResult](App[TResult]): # type: ignore[type-var]
159
160
  default: Whether this is the default output
160
161
  """
161
162
  writer = self.context.output
162
- if not isinstance(writer, TextualOutputWriter):
163
+ if not isinstance(writer, TextualOutputWriter | SignalingOutputWriter):
163
164
  msg = "Output writer is not a TextualOutputWriter"
164
165
  raise TypeError(msg)
165
166
  writer.bind(output_id, widget_query, default=default)
@@ -87,7 +87,7 @@ class CommandInput[TContext](Input, CommandWidgetMixin[TContext]):
87
87
  def get_cursor_screen_position(self) -> tuple[int, int]:
88
88
  return self.cursor_screen_offset
89
89
 
90
- def _get_completions(self) -> list[CompletionItem]:
90
+ async def _get_completions(self) -> list[CompletionItem]:
91
91
  document = Document(text=self.value, cursor_position=self.cursor_position)
92
92
  completion_context = CompletionContext(
93
93
  document=document, command_context=self.context
@@ -139,17 +139,17 @@ class CommandInput[TContext](Input, CommandWidgetMixin[TContext]):
139
139
  )
140
140
 
141
141
  self.logger.debug("Getting completions for argument: %r", arg_text)
142
- completions = list(completer.get_completions(arg_context))
142
+ completions = [i async for i in completer.get_completions(arg_context)]
143
143
  self.logger.debug("Got %d completions", len(completions))
144
144
  return completions
145
145
 
146
146
  return []
147
147
 
148
- def _update_completions(self) -> None:
148
+ async def _update_completions(self) -> None:
149
149
  """Update the completion dropdown."""
150
150
  self.logger.debug("Updating completions...")
151
151
 
152
- completions = self._get_completions()
152
+ completions = await self._get_completions()
153
153
  self._dropdown.clear_options()
154
154
 
155
155
  if completions:
@@ -272,11 +272,11 @@ class CommandInput[TContext](Input, CommandWidgetMixin[TContext]):
272
272
  self.post_message(self.InputSubmitted(text))
273
273
  self.clear_input()
274
274
 
275
- def on_input_changed(self, message: Input.Changed) -> None:
275
+ async def on_input_changed(self, message: Input.Changed) -> None:
276
276
  """Update completions when input changes."""
277
277
  self.logger.debug("Input changed: %s", self.value)
278
278
 
279
279
  if self.value.startswith("/"):
280
- self._update_completions()
280
+ await self._update_completions()
281
281
  else:
282
282
  self.action_hide_dropdown()
@@ -94,7 +94,7 @@ class CommandTextArea[TContext](TextArea, CommandWidgetMixin[TContext]):
94
94
  """Get cursor position in screen coordinates."""
95
95
  return self.cursor_screen_offset
96
96
 
97
- def _get_completions(self) -> list[CompletionItem]:
97
+ async def _get_completions(self) -> list[CompletionItem]:
98
98
  first_line = self.get_first_line()
99
99
  if not first_line.startswith("/"):
100
100
  return []
@@ -152,17 +152,17 @@ class CommandTextArea[TContext](TextArea, CommandWidgetMixin[TContext]):
152
152
  )
153
153
 
154
154
  self.logger.debug("Getting completions for argument: %r", arg_text)
155
- completions = list(completer.get_completions(arg_context))
155
+ completions = [i async for i in completer.get_completions(arg_context)]
156
156
  self.logger.debug("Got %d completions", len(completions))
157
157
  return completions
158
158
 
159
159
  return []
160
160
 
161
- def _update_completions(self) -> None:
161
+ async def _update_completions(self) -> None:
162
162
  """Update the completion dropdown."""
163
163
  self.logger.debug("Updating completions...")
164
164
 
165
- completions = self._get_completions()
165
+ completions = await self._get_completions()
166
166
  self._dropdown.clear_options()
167
167
 
168
168
  if completions:
@@ -294,9 +294,9 @@ class CommandTextArea[TContext](TextArea, CommandWidgetMixin[TContext]):
294
294
  event.prevent_default()
295
295
  event.stop()
296
296
 
297
- def on_text_area_changed(self, message: TextArea.Changed) -> None:
297
+ async def on_text_area_changed(self, message: TextArea.Changed) -> None:
298
298
  """Handle text changes."""
299
299
  if self.is_command_mode:
300
- self._update_completions()
300
+ await self._update_completions()
301
301
  else:
302
302
  self.action_hide_dropdown()
@@ -60,7 +60,9 @@ class SlashedSuggester(Suggester):
60
60
  if completer := command.get_completer():
61
61
  current_word = completion_context.current_word
62
62
  # Find first matching completion
63
- for completion in completer.get_completions(completion_context):
63
+ async for completion in completer.get_completions(
64
+ completion_context
65
+ ):
64
66
  if not current_word or completion.text.startswith(
65
67
  current_word
66
68
  ):
@@ -0,0 +1,108 @@
1
+ from collections.abc import AsyncIterator
2
+ from typing import Any
3
+ from unittest.mock import MagicMock
4
+
5
+ import pytest
6
+
7
+ from slashed.completers import KeywordCompleter, MultiValueCompleter
8
+ from slashed.completion import CompletionContext, CompletionItem, CompletionProvider
9
+
10
+
11
+ class TestCompleter(CompletionProvider):
12
+ async def get_completions(
13
+ self, context: CompletionContext
14
+ ) -> AsyncIterator[CompletionItem]:
15
+ yield CompletionItem(text="test")
16
+ yield CompletionItem(text="test2")
17
+
18
+
19
+ @pytest.fixture
20
+ def mock_document():
21
+ doc = MagicMock()
22
+ doc.text = "test"
23
+ doc.cursor_position = 4
24
+ doc.get_word_before_cursor.return_value = "test"
25
+ return doc
26
+
27
+
28
+ @pytest.mark.asyncio
29
+ async def test_basic_completer(mock_document):
30
+ completer = TestCompleter()
31
+ context = CompletionContext[Any](document=mock_document)
32
+
33
+ items = []
34
+ async for item in completer.get_completions(context):
35
+ items.append(item) # noqa: PERF401
36
+
37
+ assert len(items) == 2 # noqa: PLR2004
38
+ assert items[0].text == "test"
39
+ assert items[1].text == "test2"
40
+
41
+
42
+ @pytest.mark.asyncio
43
+ async def test_multi_value_completer(mock_document):
44
+ base_completer = TestCompleter()
45
+ multi_completer = MultiValueCompleter(base_completer, delimiter=",")
46
+
47
+ # Test single value completion
48
+ mock_document.text = "te"
49
+ mock_document.get_word_before_cursor.return_value = "te"
50
+ context = CompletionContext[Any](document=mock_document)
51
+
52
+ items = []
53
+ async for item in multi_completer.get_completions(context):
54
+ items.append(item) # noqa: PERF401
55
+
56
+ assert len(items) == 2 # noqa: PLR2004
57
+ assert items[0].text == "test"
58
+ assert items[1].text == "test2"
59
+
60
+ # Test completion with existing value
61
+ mock_document.text = "value1, te"
62
+ mock_document.get_word_before_cursor.return_value = "te"
63
+ context = CompletionContext[Any](document=mock_document)
64
+
65
+ items = []
66
+ async for item in multi_completer.get_completions(context):
67
+ items.append(item)
68
+
69
+ assert len(items) == 2 # noqa: PLR2004
70
+ assert items[0].text == "value1, test"
71
+ assert items[1].text == "value1, test2"
72
+
73
+
74
+ @pytest.mark.asyncio
75
+ async def test_keyword_completer(mock_document):
76
+ keywords = {"param1": "First parameter", "param2": "Second parameter"}
77
+ value_completer = TestCompleter()
78
+ completer = KeywordCompleter(keywords, value_completer)
79
+
80
+ # Test keyword completion
81
+ mock_document.text = "--"
82
+ mock_document.get_word_before_cursor.return_value = "--"
83
+ context = CompletionContext[Any](document=mock_document)
84
+
85
+ items = [item async for item in completer.get_completions(context)]
86
+ assert len(items) == 2 # noqa: PLR2004
87
+ assert all(item.text.startswith("--") for item in items)
88
+ assert {"--param1", "--param2"} == {item.text for item in items}
89
+
90
+ # Test value completion
91
+ mock_document.text = "--param1 t"
92
+ mock_document.get_word_before_cursor.return_value = "t"
93
+ context = CompletionContext[Any](document=mock_document)
94
+ context._args = ["--param1", "t"]
95
+ context._arg_position = 1
96
+
97
+ items = []
98
+ async for item in completer.get_completions(context):
99
+ items.append(item)
100
+
101
+ assert len(items) == 2 # noqa: PLR2004
102
+ assert {"test", "test2"} == {item.text for item in items}
103
+
104
+
105
+ if __name__ == "__main__":
106
+ import pytest
107
+
108
+ pytest.main([__file__])
@@ -241,7 +241,8 @@ class TestContextSwitching:
241
241
  class TestCompletion:
242
242
  """Test command completion with routing."""
243
243
 
244
- def test_route_completion(self, router: CommandRouter):
244
+ @pytest.mark.asyncio # Add this if not already present
245
+ async def test_route_completion(self, router: CommandRouter):
245
246
  """Test completing route prefixes."""
246
247
  doc = MagicMock()
247
248
  doc.text = "@"
@@ -249,14 +250,14 @@ class TestCompletion:
249
250
  doc.get_word_before_cursor.return_value = "@"
250
251
  context: CompletionContext[Any] = CompletionContext(doc)
251
252
 
252
- # Create command store context for completions
253
253
  store_ctx: CommandContext[Any] = router.commands.create_context(
254
254
  router.global_context,
255
255
  output_writer=_TestOutputWriter(),
256
256
  )
257
257
  context._command_context = store_ctx
258
258
 
259
- completions = list(router.get_completions(context))
259
+ # Use list comprehension with async for
260
+ completions = [item async for item in router.get_completions(context)]
260
261
  assert len(completions) == 2 # noqa: PLR2004
261
262
  assert any(c.text == "@db" for c in completions)
262
263
  assert any(c.text == "@fs" for c in completions)
@@ -268,30 +269,28 @@ class TestCompletion:
268
269
  context = CompletionContext[Any](doc)
269
270
  context._command_context = store_ctx
270
271
 
271
- completions = list(router.get_completions(context))
272
+ completions = [item async for item in router.get_completions(context)]
272
273
  assert len(completions) == 1
273
274
  assert completions[0].text == "@db"
274
275
 
275
- def test_command_completion(self, router: CommandRouter):
276
+ @pytest.mark.asyncio
277
+ async def test_command_completion(self, router: CommandRouter):
276
278
  """Test completing commands with routing."""
277
279
  doc = MagicMock()
278
- # For "@db " completion
279
280
  doc.text = "@db "
280
281
  doc.cursor_position = len("@db ")
281
282
  doc.get_word_before_cursor.return_value = ""
282
283
  context: CompletionContext[Any] = CompletionContext(doc)
283
284
 
284
- # Create command store context for completions
285
285
  store_ctx: CommandContext[Any] = router.commands.create_context(
286
286
  router._routes["db"].context,
287
287
  output_writer=_TestOutputWriter(),
288
288
  )
289
289
  context._command_context = store_ctx
290
290
 
291
- completions = list(router.get_completions(context))
292
- assert any(c.text == "query" for c in completions), (
293
- "Expected 'query' in completions"
294
- )
291
+ # Use list comprehension with async for
292
+ completions = [item async for item in router.get_completions(context)]
293
+ assert any(c.text == "query" for c in completions)
295
294
 
296
295
  # Test completing global commands
297
296
  doc.text = "t"
@@ -299,17 +298,14 @@ class TestCompletion:
299
298
  doc.get_word_before_cursor.return_value = "t"
300
299
  context = CompletionContext[Any](doc)
301
300
 
302
- # Use global context for completion
303
301
  store_ctx = router.commands.create_context(
304
302
  router.global_context,
305
303
  output_writer=_TestOutputWriter(),
306
304
  )
307
305
  context._command_context = store_ctx
308
306
 
309
- completions = list(router.get_completions(context))
310
- assert any(c.text == "test" for c in completions), (
311
- "Expected 'test' in completions"
312
- )
307
+ completions = [item async for item in router.get_completions(context)]
308
+ assert any(c.text == "test" for c in completions)
313
309
 
314
310
 
315
311
  class TestErrorHandling:
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes