diff --git a/README.md b/README.md index b56e30e..9fb3e23 100644 --- a/README.md +++ b/README.md @@ -13,13 +13,13 @@ pip install -e . ## Quick Start ```bash -# Set the snapshot database (saves context for future queries) -pt-snap use examples/snapshot_expandable.pkl.db +# Set the snapshot database and device +pt-snap focus examples/snapshot_expandable.pkl.db --device 0 # List available queries pt-snap query --list -# Run a query +# Run a query (automatically uses the focused device) pt-snap query --template-use memory_summary # Detect potential memory leaks @@ -32,7 +32,7 @@ See the [full quick start guide](docs/en/quickstart.md) for a walkthrough. | Command | Description | |---------|-------------| -| `pt-snap use` | Set and manage snapshot database context | +| `pt-snap focus` | Set and manage analysis focus (database + device) | | `pt-snap query` | Run memory analysis queries | | `pt-snap config` | Manage global configuration | @@ -41,7 +41,7 @@ See the [full quick start guide](docs/en/quickstart.md) for a walkthrough. | Topic | Guide | |-------|-------| | Getting started | [Quick Start](docs/en/quickstart.md) | -| Managing contexts | [Context Management](docs/en/context-management.md) | +| Managing focus | [Focus Management](docs/en/focus-management.md) | | Running queries | [Querying](docs/en/querying.md) | | Database format | [SnapshotDB Schema](docs/en/database.md) | | Python API | [ResultMapper API](docs/en/result-mapper-api.md) | @@ -63,7 +63,8 @@ pt-snap-cli/ ├── src/ │ └── pt_snap_cli/ │ ├── cli.py # CLI entry point -│ ├── context.py # Context management +│ ├── context.py # Database context manager +│ ├── config.py # Focus management │ ├── query/ │ │ ├── builder.py # Query builder │ │ ├── executor.py # Query executor diff --git a/README_zh.md b/README_zh.md index ad215f6..4b2a8e5 100644 --- a/README_zh.md +++ b/README_zh.md @@ -13,13 +13,13 @@ pip install -e . ## 快速开始 ```bash -# 设置快照数据库(保存上下文供后续查询使用) -pt-snap use examples/snapshot_expandable.pkl.db +# 设置快照数据库和设备 +pt-snap focus examples/snapshot_expandable.pkl.db --device 0 # 列出可用查询 pt-snap query --list -# 运行查询 +# 运行查询(自动使用 focus 中设置的设备) pt-snap query --template-use memory_summary # 检测潜在内存泄漏 @@ -32,7 +32,7 @@ pt-snap query --template-use leak_detection --params '{"min_size": 1024}' | 命令 | 说明 | |------|------| -| `pt-snap use` | 设置和管理快照数据库上下文 | +| `pt-snap focus` | 设置和管理分析焦点(数据库 + 设备) | | `pt-snap query` | 运行内存分析查询 | | `pt-snap config` | 管理全局配置 | @@ -41,7 +41,7 @@ pt-snap query --template-use leak_detection --params '{"min_size": 1024}' | 主题 | 指南 | |------|------| | 入门指南 | [Quick Start](docs/zh/quickstart.md) | -| Context 管理 | [Context Management](docs/zh/context-management.md) | +| Focus 管理 | [Focus Management](docs/zh/focus-management.md) | | 运行查询 | [Querying](docs/zh/querying.md) | | 数据库格式 | [SnapshotDB Schema](docs/zh/database.md) | | Python API | [ResultMapper API](docs/zh/result-mapper-api.md) | @@ -63,7 +63,8 @@ pt-snap-cli/ ├── src/ │ └── pt_snap_cli/ │ ├── cli.py # CLI 入口 -│ ├── context.py # 上下文管理 +│ ├── context.py # 数据库连接管理器 +│ ├── config.py # 焦点管理 │ ├── query/ │ │ ├── builder.py # 查询构建器 │ │ ├── executor.py # 查询执行器 diff --git a/docs/en/context-management.md b/docs/en/context-management.md deleted file mode 100644 index 9c75fb7..0000000 --- a/docs/en/context-management.md +++ /dev/null @@ -1,104 +0,0 @@ -# Context Management - -[English](context-management.md) | [中文](../zh/context-management.md) - -`pt-snap` supports project-scoped context so different terminals, agents, or working directories can analyze different databases without overwriting each other. - -## Resolution Priority - -Database context is resolved in this order: - -1. **Explicit argument**: `pt-snap query ` -2. **Environment variable**: `PT_SNAP_DB_PATH` -3. **Project context**: Nearest `.pt-snap/context.json`, searching upward from current directory -4. **Legacy global config**: `~/.config/pt-snap-cli/config.json` - -## Set Project Database - -```bash -pt-snap use /path/to/your/snapshot.db -``` - -After successful validation, the database path is saved to `.pt-snap/context.json` in the current directory. - -## Session-Scoped Override - -When a shell or agent needs an isolated database without changing project context: - -```bash -export PT_SNAP_DB_PATH=/path/to/agent-specific/snapshot.db -pt-snap query --template-use memory_summary -``` - -Or validate and print the export command in one step: - -```bash -pt-snap use /path/to/agent-specific/snapshot.db --session -``` - -## View Effective Context - -```bash -pt-snap use -``` - -This shows the resolved database path and where it came from (project context, session env, or global config). - -## Override Context - -Even with context configured, you can specify a different database on the command line: - -```bash -# Uses this database temporarily, does not affect saved context -pt-snap query /path/to/other.db --template-use memory_summary -``` - -## Legacy Global Configuration - -Global configuration is kept for compatibility. For concurrent workflows, prefer project or session context. - -```bash -# Store in ~/.config/pt-snap-cli/config.json -pt-snap use /path/to/your/snapshot.db --global -``` - -### Manage Global Config - -```bash -pt-snap config # View global configuration -pt-snap config --path # Show config file path -pt-snap config --clear # Clear global configuration -``` - -## Context File Locations - -| Scope | File | -|-------|------| -| Project | `.pt-snap/context.json` (git-ignored, per-project) | -| Global | `~/.config/pt-snap-cli/config.json` | - -### Context File Format - -```json -{ - "current_db_path": "/path/to/your/snapshot.db" -} -``` - -## Error Handling - -**No database configured:** - -```bash -pt-snap query --template-use memory_summary -# Error: No database path specified and no database configured. -# Use 'pt-snap use ' to set a project database, or provide db_path argument. -``` - -**Database file not found:** - -```bash -pt-snap query --template-use memory_summary -# Error: Database from project context not found: /path/to/missing.db -# Use 'pt-snap use ' to set a new project database, or provide db_path argument. -``` diff --git a/docs/en/focus-management.md b/docs/en/focus-management.md new file mode 100644 index 0000000..e99a289 --- /dev/null +++ b/docs/en/focus-management.md @@ -0,0 +1,115 @@ +# Focus Management + +[中文](../zh/focus-management.md) | English + +`pt-snap` supports project-scoped focus so different terminals, agents, or working directories can analyze different databases and devices without interfering with each other. + +## Resolution Priority + +Focus is resolved in this order: + +1. **Explicit argument**: `pt-snap query ` +2. **Environment variable**: `PT_SNAP_DB_PATH` +3. **Project focus**: Nearest `.pt-snap/focus.json`, searching upward from current directory +4. **Legacy global config**: `~/.config/pt-snap-cli/config.json` + +## Set Project Database and Device + +```bash +# Set database only +pt-snap focus /path/to/your/snapshot.db + +# Set database and device together +pt-snap focus /path/to/your/snapshot.db --device 0 + +# Change device only (keeps current database) +pt-snap focus --device 1 +``` + +After successful validation, the database path and device ID are saved to `.pt-snap/focus.json` in the current directory. + +## Session-Scoped Override + +When a shell or agent needs an isolated database without changing project focus: + +```bash +export PT_SNAP_DB_PATH=/path/to/agent-specific/snapshot.db +pt-snap query --template-use memory_summary +``` + +Or validate and print the export command in one step: + +```bash +pt-snap focus /path/to/agent-specific/snapshot.db --session +``` + +## View Current Focus + +```bash +pt-snap focus +``` + +This shows the resolved database path, device ID, and where they came from (project focus, session env, or global config). + +## Override Focus + +Even with focus configured, you can temporarily specify a different database or device on the command line: + +```bash +# Uses this database temporarily, does not affect saved focus +pt-snap query /path/to/other.db --template-use memory_summary + +# Override device (ignores focused device_id) +pt-snap query --template-use memory_summary --device 2 +``` + +## Legacy Global Configuration + +Global configuration is kept for compatibility. For concurrent workflows, prefer project focus or session overrides. + +```bash +# Store in ~/.config/pt-snap-cli/config.json +pt-snap focus /path/to/your/snapshot.db --global +``` + +### Manage Global Config + +```bash +pt-snap config # View global configuration +pt-snap config --path # Show config file path +pt-snap config --clear # Clear global configuration +``` + +## Focus File Locations + +| Scope | File | +|-------|------| +| Project | `.pt-snap/focus.json` (git-ignored, per-project) | +| Global | `~/.config/pt-snap-cli/config.json` | + +### Focus File Format + +```json +{ + "db_path": "/path/to/your/snapshot.db", + "device_id": 0 +} +``` + +## Error Handling + +**No focus configured:** + +```bash +pt-snap query --template-use memory_summary +# Error: No database path specified and no database configured. +# Use 'pt-snap focus ' to set a project database, or provide db_path argument. +``` + +**Database file not found:** + +```bash +pt-snap query --template-use memory_summary +# Error: Database from project focus not found: /path/to/missing.db +# Use 'pt-snap focus ' to set a new project database, or provide db_path argument. +``` diff --git a/docs/en/quickstart.md b/docs/en/quickstart.md index 6292627..a367d00 100644 --- a/docs/en/quickstart.md +++ b/docs/en/quickstart.md @@ -1,6 +1,6 @@ # Quick Start -[English](quickstart.md) | [中文](../zh/quickstart.md) +[中文](../zh/quickstart.md) | English Get up and running with `pt-snap-cli` in a few minutes. @@ -12,15 +12,21 @@ pip install -e . ## Your First Analysis -### Step 1: Set the Snapshot Database +### Step 1: Set the Snapshot Database and Device Point `pt-snap` to your SQLite snapshot database file: ```bash -pt-snap use examples/snapshot_expandable.pkl.db +pt-snap focus examples/snapshot_expandable.pkl.db --device 0 ``` -This validates the database and saves the path to `.pt-snap/context.json` in your current directory, so you don't need to repeat it. +This validates the database and saves the path and device ID to `.pt-snap/focus.json` in your current directory, so you don't need to repeat it. + +If you only want to set the database (no device yet): + +```bash +pt-snap focus examples/snapshot_expandable.pkl.db +``` ### Step 2: List Available Queries @@ -40,12 +46,12 @@ pt-snap query --template-use memory_summary # Detect potential memory leaks pt-snap query --template-use leak_detection --params '{"min_size": 1024}' -# View active memory blocks on device 0 -pt-snap query --template-use active_blocks --device 0 +# Query automatically uses the focused device, or you can override it +pt-snap query --template-use active_blocks --device 1 ``` ## What's Next -- [Context Management](context-management.md) — Learn how to manage multiple databases across projects and sessions +- [Focus Management](focus-management.md) — Learn how to manage database and device focus across projects and sessions - [Querying](querying.md) — Full guide to all query templates, parameters, and output - [Database Schema](database.md) — Understand the SnapshotDB format diff --git a/docs/zh/context-management.md b/docs/zh/context-management.md deleted file mode 100644 index 895202d..0000000 --- a/docs/zh/context-management.md +++ /dev/null @@ -1,104 +0,0 @@ -# Context 管理 - -[English](../en/context-management.md) | 中文 - -`pt-snap` 支持项目级上下文,避免不同终端、Agent 或工作目录分析不同数据库时互相覆盖。 - -## 解析优先级 - -数据库上下文按以下顺序解析: - -1. **显式参数**: `pt-snap query ` -2. **环境变量**: `PT_SNAP_DB_PATH` -3. **项目上下文**: 从当前目录向上查找最近的 `.pt-snap/context.json` -4. **Legacy 全局配置**: `~/.config/pt-snap-cli/config.json` - -## 设置项目数据库 - -```bash -pt-snap use /path/to/your/snapshot.db -``` - -验证成功后,数据库路径会保存到当前目录的 `.pt-snap/context.json`。 - -## Session 级覆盖 - -当某个 shell 或 Agent 需要独立数据库且不想修改项目 context 时: - -```bash -export PT_SNAP_DB_PATH=/path/to/agent-specific/snapshot.db -pt-snap query --template-use memory_summary -``` - -或在验证数据库的同时输出 export 命令: - -```bash -pt-snap use /path/to/agent-specific/snapshot.db --session -``` - -## 查看当前生效的 Context - -```bash -pt-snap use -``` - -显示已解析的数据库路径及其来源(项目 context、session 环境变量或全局配置)。 - -## 覆盖 Context - -即使已配置 context,仍可在命令行中临时指定不同的数据库: - -```bash -# 仅本次查询使用该数据库,不影响已保存的 context -pt-snap query /path/to/other.db --template-use memory_summary -``` - -## Legacy 全局配置 - -全局配置用于兼容旧版本。并发工作流中推荐使用项目 context 或 session 覆盖。 - -```bash -# 保存到 ~/.config/pt-snap-cli/config.json -pt-snap use /path/to/your/snapshot.db --global -``` - -### 管理全局配置 - -```bash -pt-snap config # 查看全局配置 -pt-snap config --path # 显示配置文件路径 -pt-snap config --clear # 清除全局配置 -``` - -## Context 文件位置 - -| 范围 | 文件 | -|------|------| -| 项目 | `.pt-snap/context.json`(git-ignored,项目级) | -| 全局 | `~/.config/pt-snap-cli/config.json` | - -### Context 文件格式 - -```json -{ - "current_db_path": "/path/to/your/snapshot.db" -} -``` - -## 错误处理 - -**未配置数据库时查询:** - -```bash -pt-snap query --template-use memory_summary -# Error: No database path specified and no database configured. -# Use 'pt-snap use ' to set a project database, or provide db_path argument. -``` - -**数据库文件不存在:** - -```bash -pt-snap query --template-use memory_summary -# Error: Database from project context not found: /path/to/missing.db -# Use 'pt-snap use ' to set a new project database, or provide db_path argument. -``` diff --git a/docs/zh/focus-management.md b/docs/zh/focus-management.md new file mode 100644 index 0000000..24b5d93 --- /dev/null +++ b/docs/zh/focus-management.md @@ -0,0 +1,115 @@ +# Focus 管理 + +[English](../en/focus-management.md) | 中文 + +`pt-snap` 支持项目级焦点设置,避免不同终端、Agent 或工作目录分析不同数据库/设备时互相干扰。 + +## 解析优先级 + +焦点按以下顺序解析: + +1. **显式参数**: `pt-snap query ` +2. **环境变量**: `PT_SNAP_DB_PATH` +3. **项目焦点**: 从当前目录向上查找最近的 `.pt-snap/focus.json` +4. **Legacy 全局配置**: `~/.config/pt-snap-cli/config.json` + +## 设置项目数据库和设备 + +```bash +# 设置数据库 +pt-snap focus /path/to/your/snapshot.db + +# 同时设置数据库和设备 +pt-snap focus /path/to/your/snapshot.db --device 0 + +# 仅切换设备(保持当前数据库) +pt-snap focus --device 1 +``` + +验证成功后,数据库路径和设备 ID 会保存到当前目录的 `.pt-snap/focus.json`。 + +## Session 级覆盖 + +当某个 shell 或 Agent 需要独立数据库且不想修改项目 focus 时: + +```bash +export PT_SNAP_DB_PATH=/path/to/agent-specific/snapshot.db +pt-snap query --template-use memory_summary +``` + +或在验证数据库的同时输出 export 命令: + +```bash +pt-snap focus /path/to/agent-specific/snapshot.db --session +``` + +## 查看当前焦点 + +```bash +pt-snap focus +``` + +显示已解析的数据库路径、设备 ID 及其来源(项目 focus、session 环境变量或全局配置)。 + +## 覆盖焦点 + +即使已配置 focus,仍可在命令行中临时指定不同的数据库或设备: + +```bash +# 仅本次查询使用该数据库,不影响已保存的 focus +pt-snap query /path/to/other.db --template-use memory_summary + +# 覆盖设备(忽略 focus 中的 device_id) +pt-snap query --template-use memory_summary --device 2 +``` + +## Legacy 全局配置 + +全局配置用于兼容旧版本。并发工作流中推荐使用项目 focus 或 session 覆盖。 + +```bash +# 保存到 ~/.config/pt-snap-cli/config.json +pt-snap focus /path/to/your/snapshot.db --global +``` + +### 管理全局配置 + +```bash +pt-snap config # 查看全局配置 +pt-snap config --path # 显示配置文件路径 +pt-snap config --clear # 清除全局配置 +``` + +## Focus 文件位置 + +| 范围 | 文件 | +|------|------| +| 项目 | `.pt-snap/focus.json`(git-ignored,项目级) | +| 全局 | `~/.config/pt-snap-cli/config.json` | + +### Focus 文件格式 + +```json +{ + "db_path": "/path/to/your/snapshot.db", + "device_id": 0 +} +``` + +## 错误处理 + +**未设置焦点时查询:** + +```bash +pt-snap query --template-use memory_summary +# Error: No database path specified and no database configured. +# Use 'pt-snap focus ' to set a project database, or provide db_path argument. +``` + +**数据库文件不存在:** + +```bash +pt-snap query --template-use memory_summary +# Error: Database from project focus not found: /path/to/missing.db +# Use 'pt-snap focus ' to set a new project database, or provide db_path argument. +``` diff --git a/docs/zh/quickstart.md b/docs/zh/quickstart.md index ccc4f66..59c1903 100644 --- a/docs/zh/quickstart.md +++ b/docs/zh/quickstart.md @@ -12,15 +12,21 @@ pip install -e . ## 第一次分析 -### 第一步:设置快照数据库 +### 第一步:设置快照数据库和设备 将 `pt-snap` 指向你的 SQLite 快照数据库文件: ```bash -pt-snap use examples/snapshot_expandable.pkl.db +pt-snap focus examples/snapshot_expandable.pkl.db --device 0 ``` -该命令会验证数据库,并将路径保存到当前目录的 `.pt-snap/context.json`,之后无需重复指定。 +该命令会验证数据库,并将路径和设备 ID 保存到当前目录的 `.pt-snap/focus.json`,之后无需重复指定。 + +如果只需设置数据库(暂不指定设备): + +```bash +pt-snap focus examples/snapshot_expandable.pkl.db +``` ### 第二步:列出可用查询 @@ -40,12 +46,12 @@ pt-snap query --template-use memory_summary # 检测潜在内存泄漏 pt-snap query --template-use leak_detection --params '{"min_size": 1024}' -# 查看设备 0 上的活跃内存块 -pt-snap query --template-use active_blocks --device 0 +# 查询自动使用 focus 中设置的设备,也可以显式覆盖 +pt-snap query --template-use active_blocks --device 1 ``` ## 下一步 -- [Context 管理](context-management.md) — 学习如何在多个项目和会话之间管理数据库 +- [Focus 管理](focus-management.md) — 学习如何在多个项目和会话之间管理数据库和设备焦点 - [运行查询](querying.md) — 所有查询模板、参数和输出的完整指南 - [数据库格式](database.md) — 了解 SnapshotDB 格式 diff --git a/src/pt_snap_cli/cli.py b/src/pt_snap_cli/cli.py index 230fdcf..7884ec8 100644 --- a/src/pt_snap_cli/cli.py +++ b/src/pt_snap_cli/cli.py @@ -7,7 +7,7 @@ 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.config import ENV_DB_PATH, Config, FocusResolutionError from pt_snap_cli.context import Context, DatabaseNotFoundError, SchemaVersionError app = typer.Typer( @@ -35,49 +35,95 @@ def main( """PyTorch Memory Snapshot Analysis Tool.""" -@app.command("use") -def use_database( +@app.command("focus") +def focus_database( db_path: Annotated[Path | None, typer.Argument(help="Path to SQLite database file")] = None, + device: Annotated[ + int | None, + typer.Option( + "--device", "-d", help="Device ID to focus on", autocompletion=complete_device_ids + ), + ] = None, session: Annotated[ bool, typer.Option("--session", help="Print a shell export for this session only") ] = False, - global_context: Annotated[ - bool, typer.Option("--global", help="Store the database in legacy global config") + global_focus: Annotated[ + bool, typer.Option("--global", help="Store the focus in legacy global config") ] = False, ) -> None: - """Set the current analysis database. + """Set the current analysis focus (database and optional device). - Validates the database and saves the path to project context by default. - After setting, you can use 'pt-snap query' without specifying db_path. + Validates the database and saves the focus to project by default. + After setting, you can use 'pt-snap query' without specifying db_path or device. + Use --device to also persist a device ID for queries. Use --session for an isolated shell/agent override. Use --global for legacy user-wide configuration. - If called without arguments, shows the effective database. + If called without arguments, shows the current focus. """ config = Config() - if db_path is None: + if db_path is None and device is None: try: - resolved = config.resolve_db_context() - except ContextResolutionError as e: + resolved = config.resolve_focus() + except FocusResolutionError as e: typer.secho(f"Error: {e}", fg=typer.colors.RED) raise typer.Exit(1) from None if resolved.db_path: typer.echo(f"Current database ({resolved.source}): {resolved.db_path}") - if resolved.context_file: - typer.echo(f"Context file: {resolved.context_file}") + if resolved.focus_file: + typer.echo(f"Focus file: {resolved.focus_file}") + if resolved.device_id is not None: + typer.echo(f"Focused device: {resolved.device_id}") if not resolved.db_path.exists(): typer.secho("Warning: Database file does not exist!", fg=typer.colors.YELLOW) else: - typer.echo("No current database set.") - typer.echo("Usage: pt-snap use [--session|--global]") + typer.echo("No current focus set.") + typer.echo("Usage: pt-snap focus [--device ] [--session|--global]") raise typer.Exit() - if session and global_context: + if session and global_focus: typer.secho("Error: --session and --global cannot be used together.", fg=typer.colors.RED) raise typer.Exit(1) + # Handle device-only update (keep current db, change device) + if db_path is None and device is not None: + try: + resolved = config.resolve_focus() + except FocusResolutionError as e: + typer.secho(f"Error: {e}", fg=typer.colors.RED) + raise typer.Exit(1) from None + + if resolved.db_path is None: + typer.secho( + "Error: No database set. Use 'pt-snap focus ' first.", + fg=typer.colors.RED, + ) + raise typer.Exit(1) + if not resolved.db_path.exists(): + typer.secho(f"Error: Database not found: {resolved.db_path}", fg=typer.colors.RED) + raise typer.Exit(1) + + ctx = Context(resolved.db_path) + if device not in ctx.device_ids: + typer.secho( + f"Error: Device {device} not found. Available: {ctx.device_ids}", + fg=typer.colors.RED, + ) + raise typer.Exit(1) + + if global_focus or resolved.source == "global": + config.current_device_id = device + typer.secho(f"Focused device (global): {device}", fg=typer.colors.GREEN) + else: + focus_file = config.project_focus_path() + config.write_project_focus(resolved.db_path, device_id=device) + typer.secho(f"Focused device (project): {device}", fg=typer.colors.GREEN) + typer.echo(f"Focus file: {focus_file}") + raise typer.Exit() + + # Handle db_path provided (with optional device) if not db_path.exists(): typer.secho(f"Error: Database file not found: {db_path}", fg=typer.colors.RED) raise typer.Exit(1) @@ -85,18 +131,32 @@ def use_database( try: ctx = Context(db_path) resolved_db_path = db_path.expanduser().resolve() + + if device is not None and device not in ctx.device_ids: + typer.secho( + f"Error: Device {device} not found. Available: {ctx.device_ids}", + fg=typer.colors.RED, + ) + raise typer.Exit(1) + if session: import shlex typer.echo(f"export {ENV_DB_PATH}={shlex.quote(str(resolved_db_path))}") return - if global_context: + if global_focus: config.current_db_path = resolved_db_path + if device is not None: + config.current_device_id = device typer.secho(f"Using global database: {resolved_db_path}", fg=typer.colors.GREEN) + if device is not None: + typer.echo(f"Focused device: {device}") else: - context_file = config.write_project_db_path(resolved_db_path) + focus_file = config.write_project_focus(resolved_db_path, device_id=device) typer.secho(f"Using project database: {resolved_db_path}", fg=typer.colors.GREEN) - typer.echo(f"Project context: {context_file}") + typer.echo(f"Focus file: {focus_file}") + if device is not None: + typer.echo(f"Focused device: {device}") devices = ctx.device_ids if devices: typer.echo(f"Available devices: {', '.join(map(str, devices))}") @@ -153,15 +213,18 @@ def query_database( ) -> None: """Execute queries on the memory snapshot database. - The db_path argument is optional if you have configured a database with 'pt-snap use'. + The db_path argument is optional if you have configured a focus with 'pt-snap focus'. + The device argument is optional if you have set a focused device. Use --list to see all supported query templates. Use --template-info {template_name} to see detailed template information. Examples: - pt-snap use snapshot.pkl.db # Set project database - pt-snap query --list # List templates - pt-snap query --template-use leak_detection # Query with resolved context + pt-snap focus snapshot.pkl.db # Set project database + pt-snap focus snapshot.pkl.db --device 0 # Set database and device + pt-snap focus --device 1 # Change device only + pt-snap query --list # List templates + pt-snap query --template-use leak_detection # Uses focused db and device pt-snap query --template-use active_blocks --device 0 pt-snap query custom.db --template-use leak_detection # Override with custom path pt-snap query --template-info leak_detection @@ -286,8 +349,8 @@ def query_database( config = Config() try: - resolved = config.resolve_db_context(db_path) - except ContextResolutionError as e: + resolved = config.resolve_focus(db_path, explicit_device_id=device) + except FocusResolutionError as e: typer.secho(f"Error: {e}", fg=typer.colors.RED) raise typer.Exit(1) from None @@ -298,18 +361,18 @@ def query_database( fg=typer.colors.RED, ) typer.echo( - "Use 'pt-snap use ' to set a project database, or provide db_path argument." + "Use 'pt-snap focus ' to set a project database, or provide db_path argument." ) raise typer.Exit(1) if not db_path.exists(): typer.secho( - f"Error: Database from {resolved.source} context not found: {db_path}", + f"Error: Database from {resolved.source} focus not found: {db_path}", fg=typer.colors.RED, ) - if resolved.context_file: - typer.echo(f"Context file: {resolved.context_file}") + if resolved.focus_file: + typer.echo(f"Focus file: {resolved.focus_file}") typer.echo( - "Use 'pt-snap use ' to set a new project database, or provide db_path argument." + "Use 'pt-snap focus ' to set a new project database, or provide db_path argument." ) raise typer.Exit(1) @@ -325,17 +388,19 @@ def query_database( query_params = json.loads(params) + # Determine device: explicit > focused > first discovered if device is not None: - results = executor.execute_template(template_use, query_params, device_id=device) + target_device = device + elif resolved.device_id is not None: + target_device = resolved.device_id else: device_ids = context.device_ids if not device_ids: typer.echo("No devices found in database.") raise typer.Exit() - default_device = device_ids[0] - results = executor.execute_template( - template_use, query_params, device_id=default_device - ) + target_device = device_ids[0] + + results = executor.execute_template(template_use, query_params, device_id=target_device) if results: typer.echo(f"Found {len(results)} results:") diff --git a/src/pt_snap_cli/completion.py b/src/pt_snap_cli/completion.py index db1d5c5..89557d1 100644 --- a/src/pt_snap_cli/completion.py +++ b/src/pt_snap_cli/completion.py @@ -6,7 +6,7 @@ import os from pathlib import Path -from pt_snap_cli.config import CURRENT_DB_KEY, Config +from pt_snap_cli.config import DB_PATH_KEY, Config def complete_template_names() -> list[str]: @@ -24,18 +24,18 @@ def complete_categories() -> list[str]: 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. + Priority: env var > project focus > 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: + project_focus = Config.find_project_focus_path() + if project_focus: try: - with open(project_context) as f: + with open(project_focus) as f: data = json.load(f) - db_path = data.get(CURRENT_DB_KEY) + db_path = data.get(DB_PATH_KEY) or data.get("current_db_path") if db_path: return Path(db_path).expanduser() except (json.JSONDecodeError, OSError): diff --git a/src/pt_snap_cli/config.py b/src/pt_snap_cli/config.py index 4c4ad72..fe0d758 100644 --- a/src/pt_snap_cli/config.py +++ b/src/pt_snap_cli/config.py @@ -1,4 +1,4 @@ -"""Configuration management for pt-snap-cli.""" +"""Focus management for pt-snap-cli.""" from __future__ import annotations @@ -9,24 +9,26 @@ from typing import Any ENV_DB_PATH = "PT_SNAP_DB_PATH" -PROJECT_CONTEXT_DIR = ".pt-snap" -PROJECT_CONTEXT_FILE = "context.json" -CURRENT_DB_KEY = "current_db_path" +PROJECT_FOCUS_DIR = ".pt-snap" +PROJECT_FOCUS_FILE = "focus.json" +DB_PATH_KEY = "db_path" +DEVICE_ID_KEY = "device_id" -class ContextResolutionError(ValueError): - """Raised when a configured database context cannot be read.""" +class FocusResolutionError(ValueError): + """Raised when a configured focus cannot be read.""" pass @dataclass(frozen=True) -class ResolvedDbContext: - """Resolved database context with its source.""" +class ResolvedFocus: + """Resolved focus (database + optional device) with its source.""" db_path: Path | None source: str - context_file: Path | None = None + focus_file: Path | None = None + device_id: int | None = None @property def is_configured(self) -> bool: @@ -37,7 +39,7 @@ def is_configured(self) -> bool: class Config: """Configuration manager for pt-snap-cli. - Manages user configuration including current database path. + Manages user configuration including current database path and device ID. Configuration is stored in ~/.config/pt-snap-cli/config.json """ @@ -68,7 +70,7 @@ def _save(self) -> None: @property def current_db_path(self) -> Path | None: """Get current database path from configuration.""" - db_path = self._config.get(CURRENT_DB_KEY) + db_path = self._config.get(DB_PATH_KEY) if db_path: return Path(db_path).expanduser() return None @@ -76,12 +78,26 @@ def current_db_path(self) -> Path | None: @current_db_path.setter def current_db_path(self, db_path: Path | str) -> None: """Set current database path in configuration.""" - self._config[CURRENT_DB_KEY] = str(Path(db_path).expanduser().resolve()) + self._config[DB_PATH_KEY] = str(Path(db_path).expanduser().resolve()) self._save() def clear_current_db_path(self) -> None: """Clear current database path from configuration.""" - self._config.pop(CURRENT_DB_KEY, None) + self._config.pop(DB_PATH_KEY, None) + self._save() + + @property + def current_device_id(self) -> int | None: + """Get current device ID from configuration.""" + return self._config.get(DEVICE_ID_KEY) + + @current_device_id.setter + def current_device_id(self, device_id: int | None) -> None: + """Set current device ID in configuration.""" + if device_id is not None: + self._config[DEVICE_ID_KEY] = device_id + else: + self._config.pop(DEVICE_ID_KEY, None) self._save() def validate_db_path(self) -> bool: @@ -112,72 +128,81 @@ def show(self) -> dict[str, Any]: return self._config.copy() @staticmethod - def project_context_path(base_dir: Path | None = None) -> Path: - """Return the project context file path to write in a directory.""" + def project_focus_path(base_dir: Path | None = None) -> Path: + """Return the project focus file path to write in a directory.""" root = (base_dir or Path.cwd()).resolve() - return root / PROJECT_CONTEXT_DIR / PROJECT_CONTEXT_FILE + return root / PROJECT_FOCUS_DIR / PROJECT_FOCUS_FILE @staticmethod - def find_project_context_path(start_dir: Path | None = None) -> Path | None: - """Find the nearest project context file from a directory upward.""" + def find_project_focus_path(start_dir: Path | None = None) -> Path | None: + """Find the nearest project focus file from a directory upward.""" current = (start_dir or Path.cwd()).resolve() if current.is_file(): current = current.parent for directory in (current, *current.parents): - context_file = directory / PROJECT_CONTEXT_DIR / PROJECT_CONTEXT_FILE - if context_file.exists(): - return context_file + focus_file = directory / PROJECT_FOCUS_DIR / PROJECT_FOCUS_FILE + if focus_file.exists(): + return focus_file return None - def write_project_db_path(self, db_path: Path | str, base_dir: Path | None = None) -> Path: - """Write a project-scoped database path and return the context file.""" - context_file = self.project_context_path(base_dir) - context_file.parent.mkdir(parents=True, exist_ok=True) - data = {CURRENT_DB_KEY: str(Path(db_path).expanduser().resolve())} - with open(context_file, "w") as f: + def write_project_focus( + self, db_path: Path | str, base_dir: Path | None = None, device_id: int | None = None + ) -> Path: + """Write a project-scoped focus file with db_path and optional device_id.""" + focus_file = self.project_focus_path(base_dir) + focus_file.parent.mkdir(parents=True, exist_ok=True) + data: dict[str, Any] = {DB_PATH_KEY: str(Path(db_path).expanduser().resolve())} + if device_id is not None: + data[DEVICE_ID_KEY] = device_id + with open(focus_file, "w") as f: json.dump(data, f, indent=2) - return context_file - - def get_project_db_path(self, start_dir: Path | None = None) -> tuple[Path, Path] | None: - """Return the nearest project database path and its context file.""" - context_file = self.find_project_context_path(start_dir) - if context_file is None: + return focus_file + + def get_project_focus( + self, start_dir: Path | None = None + ) -> tuple[Path, Path, int | None] | None: + """Return the nearest project focus data: (db_path, focus_file, device_id).""" + focus_file = self.find_project_focus_path(start_dir) + if focus_file is None: return None try: - with open(context_file) as f: + with open(focus_file) as f: data = json.load(f) except (json.JSONDecodeError, OSError) as exc: - raise ContextResolutionError(f"Invalid project context file: {context_file}") from exc + raise FocusResolutionError(f"Invalid project focus file: {focus_file}") from exc - db_path = data.get(CURRENT_DB_KEY) + db_path = data.get(DB_PATH_KEY) or data.get("current_db_path") if not db_path: - raise ContextResolutionError( - f"Project context file has no {CURRENT_DB_KEY!r}: {context_file}" - ) - return Path(db_path).expanduser(), context_file + raise FocusResolutionError(f"Project focus file has no {DB_PATH_KEY!r}: {focus_file}") + device_id = data.get(DEVICE_ID_KEY) + return Path(db_path).expanduser(), focus_file, device_id - def resolve_db_context( + def resolve_focus( self, explicit_db_path: Path | str | None = None, + explicit_device_id: int | None = None, start_dir: Path | None = None, - ) -> ResolvedDbContext: - """Resolve database path using explicit, env, project, then global config.""" + ) -> ResolvedFocus: + """Resolve focus (db_path + device_id) using explicit, env, project, then global.""" if explicit_db_path is not None: - return ResolvedDbContext(Path(explicit_db_path).expanduser(), "explicit") + return ResolvedFocus( + Path(explicit_db_path).expanduser(), "explicit", None, explicit_device_id + ) env_db_path = os.environ.get(ENV_DB_PATH) if env_db_path: - return ResolvedDbContext(Path(env_db_path).expanduser(), "env") + return ResolvedFocus(Path(env_db_path).expanduser(), "env", None, None) - project_db = self.get_project_db_path(start_dir) - if project_db is not None: - db_path, context_file = project_db - return ResolvedDbContext(db_path, "project", context_file) + project_focus = self.get_project_focus(start_dir) + if project_focus is not None: + db_path, focus_file, device_id = project_focus + return ResolvedFocus(db_path, "project", focus_file, device_id) global_db_path = self.current_db_path if global_db_path is not None: - return ResolvedDbContext(global_db_path, "global", self.config_file) + global_device_id = self.current_device_id + return ResolvedFocus(global_db_path, "global", self.config_file, global_device_id) - return ResolvedDbContext(None, "none") + return ResolvedFocus(None, "none", None, None) diff --git a/tests/test_cli.py b/tests/test_cli.py index dd8eb4d..7d9b589 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -86,7 +86,7 @@ def config_with_db(tmp_path: Path, sample_db: Path) -> None: config_dir = tmp_path / ".config" / "pt-snap-cli" config_dir.mkdir(parents=True) config_file = config_dir / "config.json" - config_file.write_text(json.dumps({"current_db_path": str(sample_db)})) + config_file.write_text(json.dumps({"db_path": str(sample_db)})) @pytest.fixture(autouse=True) @@ -133,10 +133,10 @@ def test_subcommand_short_help_flag(self) -> None: assert result.exit_code == 0 assert "Execute queries on the memory snapshot database" in result.stdout - def test_use_database_not_found(self, tmp_path: Path) -> None: - """Test 'use' command with non-existent database.""" + def test_focus_database_not_found(self, tmp_path: Path) -> None: + """Test 'focus' command with non-existent database.""" non_existent = tmp_path / "not_found.db" - result = runner.invoke(app, ["use", str(non_existent)]) + result = runner.invoke(app, ["focus", str(non_existent)]) assert result.exit_code == 1 assert "Error" in result.stdout @@ -170,7 +170,7 @@ def test_query_with_config(self, tmp_path: Path, sample_db: Path) -> None: config_dir = tmp_path / ".config" / "pt-snap-cli" config_dir.mkdir(parents=True) config_file = config_dir / "config.json" - config_file.write_text(json.dumps({"current_db_path": str(sample_db)})) + config_file.write_text(json.dumps({"db_path": str(sample_db)})) register_query(QueryTemplate(name="test_query", description="Test", query="SELECT 1")) @@ -183,7 +183,7 @@ def test_query_configured_db_not_found(self, tmp_path: Path) -> None: config_dir = tmp_path / ".config" / "pt-snap-cli" config_dir.mkdir(parents=True) config_file = config_dir / "config.json" - config_file.write_text(json.dumps({"current_db_path": "/nonexistent/path.db"})) + config_file.write_text(json.dumps({"db_path": "/nonexistent/path.db"})) register_query(QueryTemplate(name="test", description="Test", query="SELECT 1")) @@ -193,25 +193,24 @@ def test_query_configured_db_not_found(self, tmp_path: Path) -> None: assert "database" in result.stdout.lower() -class TestUseCommandErrors: - """Test use command error scenarios.""" +class TestFocusCommandErrors: + """Test focus command error scenarios.""" - def test_use_database_invalid(self, tmp_path: Path) -> None: - """Test 'use' command with invalid database.""" + def test_focus_database_invalid(self, tmp_path: Path) -> None: + """Test 'focus' command with invalid database.""" invalid_db = tmp_path / "invalid.db" invalid_db.write_text("not a database") - result = runner.invoke(app, ["use", str(invalid_db)]) + result = runner.invoke(app, ["focus", str(invalid_db)]) assert result.exit_code == 1 assert "error" in result.stdout.lower() - def test_use_database_exception_handling(self, tmp_path: Path) -> None: - """Test 'use' command exception handling.""" - # Create a file that will cause an exception when opening as Context + def test_focus_database_exception_handling(self, tmp_path: Path) -> None: + """Test 'focus' command exception handling.""" bad_file = tmp_path / "bad.db" bad_file.write_text("corrupted content") - result = runner.invoke(app, ["use", str(bad_file)]) + result = runner.invoke(app, ["focus", str(bad_file)]) assert result.exit_code == 1 assert "error" in result.stdout.lower() @@ -313,89 +312,147 @@ def test_template_info_without_output_schema(self, sample_db: Path) -> None: assert "Output Schema:" in result.stdout assert "Dynamic" in result.stdout - def test_use_database_success(self, sample_db: Path) -> None: - """Test 'use' command writes project context by default.""" - result = runner.invoke(app, ["use", str(sample_db)]) + def test_focus_database_success(self, sample_db: Path) -> None: + """Test 'focus' command writes project focus by default.""" + result = runner.invoke(app, ["focus", str(sample_db)]) assert result.exit_code == 0 assert "Using project database" in result.stdout - assert "Project context" in result.stdout + assert "Focus file" in result.stdout assert "Available devices" in result.stdout - context_file = Path.cwd() / ".pt-snap" / "context.json" - assert json.loads(context_file.read_text())["current_db_path"] == str(sample_db.resolve()) + focus_file = Path.cwd() / ".pt-snap" / "focus.json" + assert json.loads(focus_file.read_text())["db_path"] == str(sample_db.resolve()) - def test_use_database_global(self, tmp_path: Path, sample_db: Path) -> None: - """Test 'use --global' preserves legacy global config behavior.""" - result = runner.invoke(app, ["use", str(sample_db), "--global"]) + def test_focus_database_with_device(self, sample_db: Path) -> None: + """Test 'focus --device' sets both database and device.""" + result = runner.invoke(app, ["focus", str(sample_db), "--device", "0"]) + assert result.exit_code == 0 + assert "Focused device: 0" in result.stdout + + focus_file = Path.cwd() / ".pt-snap" / "focus.json" + data = json.loads(focus_file.read_text()) + assert data["db_path"] == str(sample_db.resolve()) + assert data["device_id"] == 0 + + def test_focus_database_global(self, tmp_path: Path, sample_db: Path) -> None: + """Test 'focus --global' preserves legacy global config behavior.""" + result = runner.invoke(app, ["focus", str(sample_db), "--global"]) assert result.exit_code == 0 assert "Using global database" in result.stdout config_file = tmp_path / ".config" / "pt-snap-cli" / "config.json" - assert json.loads(config_file.read_text())["current_db_path"] == str(sample_db.resolve()) - assert not (Path.cwd() / ".pt-snap" / "context.json").exists() + assert json.loads(config_file.read_text())["db_path"] == str(sample_db.resolve()) + assert not (Path.cwd() / ".pt-snap" / "focus.json").exists() - def test_use_database_session(self, sample_db: Path) -> None: - """Test 'use --session' prints export without writing context files.""" - result = runner.invoke(app, ["use", str(sample_db), "--session"]) + def test_focus_database_session(self, sample_db: Path) -> None: + """Test 'focus --session' prints export without writing focus files.""" + result = runner.invoke(app, ["focus", str(sample_db), "--session"]) assert result.exit_code == 0 assert result.stdout.strip() == f"export PT_SNAP_DB_PATH={sample_db.resolve()}" - assert not (Path.cwd() / ".pt-snap" / "context.json").exists() + assert not (Path.cwd() / ".pt-snap" / "focus.json").exists() - def test_use_database_session_and_global_conflict(self, sample_db: Path) -> None: - """Test mutually exclusive use scopes.""" - result = runner.invoke(app, ["use", str(sample_db), "--session", "--global"]) + def test_focus_database_session_and_global_conflict(self, sample_db: Path) -> None: + """Test mutually exclusive focus scopes.""" + result = runner.invoke(app, ["focus", str(sample_db), "--session", "--global"]) assert result.exit_code == 1 assert "cannot be used together" in result.stdout - def test_use_show_current(self, tmp_path: Path, sample_db: Path) -> None: - """Test 'use' command without arguments shows effective database.""" - context_dir = tmp_path / ".pt-snap" - context_dir.mkdir() - context_file = context_dir / "context.json" - context_file.write_text(json.dumps({"current_db_path": str(sample_db)})) + def test_focus_show_current(self, tmp_path: Path, sample_db: Path) -> None: + """Test 'focus' command without arguments shows effective focus.""" + focus_dir = tmp_path / ".pt-snap" + focus_dir.mkdir() + focus_file = focus_dir / "focus.json" + focus_file.write_text(json.dumps({"db_path": str(sample_db)})) - result = runner.invoke(app, ["use"]) + result = runner.invoke(app, ["focus"]) assert result.exit_code == 0 assert "Current database (project)" in result.stdout assert str(sample_db) in result.stdout - def test_use_no_database_set(self, tmp_path: Path) -> None: - """Test 'use' command when no database is configured.""" + def test_focus_show_current_with_device(self, tmp_path: Path, sample_db: Path) -> None: + """Test 'focus' without arguments shows db and device.""" + focus_dir = tmp_path / ".pt-snap" + focus_dir.mkdir() + focus_file = focus_dir / "focus.json" + focus_file.write_text(json.dumps({"db_path": str(sample_db), "device_id": 1})) + + result = runner.invoke(app, ["focus"]) + assert result.exit_code == 0 + assert "Focused device: 1" in result.stdout + + def test_focus_no_database_set(self, tmp_path: Path) -> None: + """Test 'focus' command when no focus is configured.""" config_dir = tmp_path / ".config" / "pt-snap-cli" config_dir.mkdir(parents=True) - result = runner.invoke(app, ["use"]) + result = runner.invoke(app, ["focus"]) assert result.exit_code == 0 - assert "No current database set" in result.stdout + assert "No current focus set" in result.stdout - def test_use_database_not_exist_warning(self, tmp_path: Path) -> None: - """Test 'use' command shows warning when effective database doesn't exist.""" - context_dir = tmp_path / ".pt-snap" - context_dir.mkdir() - context_file = context_dir / "context.json" - context_file.write_text(json.dumps({"current_db_path": "/nonexistent/path.db"})) + def test_focus_database_not_exist_warning(self, tmp_path: Path) -> None: + """Test 'focus' command shows warning when effective focus doesn't exist.""" + focus_dir = tmp_path / ".pt-snap" + focus_dir.mkdir() + focus_file = focus_dir / "focus.json" + focus_file.write_text(json.dumps({"db_path": "/nonexistent/path.db"})) - result = runner.invoke(app, ["use"]) + result = runner.invoke(app, ["focus"]) assert result.exit_code == 0 assert "Current database" in result.stdout assert "Warning" in result.stdout + def test_focus_device_only_update(self, tmp_path: Path, sample_db: Path) -> None: + """Test 'focus --device' without db_path updates device only.""" + focus_dir = tmp_path / ".pt-snap" + focus_dir.mkdir() + (focus_dir / "focus.json").write_text(json.dumps({"db_path": str(sample_db)})) + + result = runner.invoke(app, ["focus", "--device", "0"]) + assert result.exit_code == 0 + assert "Focused device" in result.stdout + + data = json.loads((focus_dir / "focus.json").read_text()) + assert data["device_id"] == 0 + assert data["db_path"] == str(sample_db) + + def test_focus_device_only_no_db_set(self, tmp_path: Path) -> None: + """Test 'focus --device' without a database set fails.""" + result = runner.invoke(app, ["focus", "--device", "0"]) + assert result.exit_code == 1 + assert "No database set" in result.stdout + + def test_focus_device_invalid(self, sample_db: Path) -> None: + """Test 'focus --device' with invalid device ID.""" + result = runner.invoke(app, ["focus", str(sample_db), "--device", "99"]) + assert result.exit_code == 1 + assert "Device 99 not found" in result.stdout + + def test_focus_device_only_invalid(self, tmp_path: Path, sample_db: Path) -> None: + """Test 'focus --device' with invalid device when db already set.""" + focus_dir = tmp_path / ".pt-snap" + focus_dir.mkdir() + (focus_dir / "focus.json").write_text(json.dumps({"db_path": str(sample_db)})) + + result = runner.invoke(app, ["focus", "--device", "99"]) + assert result.exit_code == 1 + assert "Device 99 not found" in result.stdout + def test_config_show(self, tmp_path: Path, sample_db: Path) -> None: """Test 'config' command shows configuration.""" config_dir = tmp_path / ".config" / "pt-snap-cli" config_dir.mkdir(parents=True) config_file = config_dir / "config.json" - config_file.write_text(json.dumps({"current_db_path": str(sample_db)})) + config_file.write_text(json.dumps({"db_path": str(sample_db)})) result = runner.invoke(app, ["config"]) assert result.exit_code == 0 assert "Current configuration" in result.stdout - assert "current_db_path" in result.stdout + assert "db_path" in result.stdout def test_config_clear(self, tmp_path: Path) -> None: """Test 'config --clear' command clears configuration.""" config_dir = tmp_path / ".config" / "pt-snap-cli" config_dir.mkdir(parents=True) config_file = config_dir / "config.json" - config_file.write_text(json.dumps({"current_db_path": "/some/path.db"})) + config_file.write_text(json.dumps({"db_path": "/some/path.db"})) result = runner.invoke(app, ["config", "--clear"]) assert result.exit_code == 0 @@ -475,11 +532,11 @@ def test_query_no_database_configured(self, tmp_path: Path) -> None: # The error should mention either database or template-use assert "error" in result.stdout.lower() - def test_query_uses_project_context(self, sample_db: Path) -> None: - """Test 'query' command uses project context.""" - context_dir = Path.cwd() / ".pt-snap" - context_dir.mkdir() - (context_dir / "context.json").write_text(json.dumps({"current_db_path": str(sample_db)})) + def test_query_uses_project_focus(self, sample_db: Path) -> None: + """Test 'query' command uses project focus.""" + focus_dir = Path.cwd() / ".pt-snap" + focus_dir.mkdir() + (focus_dir / "focus.json").write_text(json.dumps({"db_path": str(sample_db)})) register_query( QueryTemplate( name="size_query", description="Test", query="SELECT size FROM trace_entry_0" @@ -491,17 +548,17 @@ def test_query_uses_project_context(self, sample_db: Path) -> None: assert result.exit_code == 0 assert "'size': 1024" in result.stdout - def test_query_env_overrides_project_context( + def test_query_env_overrides_project_focus( self, tmp_path: Path, sample_db: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Test PT_SNAP_DB_PATH overrides project context.""" + """Test PT_SNAP_DB_PATH overrides project focus.""" env_db = create_sample_db(tmp_path / "env.db", size=2048) - context_dir = Path.cwd() / ".pt-snap" - context_dir.mkdir() - (context_dir / "context.json").write_text(json.dumps({"current_db_path": str(sample_db)})) + focus_dir = Path.cwd() / ".pt-snap" + focus_dir.mkdir() + (focus_dir / "focus.json").write_text(json.dumps({"db_path": str(sample_db)})) monkeypatch.setenv("PT_SNAP_DB_PATH", str(env_db)) register_query( QueryTemplate( @@ -523,9 +580,9 @@ def test_query_explicit_path_overrides_env_and_project( """Test explicit db path has highest priority.""" env_db = create_sample_db(tmp_path / "env.db", size=2048) explicit_db = create_sample_db(tmp_path / "explicit.db", size=4096) - context_dir = Path.cwd() / ".pt-snap" - context_dir.mkdir() - (context_dir / "context.json").write_text(json.dumps({"current_db_path": str(sample_db)})) + focus_dir = Path.cwd() / ".pt-snap" + focus_dir.mkdir() + (focus_dir / "focus.json").write_text(json.dumps({"db_path": str(sample_db)})) monkeypatch.setenv("PT_SNAP_DB_PATH", str(env_db)) register_query( QueryTemplate( @@ -551,7 +608,6 @@ def test_query_with_device(self, sample_db: Path) -> None: result = runner.invoke( app, ["query", str(sample_db), "--template-use", "device_query", "--device", "0"] ) - # The test might fail due to executor issues, but we're testing CLI flow assert result.exit_code in [0, 1] def test_query_with_params(self, sample_db: Path) -> None: @@ -575,7 +631,6 @@ def test_query_with_params(self, sample_db: Path) -> None: '{"device_id": 0}', ], ) - # The test might fail due to executor issues, but we're testing CLI flow assert result.exit_code in [0, 1] def test_query_invalid_json_params(self, sample_db: Path) -> None: @@ -637,7 +692,6 @@ def test_safe_call_catches_comp_keyerror(self) -> None: from pt_snap_cli.cli import _safe_call - # Simulate Click trying completion with missing COMP_WORDS with patch("sys.argv", ["pt-snap"]): with patch("click.core.Command.parse_args", side_effect=KeyError("COMP_WORDS")): exit_code = _safe_call() diff --git a/tests/test_completion.py b/tests/test_completion.py index aa2cfa4..18ac456 100644 --- a/tests/test_completion.py +++ b/tests/test_completion.py @@ -12,9 +12,9 @@ complete_template_names, ) from pt_snap_cli.config import ( - CURRENT_DB_KEY, - PROJECT_CONTEXT_DIR, - PROJECT_CONTEXT_FILE, + DB_PATH_KEY, + PROJECT_FOCUS_DIR, + PROJECT_FOCUS_FILE, ) from pt_snap_cli.query.config import QueryTemplate from pt_snap_cli.query.registry import QueryRegistry, register_query @@ -115,12 +115,12 @@ def test_returns_empty_for_invalid_db(self, tmp_path: Path): else: os.environ["PT_SNAP_DB_PATH"] = old_env - def test_uses_project_context(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + def test_uses_project_focus(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)})) + focus_dir = tmp_path / PROJECT_FOCUS_DIR + focus_dir.mkdir() + focus_file = focus_dir / PROJECT_FOCUS_FILE + focus_file.write_text(json.dumps({DB_PATH_KEY: str(db_path)})) monkeypatch.chdir(tmp_path) result = complete_device_ids() diff --git a/tests/test_config.py b/tests/test_config.py index fbfc44e..cb8277e 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -5,7 +5,13 @@ import pytest -from pt_snap_cli.config import ENV_DB_PATH, Config, ContextResolutionError +from pt_snap_cli.config import ( + DB_PATH_KEY, + DEVICE_ID_KEY, + ENV_DB_PATH, + Config, + FocusResolutionError, +) class TestConfig: @@ -13,20 +19,19 @@ class TestConfig: def test_config_init_empty(self, tmp_path: Path) -> None: """Test config initialization with no config file.""" - # Monkey-patch Path.home to use tmp_path original_home = Path.home Path.home = lambda: tmp_path try: config = Config() assert not config.config_file.exists() assert config.current_db_path is None + assert config.current_device_id is None assert config.show() == {} finally: Path.home = original_home def test_config_set_db_path(self, tmp_path: Path) -> None: """Test setting database path.""" - # Monkey-patch Path.home to use tmp_path original_home = Path.home Path.home = lambda: tmp_path try: @@ -41,13 +46,12 @@ def test_config_set_db_path(self, tmp_path: Path) -> None: # Verify persisted to file config_data = json.loads(config.config_file.read_text()) - assert config_data["current_db_path"] == str(db_path.resolve()) + assert config_data[DB_PATH_KEY] == str(db_path.resolve()) finally: Path.home = original_home def test_config_clear_db_path(self, tmp_path: Path) -> None: """Test clearing database path.""" - # Monkey-patch Path.home to use tmp_path original_home = Path.home Path.home = lambda: tmp_path try: @@ -60,13 +64,46 @@ def test_config_clear_db_path(self, tmp_path: Path) -> None: assert config.current_db_path is None config_data = json.loads(config.config_file.read_text()) - assert "current_db_path" not in config_data + assert DB_PATH_KEY not in config_data + finally: + Path.home = original_home + + def test_config_set_device_id(self, tmp_path: Path) -> None: + """Test setting device ID in global config.""" + original_home = Path.home + Path.home = lambda: tmp_path + try: + config = Config() + config.current_device_id = 2 + + assert config.current_device_id == 2 + + # Verify persisted + config2 = Config() + assert config2.current_device_id == 2 + + config_data = json.loads(config.config_file.read_text()) + assert config_data[DEVICE_ID_KEY] == 2 + finally: + Path.home = original_home + + def test_config_clear_device_id(self, tmp_path: Path) -> None: + """Test clearing device ID from global config.""" + original_home = Path.home + Path.home = lambda: tmp_path + try: + config = Config() + config.current_device_id = 1 + config.current_device_id = None + + assert config.current_device_id is None + config_data = json.loads(config.config_file.read_text()) + assert DEVICE_ID_KEY not in config_data finally: Path.home = original_home def test_config_get_set(self, tmp_path: Path) -> None: """Test generic get/set methods.""" - # Monkey-patch Path.home to use tmp_path original_home = Path.home Path.home = lambda: tmp_path try: @@ -80,7 +117,6 @@ def test_config_get_set(self, tmp_path: Path) -> None: def test_config_clear_all(self, tmp_path: Path) -> None: """Test clearing all configuration.""" - # Monkey-patch Path.home to use tmp_path original_home = Path.home Path.home = lambda: tmp_path try: @@ -92,12 +128,12 @@ def test_config_clear_all(self, tmp_path: Path) -> None: assert config.show() == {} assert config.current_db_path is None + assert config.current_device_id is None finally: Path.home = original_home def test_config_validate_db_path_exists(self, tmp_path: Path) -> None: """Test validate_db_path when file exists.""" - # Monkey-patch Path.home to use tmp_path original_home = Path.home Path.home = lambda: tmp_path try: @@ -113,7 +149,6 @@ def test_config_validate_db_path_exists(self, tmp_path: Path) -> None: def test_config_validate_db_path_not_exists(self, tmp_path: Path) -> None: """Test validate_db_path when file doesn't exist.""" - # Monkey-patch Path.home to use tmp_path original_home = Path.home Path.home = lambda: tmp_path try: @@ -122,13 +157,12 @@ def test_config_validate_db_path_not_exists(self, tmp_path: Path) -> None: config.current_db_path = db_path assert config.validate_db_path() is False - assert config.current_db_path is None # Should be cleared + assert config.current_db_path is None finally: Path.home = original_home def test_config_load_from_file(self, tmp_path: Path) -> None: """Test loading config from existing file.""" - # Monkey-patch Path.home to use tmp_path original_home = Path.home Path.home = lambda: tmp_path try: @@ -139,7 +173,7 @@ def test_config_load_from_file(self, tmp_path: Path) -> None: db_path = tmp_path / "existing.db" db_path.touch() config_file.write_text( - json.dumps({"current_db_path": str(db_path), "other_key": "other_value"}) + json.dumps({DB_PATH_KEY: str(db_path), "other_key": "other_value"}) ) config = Config() @@ -150,7 +184,6 @@ def test_config_load_from_file(self, tmp_path: Path) -> None: def test_config_load_invalid_json(self, tmp_path: Path) -> None: """Test loading config from invalid JSON file.""" - # Monkey-patch Path.home to use tmp_path original_home = Path.home Path.home = lambda: tmp_path try: @@ -165,8 +198,8 @@ def test_config_load_invalid_json(self, tmp_path: Path) -> None: Path.home = original_home -class TestDbContextResolver: - """Test database context resolution.""" +class TestDbFocusResolver: + """Test database focus resolution.""" @pytest.fixture(autouse=True) def mock_home_and_env( @@ -178,41 +211,61 @@ def mock_home_and_env( monkeypatch.setattr(Path, "home", lambda: tmp_path) monkeypatch.delenv(ENV_DB_PATH, raising=False) - def test_write_and_resolve_project_context( + def test_write_and_resolve_project_focus( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Test writing and resolving project context.""" + """Test writing and resolving project focus.""" monkeypatch.chdir(tmp_path) db_path = tmp_path / "test.db" db_path.touch() config = Config() - context_file = config.write_project_db_path(db_path) - resolved = config.resolve_db_context() + focus_file = config.write_project_focus(db_path) + resolved = config.resolve_focus() - assert context_file == tmp_path / ".pt-snap" / "context.json" + assert focus_file == tmp_path / ".pt-snap" / "focus.json" assert resolved.db_path == db_path.resolve() assert resolved.source == "project" - assert resolved.context_file == context_file + assert resolved.focus_file == focus_file + assert resolved.device_id is None - def test_resolve_project_context_from_child_directory( + def test_write_and_resolve_with_device_id( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Test resolving project context by walking up parent directories.""" + """Test writing and resolving focus with device_id.""" + monkeypatch.chdir(tmp_path) + db_path = tmp_path / "test.db" + db_path.touch() + config = Config() + + focus_file = config.write_project_focus(db_path, device_id=1) + resolved = config.resolve_focus() + + assert focus_file == tmp_path / ".pt-snap" / "focus.json" + assert resolved.db_path == db_path.resolve() + assert resolved.device_id == 1 + assert resolved.source == "project" + + def test_resolve_project_focus_from_child_directory( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """Test resolving project focus by walking up parent directories.""" project = tmp_path / "project" child = project / "nested" / "child" child.mkdir(parents=True) db_path = tmp_path / "test.db" db_path.touch() config = Config() - config.write_project_db_path(db_path, base_dir=project) + config.write_project_focus(db_path, base_dir=project) monkeypatch.chdir(child) - resolved = config.resolve_db_context() + resolved = config.resolve_focus() assert resolved.db_path == db_path.resolve() assert resolved.source == "project" @@ -222,7 +275,7 @@ def test_resolve_priority_explicit_env_project_global( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Test database context priority order.""" + """Test database focus priority order.""" monkeypatch.chdir(tmp_path) explicit_db = tmp_path / "explicit.db" env_db = tmp_path / "env.db" @@ -233,15 +286,15 @@ def test_resolve_priority_explicit_env_project_global( config = Config() config.current_db_path = global_db - config.write_project_db_path(project_db) + config.write_project_focus(project_db) monkeypatch.setenv(ENV_DB_PATH, str(env_db)) - explicit = config.resolve_db_context(explicit_db) - env = config.resolve_db_context() + explicit = config.resolve_focus(explicit_db) + env = config.resolve_focus() monkeypatch.delenv(ENV_DB_PATH) - project = config.resolve_db_context() - (tmp_path / ".pt-snap" / "context.json").unlink() - global_context = config.resolve_db_context() + project = config.resolve_focus() + (tmp_path / ".pt-snap" / "focus.json").unlink() + global_focus = config.resolve_focus() assert explicit.db_path == explicit_db assert explicit.source == "explicit" @@ -249,15 +302,15 @@ def test_resolve_priority_explicit_env_project_global( assert env.source == "env" assert project.db_path == project_db.resolve() assert project.source == "project" - assert global_context.db_path == global_db.resolve() - assert global_context.source == "global" + assert global_focus.db_path == global_db.resolve() + assert global_focus.source == "global" - def test_project_context_is_cwd_scoped( + def test_project_focus_is_cwd_scoped( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Test different working directories can use different contexts.""" + """Test different working directories can use different focuses.""" project_a = tmp_path / "project-a" project_b = tmp_path / "project-b" project_a.mkdir() @@ -267,41 +320,91 @@ def test_project_context_is_cwd_scoped( db_a.touch() db_b.touch() config = Config() - config.write_project_db_path(db_a, base_dir=project_a) - config.write_project_db_path(db_b, base_dir=project_b) + config.write_project_focus(db_a, base_dir=project_a) + config.write_project_focus(db_b, base_dir=project_b) monkeypatch.chdir(project_a) - resolved_a = config.resolve_db_context() + resolved_a = config.resolve_focus() monkeypatch.chdir(project_b) - resolved_b = config.resolve_db_context() + resolved_b = config.resolve_focus() assert resolved_a.db_path == db_a.resolve() assert resolved_b.db_path == db_b.resolve() - def test_invalid_project_context_json( + def test_invalid_project_focus_json( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """Test invalid project focus JSON fails clearly.""" + monkeypatch.chdir(tmp_path) + focus_dir = tmp_path / ".pt-snap" + focus_dir.mkdir() + (focus_dir / "focus.json").write_text("not-json") + + with pytest.raises(FocusResolutionError, match="Invalid project focus file"): + Config().resolve_focus() + + def test_project_focus_missing_db_key( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """Test project focus without db_path fails clearly.""" + monkeypatch.chdir(tmp_path) + focus_dir = tmp_path / ".pt-snap" + focus_dir.mkdir() + (focus_dir / "focus.json").write_text(json.dumps({"other": "value"})) + + with pytest.raises(FocusResolutionError, match="db_path"): + Config().resolve_focus() + + def test_backward_compat_old_current_db_path_key( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Test invalid project context JSON fails clearly.""" + """Test that old 'current_db_path' key is still readable.""" monkeypatch.chdir(tmp_path) - context_dir = tmp_path / ".pt-snap" - context_dir.mkdir() - (context_dir / "context.json").write_text("not-json") + focus_dir = tmp_path / ".pt-snap" + focus_dir.mkdir() + old_db = tmp_path / "old.db" + old_db.touch() + (focus_dir / "focus.json").write_text(json.dumps({"current_db_path": str(old_db)})) + + resolved = Config().resolve_focus() + assert resolved.db_path == old_db.resolve() + assert resolved.source == "project" - with pytest.raises(ContextResolutionError, match="Invalid project context file"): - Config().resolve_db_context() + def test_global_device_id_in_resolve( + self, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """Test global device_id is included in resolved focus.""" + monkeypatch.chdir(tmp_path) + db_path = tmp_path / "test.db" + db_path.touch() + config = Config() + config.current_db_path = db_path + config.current_device_id = 3 - def test_project_context_missing_db_key( + resolved = config.resolve_focus() + assert resolved.db_path == db_path.resolve() + assert resolved.device_id == 3 + assert resolved.source == "global" + + def test_explicit_device_id_with_explicit_db( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - """Test project context without current_db_path fails clearly.""" + """Test passing explicit device_id along with explicit db_path.""" monkeypatch.chdir(tmp_path) - context_dir = tmp_path / ".pt-snap" - context_dir.mkdir() - (context_dir / "context.json").write_text(json.dumps({"other": "value"})) + db_path = tmp_path / "test.db" + db_path.touch() - with pytest.raises(ContextResolutionError, match="current_db_path"): - Config().resolve_db_context() + resolved = Config().resolve_focus(db_path, explicit_device_id=2) + assert resolved.db_path == db_path + assert resolved.device_id == 2 + assert resolved.source == "explicit"