qkrun 2.0.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.
qkrun/__init__.py ADDED
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env python
2
+ # PYTHON_ARGCOMPLETE_OK
3
+ """A CLI tool for quick tasks."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import typing
8
+
9
+ from ._meta import __author__, __copyright__, __email__, __home__, __version__
10
+
11
+ if typing.TYPE_CHECKING:
12
+ # Static imports for type checkers (Pylance/Pyright) — never executed at runtime
13
+ from qkrun.factories import (
14
+ command,
15
+ task_factory_helper,
16
+ group,
17
+ script,
18
+ task,
19
+ thread_group,
20
+ )
21
+ from qkrun.tasks import (
22
+ Command,
23
+ Group,
24
+ OutputMode,
25
+ Script,
26
+ Task,
27
+ ThreadGroup,
28
+ )
29
+ from qkrun._namespace import Namespace, namespace
30
+ from qkrun.config import app, console, logger
31
+ from qkrun import context
32
+ from qkrun.context import Context, load_env_file
33
+ from qkrun.utils.argparser import Arg
34
+
35
+ __all__ = [
36
+ "__author__",
37
+ "__copyright__",
38
+ "__email__",
39
+ "__home__",
40
+ "__version__",
41
+ "app",
42
+ "console",
43
+ "logger",
44
+ "context",
45
+ "Context",
46
+ "load_env_file",
47
+ "Task",
48
+ "Script",
49
+ "Command",
50
+ "Group",
51
+ "ThreadGroup",
52
+ "OutputMode",
53
+ "Namespace",
54
+ "namespace",
55
+ "task",
56
+ "script",
57
+ "command",
58
+ "Arg",
59
+ "task_factory_helper",
60
+ "group",
61
+ "thread_group",
62
+ ]
63
+
64
+ # Lazy import mapping: symbol name -> (module_path, symbol_name)
65
+ _LAZY_IMPORTS: dict[str, tuple[str, str]] = {
66
+ # factories
67
+ "command": ("qkrun.factories", "command"),
68
+ "task_factory_helper": ("qkrun.factories", "task_factory_helper"),
69
+ "group": ("qkrun.factories", "group"),
70
+ "script": ("qkrun.factories", "script"),
71
+ "task": ("qkrun.factories", "task"),
72
+ "thread_group": ("qkrun.factories", "thread_group"),
73
+ # tasks
74
+ "Command": ("qkrun.tasks", "Command"),
75
+ "Group": ("qkrun.tasks", "Group"),
76
+ "OutputMode": ("qkrun.tasks", "OutputMode"),
77
+ "Script": ("qkrun.tasks", "Script"),
78
+ "Task": ("qkrun.tasks", "Task"),
79
+ "ThreadGroup": ("qkrun.tasks", "ThreadGroup"),
80
+ # namespace
81
+ "Namespace": ("qkrun._namespace", "Namespace"),
82
+ "namespace": ("qkrun._namespace", "namespace"),
83
+ # config
84
+ "app": ("qkrun.config", "app"),
85
+ "console": ("qkrun.config", "console"),
86
+ "logger": ("qkrun.config", "logger"),
87
+ # context
88
+ "context": ("qkrun", "context"),
89
+ "Context": ("qkrun.context", "Context"),
90
+ "load_env_file": ("qkrun.context", "load_env_file"),
91
+ # utils
92
+ "Arg": ("qkrun.utils.argparser", "Arg"),
93
+ }
94
+
95
+
96
+ def __getattr__(name: str):
97
+ if name in _LAZY_IMPORTS:
98
+ module_path, symbol_name = _LAZY_IMPORTS[name]
99
+ import importlib
100
+
101
+ module = importlib.import_module(module_path)
102
+ value = getattr(module, symbol_name)
103
+ # Cache on the module so subsequent accesses are fast
104
+ globals()[name] = value
105
+ return value
106
+ raise AttributeError(f"module 'qkrun' has no attribute {name!r}")
qkrun/__main__.py ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env python
2
+ # PYTHON_ARGCOMPLETE_OK
3
+ """Entry point for the application script."""
4
+
5
+ import sys
6
+
7
+ from ._cli import main
8
+
9
+
10
+ def _run_main():
11
+ if __name__ == "__main__":
12
+ argv = sys.argv[1:]
13
+ main(argv)
14
+
15
+
16
+ _run_main()
qkrun/_argparser.py ADDED
@@ -0,0 +1,226 @@
1
+ """Custom argument parser for qkrun."""
2
+
3
+ import sys
4
+ import typing
5
+ from argparse import SUPPRESS, ArgumentParser, RawDescriptionHelpFormatter
6
+
7
+ import argcomplete
8
+
9
+ from qkrun._meta import __version__ as version
10
+ from qkrun.commands import COMMANDS
11
+ from qkrun.completion._internal import TaskCompleter
12
+
13
+
14
+ class BaseArgumentParser(ArgumentParser):
15
+ """Base argument parser with common arguments for qk and qk-mcp.
16
+
17
+ Includes: verbosity, log-file, version, module path, and global flag.
18
+ """
19
+
20
+ @typing.override
21
+ def __init__(self, **kwargs):
22
+ super().__init__(**kwargs)
23
+ self._add_common_arguments()
24
+
25
+ def _add_common_arguments(self) -> None:
26
+ """Add arguments common to both qk and qk-mcp."""
27
+ self.add_argument(
28
+ "-v",
29
+ "--verbose",
30
+ action="count",
31
+ dest="verbosity",
32
+ default=0,
33
+ help="Increase verbosity (repeat for increased verbosity)",
34
+ )
35
+ self.add_argument(
36
+ "-q",
37
+ "--quiet",
38
+ action="store_const",
39
+ const=-1,
40
+ default=0,
41
+ dest="verbosity",
42
+ help="Decrease verbosity (show errors only)",
43
+ )
44
+ self.add_argument(
45
+ "--log-file",
46
+ type=str,
47
+ help="The file to log to. If not set, logs to stdout.",
48
+ )
49
+ self.add_argument("-V", "--version", action="version", version=version)
50
+
51
+
52
+ class AppArgumentParser(BaseArgumentParser):
53
+ """Custom argument parser for qkrun."""
54
+
55
+ @typing.override
56
+ def __init__(self):
57
+ super().__init__(
58
+ usage="qk [OPTIONS] COMMAND ... | qk [OPTIONS] TASK [ARGS ...]",
59
+ description="A CLI tool for quick tasks.",
60
+ epilog=(
61
+ "Examples:\n"
62
+ " qk build\n"
63
+ " qk test unit --fast\n"
64
+ " qk :list\n"
65
+ " qk :watch --paths src build"
66
+ ),
67
+ formatter_class=RawDescriptionHelpFormatter,
68
+ )
69
+ self._add_app_arguments()
70
+
71
+ def _add_app_arguments(self) -> None:
72
+ """Add arguments specific to the qk CLI."""
73
+ self.add_argument(
74
+ "-m", "--module", type=str, help="The module to load tasks from"
75
+ )
76
+ self.add_argument(
77
+ "-g",
78
+ "--global",
79
+ action="store_true",
80
+ dest="use_global",
81
+ help="Use global tasks from ~/_qkg instead of project tasks",
82
+ )
83
+ self.set_defaults(task=None, args=[])
84
+ commands = self.add_subparsers(
85
+ dest="command",
86
+ title="commands",
87
+ description="Built in commands.",
88
+ metavar="COMMAND",
89
+ parser_class=ArgumentParser,
90
+ )
91
+ self.commands_action = commands
92
+ self.command_parsers: dict[str, ArgumentParser] = {}
93
+ # Register each command, letting it configure its own parser
94
+ public_command_names: list[str] = []
95
+ for name, command in COMMANDS.items():
96
+ if name == ":run":
97
+ # :run is hidden from help; kept as the default runner for
98
+ # bare task names via _normalize_args.
99
+ run = commands.add_parser(":run", help=SUPPRESS, add_help=False)
100
+ commands._choices_actions.pop()
101
+ self.run_parser = run
102
+ self.command_parsers[":run"] = run
103
+ else:
104
+ parser = commands.add_parser(
105
+ name,
106
+ help=command.__doc__,
107
+ usage=f"qk {name} [OPTIONS]",
108
+ description=command.__doc__,
109
+ )
110
+ public_command_names.append(name)
111
+ self.command_parsers[name] = parser
112
+ command.configure_parser(run if name == ":run" else parser) # type: ignore[possibly-undefined]
113
+ commands.completer = argcomplete.completers.ChoicesCompleter( # type: ignore
114
+ public_command_names # type: ignore[arg-type]
115
+ )
116
+ self.add_argument(
117
+ "task_name",
118
+ nargs="?",
119
+ metavar="TASK",
120
+ help="Name of the task to run",
121
+ ).completer = TaskCompleter() # type: ignore
122
+ self.add_argument(
123
+ "task_args",
124
+ nargs="*",
125
+ metavar="ARGS",
126
+ help="Arguments passed to the task",
127
+ )
128
+ self.task_completion_parser = BaseArgumentParser(
129
+ prog=self.prog,
130
+ description=self.description,
131
+ add_help=False,
132
+ )
133
+ self.task_completion_parser.add_argument(
134
+ "-m", "--module", type=str, help=SUPPRESS
135
+ )
136
+ self.task_completion_parser.add_argument(
137
+ "-g", "--global", action="store_true", dest="use_global", help=SUPPRESS
138
+ )
139
+ self.task_completion_parser.add_argument(
140
+ "-h", "--help", action="help", help="Show this help message and exit"
141
+ )
142
+ self.task_completion_parser.add_argument(
143
+ "task",
144
+ nargs="?",
145
+ help=SUPPRESS,
146
+ ).completer = TaskCompleter( # type: ignore
147
+ {
148
+ name: command.__doc__ or ""
149
+ for name, command in COMMANDS.items()
150
+ if name != ":run"
151
+ }
152
+ )
153
+
154
+ def _command_index(self, args: list[str]) -> int | None:
155
+ """Locate the command or task after global options."""
156
+ value_flags = {"-m", "--module", "--log-file"}
157
+ iterator = iter(enumerate(args))
158
+ for index, arg in iterator:
159
+ if arg in value_flags:
160
+ next(iterator, None)
161
+ elif not arg.startswith("-"):
162
+ return index
163
+ return None
164
+
165
+ def _normalize_args(self, args: list[str]) -> list[str]:
166
+ """Route ordinary task invocations through the hidden run subcommand."""
167
+ index = self._command_index(args)
168
+ if index is not None and not args[index].startswith(":"):
169
+ return args[:index] + [":run"] + args[index:]
170
+ return args
171
+
172
+ @typing.override
173
+ def parse_args(self, args=None, namespace=None):
174
+ if args is None:
175
+ args = sys.argv[1:]
176
+ parsed, unknown = self.parse_known_args(args, namespace)
177
+ if unknown:
178
+ self.error(f"unrecognized arguments: {' '.join(unknown)}")
179
+ return parsed
180
+
181
+ @typing.override
182
+ def parse_known_args(self, args=None, namespace=None):
183
+ if args is None:
184
+ args = sys.argv[1:]
185
+ normalized = self._normalize_args(list(args))
186
+ parsed, unknown = super().parse_known_args(normalized, namespace)
187
+ if parsed.command in (":run", ":watch") and parsed.task:
188
+ tail_index = len(normalized) - len(parsed.args)
189
+ # argparse consumes a separator immediately following the task.
190
+ if normalized[tail_index - 1] == "--":
191
+ parsed.args.insert(0, "--")
192
+ return parsed, unknown
193
+
194
+
195
+ class MCPArgumentParser(BaseArgumentParser):
196
+ """Argument parser for the qk-mcp MCP stdio server.
197
+
198
+ Supports common arguments like verbosity and log file.
199
+ """
200
+
201
+ @typing.override
202
+ def __init__(self):
203
+ super().__init__(
204
+ prog="qk-mcp",
205
+ description="MCP stdio server that exposes qkrun project tasks.",
206
+ )
207
+ self.add_argument(
208
+ "--project",
209
+ action="append",
210
+ type=str,
211
+ dest="projects",
212
+ metavar="NAME:PATH",
213
+ default=None,
214
+ help=(
215
+ "Register a project as NAME:PATH where PATH points to the _qk "
216
+ "module or directory. Repeatable. Overrides --config on name conflict."
217
+ ),
218
+ )
219
+ self.add_argument(
220
+ "--config",
221
+ type=str,
222
+ dest="config",
223
+ metavar="FILE",
224
+ default=None,
225
+ help=("Path to a TOML or JSON config file declaring projects to register."),
226
+ )
qkrun/_cache.py ADDED
@@ -0,0 +1,212 @@
1
+ """Disk cache for task metadata to speed up autocomplete.
2
+
3
+ The cache lives in a ``.qkrun_cache/`` directory inside the tasks
4
+ directory. An inner ``.gitignore`` is created automatically so that
5
+ users never accidentally commit cached data.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ from pathlib import Path
13
+ from typing import TYPE_CHECKING
14
+
15
+ if TYPE_CHECKING:
16
+ from qkrun.tasks import Task
17
+
18
+ _CACHE_DIR_NAME = ".qkrun_cache"
19
+ _CACHE_FILE_NAME = "task_names.json"
20
+ _GITIGNORE_CONTENT = "*\n"
21
+
22
+ # Completers we can recreate from cache (stateless, no constructor args).
23
+ _REBUILDABLE_COMPLETERS: frozenset[str] = frozenset(
24
+ {"PathCompleter", "PytestCompleter"}
25
+ )
26
+
27
+
28
+ class TaskCache:
29
+ """Disk cache mapping task names to their help text and arg metadata."""
30
+
31
+ # ------------------------------------------------------------------
32
+ # Path helpers
33
+ # ------------------------------------------------------------------
34
+
35
+ @staticmethod
36
+ def _cache_dir(tasks_path: Path) -> Path:
37
+ return tasks_path / _CACHE_DIR_NAME
38
+
39
+ @staticmethod
40
+ def _cache_file(tasks_path: Path) -> Path:
41
+ return TaskCache._cache_dir(tasks_path) / _CACHE_FILE_NAME
42
+
43
+ @staticmethod
44
+ def _gitignore_file(tasks_path: Path) -> Path:
45
+ return TaskCache._cache_dir(tasks_path) / ".gitignore"
46
+
47
+ # ------------------------------------------------------------------
48
+ # Cache dir management
49
+ # ------------------------------------------------------------------
50
+
51
+ @staticmethod
52
+ def _ensure_cache_dir(tasks_path: Path) -> None:
53
+ """Create the cache directory and ``.gitignore`` if missing."""
54
+ cache_dir = TaskCache._cache_dir(tasks_path)
55
+ cache_dir.mkdir(parents=True, exist_ok=True)
56
+
57
+ gitignore = TaskCache._gitignore_file(tasks_path)
58
+ if not gitignore.exists():
59
+ gitignore.write_text(_GITIGNORE_CONTENT)
60
+
61
+ # ------------------------------------------------------------------
62
+ # Save / load
63
+ # ------------------------------------------------------------------
64
+
65
+ @staticmethod
66
+ def save(tasks_path: Path, tasks: dict[str, dict], version: str) -> None:
67
+ """Write task metadata to the disk cache.
68
+
69
+ :param tasks_path: Root path of the tasks module.
70
+ :param tasks: Mapping of ``{task_name: {"help": ..., "args": ...}}``.
71
+ :param version: Current qkrun version string.
72
+ """
73
+ TaskCache._ensure_cache_dir(tasks_path)
74
+ data = {"_version": version, "tasks": tasks}
75
+ TaskCache._cache_file(tasks_path).write_text(
76
+ json.dumps(data, indent=None) + "\n"
77
+ )
78
+
79
+ @staticmethod
80
+ def load(tasks_path: Path, version: str) -> dict | None:
81
+ """Load cached task metadata if the cache is still valid.
82
+
83
+ Returns ``None`` when the cache is missing, corrupt, or stale.
84
+
85
+ :param tasks_path: Root path of the tasks module.
86
+ :param version: Current qkrun version string (for invalidation).
87
+ """
88
+ cache_file = TaskCache._cache_file(tasks_path)
89
+ if not cache_file.exists():
90
+ return None
91
+
92
+ cache_mtime = cache_file.stat().st_mtime
93
+ if TaskCache._is_stale(tasks_path, cache_mtime):
94
+ return None
95
+
96
+ try:
97
+ data = json.loads(cache_file.read_text())
98
+ except (json.JSONDecodeError, OSError):
99
+ return None
100
+
101
+ if data.get("_version") != version:
102
+ return None
103
+
104
+ return data.get("tasks")
105
+
106
+ # ------------------------------------------------------------------
107
+ # Staleness
108
+ # ------------------------------------------------------------------
109
+
110
+ @staticmethod
111
+ def _is_stale(tasks_path: Path, cache_mtime: float) -> bool:
112
+ """Return `True` if any `.py` file is newer than *cache_mtime*."""
113
+ try:
114
+ for file_path in tasks_path.rglob("*.py"):
115
+ # Skip hidden directories like .qkrun_cache
116
+ if any(part.startswith(".") for part in file_path.parts):
117
+ continue
118
+
119
+ if file_path.stat().st_mtime > cache_mtime:
120
+ return True
121
+
122
+ except OSError:
123
+ return True
124
+
125
+ return False
126
+
127
+
128
+ # ------------------------------------------------------------------
129
+ # Cache population helpers
130
+ # ------------------------------------------------------------------
131
+
132
+
133
+ def _detect_completer_type(action: argparse.Action) -> str | None:
134
+ """Return the completer type name for *action*, or ``None``."""
135
+ completer = getattr(action, "completer", None)
136
+ if completer is None:
137
+ return None
138
+ return type(completer).__name__
139
+
140
+
141
+ def build_cache_entry(task: Task) -> dict:
142
+ """Build a cache-entry dict for a single task.
143
+
144
+ Returns ``{"help": ..., "args": ...}`` where *args* is either ``None``
145
+ (no arguments) or a dict with ``schema`` and ``has_unknown_completers``.
146
+ """
147
+ schema = task._get_args_schema()
148
+
149
+ # Build a lookup by dest so we can enrich in a single pass
150
+ schema_by_dest: dict[str, dict] = {e["dest"]: e for e in schema}
151
+
152
+ # Enrich schema with completer_type and detect unknown completers
153
+ has_unknown = False
154
+ for action in task.parser._actions:
155
+ if isinstance(action, argparse._HelpAction):
156
+ continue
157
+ entry = schema_by_dest.get(action.dest)
158
+ if entry is not None:
159
+ completer_type = _detect_completer_type(action)
160
+ entry["completer_type"] = completer_type
161
+ if (
162
+ completer_type is not None
163
+ and completer_type not in _REBUILDABLE_COMPLETERS
164
+ ):
165
+ has_unknown = True
166
+
167
+ if not schema:
168
+ args = None
169
+ else:
170
+ args = {"schema": schema, "has_unknown_completers": has_unknown}
171
+
172
+ return {"help": task.get_short_help(), "args": args}
173
+
174
+
175
+ # ------------------------------------------------------------------
176
+ # Parser rebuild (for arg completion from cache)
177
+ # ------------------------------------------------------------------
178
+
179
+
180
+ def rebuild_parser(task_name: str, cached_args: dict) -> argparse.ArgumentParser:
181
+ """Rebuild a lightweight ``ArgumentParser`` from cached arg metadata.
182
+
183
+ :param task_name: Name of the task (used as ``prog``).
184
+ :param cached_args: The ``args`` dict from the cache (must not be ``None``).
185
+ :returns: A parser with arguments and known completers reattached.
186
+ """
187
+ parser = argparse.ArgumentParser(prog=task_name)
188
+
189
+ for entry in cached_args["schema"]:
190
+ flags = entry["flags"]
191
+ kwargs: dict = {}
192
+
193
+ # Only the fields needed for argcomplete completion.
194
+ if entry.get("choices") is not None:
195
+ kwargs["choices"] = entry["choices"]
196
+ if entry.get("nargs") is not None:
197
+ kwargs["nargs"] = entry["nargs"]
198
+
199
+ action = parser.add_argument(*flags, **kwargs)
200
+
201
+ # Reattach known completers
202
+ completer_type = entry.get("completer_type")
203
+ if completer_type == "PathCompleter":
204
+ from qkrun.completion import PathCompleter
205
+
206
+ setattr(action, "completer", PathCompleter())
207
+ elif completer_type == "PytestCompleter":
208
+ from qkrun.completion.python import PytestCompleter
209
+
210
+ setattr(action, "completer", PytestCompleter())
211
+
212
+ return parser