From 82ff8a3ff9869ea22b757980dcc3e1f3d09dd735 Mon Sep 17 00:00:00 2001 From: codeasier Date: Fri, 17 Apr 2026 21:17:28 +0800 Subject: [PATCH 1/2] feat: add shell tab completion for query command options (#1) Add autocompletion for pt-snap query options using Typer's built-in shell completion support: - --template-use and --template-info: complete from registered template names - --category: complete with basic/statistical/business - --device: complete device IDs from the resolved database (env > project > global) A new src/pt_snap_cli/completion.py module provides the completion functions, including lazy DB resolution for device ID discovery. Users can enable completion with: pt-snap --install-completion Closes #1 --- src/pt_snap_cli/cli.py | 18 +++- src/pt_snap_cli/completion.py | 70 ++++++++++++++++ tests/test_completion.py | 150 ++++++++++++++++++++++++++++++++++ 3 files changed, 236 insertions(+), 2 deletions(-) create mode 100644 src/pt_snap_cli/completion.py create mode 100644 tests/test_completion.py diff --git a/src/pt_snap_cli/cli.py b/src/pt_snap_cli/cli.py index 2ad1b3a..3fb9bec 100644 --- a/src/pt_snap_cli/cli.py +++ b/src/pt_snap_cli/cli.py @@ -6,6 +6,7 @@ import typer from pt_snap_cli import __version__ +from pt_snap_cli.completion import complete_categories, complete_device_ids, complete_template_names from pt_snap_cli.config import ENV_DB_PATH, Config, ContextResolutionError from pt_snap_cli.context import Context @@ -112,10 +113,21 @@ def query_database( Path | None, typer.Argument(help="Path to database file (optional if configured)") ] = None, template_use: Annotated[ - str | None, typer.Option("--template-use", help="Query template name to execute") + str | None, + typer.Option( + "--template-use", + help="Query template name to execute", + autocompletion=complete_template_names, + ), ] = None, params: Annotated[str | None, typer.Option(help="Query parameters as JSON string")] = None, - device: Annotated[int | None, typer.Option(help="Device ID to query")] = None, + device: Annotated[ + int | None, + typer.Option( + help="Device ID to query", + autocompletion=complete_device_ids, + ), + ] = None, list_templates: Annotated[ bool, typer.Option("--list", help="List all available query templates") ] = False, @@ -124,6 +136,7 @@ def query_database( typer.Option( "--category", help="Filter templates by category (basic, statistical, business)", + autocompletion=complete_categories, ), ] = None, template_info: Annotated[ @@ -131,6 +144,7 @@ def query_database( typer.Option( "--template-info", help="Show detailed information about a template (including parameters and output schema)", + autocompletion=complete_template_names, ), ] = None, ) -> None: diff --git a/src/pt_snap_cli/completion.py b/src/pt_snap_cli/completion.py new file mode 100644 index 0000000..db1d5c5 --- /dev/null +++ b/src/pt_snap_cli/completion.py @@ -0,0 +1,70 @@ +"""Shell completion functions for CLI options.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path + +from pt_snap_cli.config import CURRENT_DB_KEY, Config + + +def complete_template_names() -> list[str]: + """Return all registered query template names for shell completion.""" + from pt_snap_cli.query.registry import list_queries + + return sorted(list_queries()) + + +def complete_categories() -> list[str]: + """Return valid category names for shell completion.""" + return ["basic", "statistical", "business"] + + +def _resolve_db_for_completion() -> Path | None: + """Resolve the database path using the same priority as the CLI. + + Priority: env var > project context > global config. + """ + env_path = os.environ.get("PT_SNAP_DB_PATH") + if env_path: + return Path(env_path).expanduser() + + project_context = Config.find_project_context_path() + if project_context: + try: + with open(project_context) as f: + data = json.load(f) + db_path = data.get(CURRENT_DB_KEY) + if db_path: + return Path(db_path).expanduser() + except (json.JSONDecodeError, OSError): + pass + + global_path = Config().current_db_path + return global_path + + +def complete_device_ids() -> list[str]: + """Return device IDs from the resolved database for shell completion.""" + import sqlite3 + + db_path = _resolve_db_for_completion() + if db_path is None or not db_path.exists(): + return [] + + try: + uri = f"file:{db_path}?mode=ro" + with sqlite3.connect(uri, uri=True) as conn: + cursor = conn.cursor() + cursor.execute( + "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'trace_entry_%'" + ) + device_ids = [] + for row in cursor.fetchall(): + table_name = row[0] + device_id = table_name.split("_")[-1] + device_ids.append(device_id) + return sorted(device_ids, key=int) + except Exception: + return [] diff --git a/tests/test_completion.py b/tests/test_completion.py new file mode 100644 index 0000000..aa2cfa4 --- /dev/null +++ b/tests/test_completion.py @@ -0,0 +1,150 @@ +"""Tests for shell completion functions.""" + +import json +import sqlite3 +from pathlib import Path + +import pytest + +from pt_snap_cli.completion import ( + complete_categories, + complete_device_ids, + complete_template_names, +) +from pt_snap_cli.config import ( + CURRENT_DB_KEY, + PROJECT_CONTEXT_DIR, + PROJECT_CONTEXT_FILE, +) +from pt_snap_cli.query.config import QueryTemplate +from pt_snap_cli.query.registry import QueryRegistry, register_query + + +@pytest.fixture(autouse=True) +def reset_registry(): + """Reset query registry before each test.""" + QueryRegistry.reset() + yield + QueryRegistry.reset() + + +def _create_sample_db(db_path: Path) -> Path: + """Create a sample SQLite database with device tables.""" + conn = sqlite3.connect(str(db_path)) + conn.execute(""" + CREATE TABLE dictionary ( + `table` TEXT, `column` TEXT, `key` TEXT, `value` TEXT + ) + """) + conn.execute(""" + CREATE TABLE trace_entry_0 ( + id INTEGER PRIMARY KEY, action TEXT + ) + """) + conn.execute(""" + CREATE TABLE trace_entry_1 ( + id INTEGER PRIMARY KEY, action TEXT + ) + """) + conn.commit() + conn.close() + return db_path + + +class TestCompleteTemplateNames: + def test_returns_registered_templates(self): + register_query(QueryTemplate(name="alpha_z_test", query="SELECT 1")) + + result = complete_template_names() + assert "alpha_z_test" in result + + def test_returns_sorted(self): + register_query(QueryTemplate(name="zebra_test", query="SELECT 1")) + register_query(QueryTemplate(name="apple_test", query="SELECT 1")) + after = complete_template_names() + + # Verify the result is sorted and contains our new entries + assert after == sorted(after) + assert "apple_test" in after + assert "zebra_test" in after + + +class TestCompleteCategories: + def test_returns_three_categories(self): + result = complete_categories() + assert result == ["basic", "statistical", "business"] + + def test_order_is_fixed(self): + assert complete_categories() == ["basic", "statistical", "business"] + + +class TestCompleteDeviceIds: + def test_returns_device_ids_from_db(self, tmp_path: Path): + db_path = _create_sample_db(tmp_path / "test.db") + import os + + old_env = os.environ.get("PT_SNAP_DB_PATH") + os.environ["PT_SNAP_DB_PATH"] = str(db_path) + try: + result = complete_device_ids() + assert result == ["0", "1"] + finally: + if old_env is None: + os.environ.pop("PT_SNAP_DB_PATH", None) + else: + os.environ["PT_SNAP_DB_PATH"] = old_env + + def test_returns_empty_for_no_db(self): + result = complete_device_ids() + # Without any DB configured, should return empty list + assert result == [] + + def test_returns_empty_for_invalid_db(self, tmp_path: Path): + import os + + invalid_file = tmp_path / "not_a_db.txt" + invalid_file.write_text("not a database") + old_env = os.environ.get("PT_SNAP_DB_PATH") + os.environ["PT_SNAP_DB_PATH"] = str(invalid_file) + try: + result = complete_device_ids() + assert result == [] + finally: + if old_env is None: + os.environ.pop("PT_SNAP_DB_PATH", None) + else: + os.environ["PT_SNAP_DB_PATH"] = old_env + + def test_uses_project_context(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + db_path = _create_sample_db(tmp_path / "test.db") + context_dir = tmp_path / PROJECT_CONTEXT_DIR + context_dir.mkdir() + context_file = context_dir / PROJECT_CONTEXT_FILE + context_file.write_text(json.dumps({CURRENT_DB_KEY: str(db_path)})) + monkeypatch.chdir(tmp_path) + + result = complete_device_ids() + assert result == ["0", "1"] + + def test_sorted_by_integer_value(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """Device IDs should be sorted numerically, not lexicographically.""" + import os + + db_path = tmp_path / "test.db" + conn = sqlite3.connect(str(db_path)) + conn.execute("CREATE TABLE dictionary (k TEXT, v TEXT)") + for dev in [0, 1, 2, 10]: + conn.execute(f"CREATE TABLE trace_entry_{dev} (id INTEGER PRIMARY KEY)") + conn.commit() + conn.close() + + old_env = os.environ.get("PT_SNAP_DB_PATH") + os.environ["PT_SNAP_DB_PATH"] = str(db_path) + try: + result = complete_device_ids() + assert result == ["0", "1", "2", "10"] + finally: + if old_env is None: + os.environ.pop("PT_SNAP_DB_PATH", None) + else: + os.environ["PT_SNAP_DB_PATH"] = old_env From 22036ed17471c320082350fb2752aeeea2ac2b44 Mon Sep 17 00:00:00 2001 From: codeasier Date: Fri, 17 Apr 2026 21:24:50 +0800 Subject: [PATCH 2/2] fix: enable Typer completion support (add_completion=True) The default was add_completion=False which disables --install-completion and --show-completion flags. Changed to True so users can enable shell tab completion. --- src/pt_snap_cli/cli.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pt_snap_cli/cli.py b/src/pt_snap_cli/cli.py index 3fb9bec..d5dccb3 100644 --- a/src/pt_snap_cli/cli.py +++ b/src/pt_snap_cli/cli.py @@ -13,7 +13,7 @@ app = typer.Typer( name="pt-snap", help="PyTorch Memory Snapshot Analysis Tool", - add_completion=False, + add_completion=True, context_settings={"help_option_names": ["-h", "--help"]}, )