Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
name: Release

on:
push:
tags: ["v*"]

jobs:
build:
name: Build distribution
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: actions/setup-python@v5
with:
python-version: "3.13"

- name: Install build tool
run: pip install build

- name: Build sdist and wheel
run: python -m build

- name: Verify tag matches package version
run: |
TAG=${GITHUB_REF#refs/tags/v}
PKG_VERSION=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
if [ "$TAG" != "$PKG_VERSION" ]; then
echo "::error::Tag v$TAG does not match pyproject.toml version $PKG_VERSION"
exit 1
fi

- name: Verify package installs and runs
run: |
pip install dist/*.whl
pt-snap --version

- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
retention-days: 90

publish:
name: Publish to PyPI
needs: build
runs-on: ubuntu-latest
permissions:
id-token: write
environment:
name: pypi
url: https://pypi.org/project/pt-snap-cli/
steps:
- name: Download build artifacts
uses: actions/download-artifact@v4
with:
name: dist
path: dist/

- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
# Uses Trusted Publisher (OIDC) by default - no API token needed.
# To publish to TestPyPI instead, uncomment:
# with:
# repository-url: https://test.pypi.org/legacy/

# Alternative: token-based publishing (if OIDC not configured)
# with:
# password: ${{ secrets.PYPI_API_TOKEN }}
66 changes: 66 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
name: Test

on:
push:
branches: [main]
pull_request:
branches: [main]

concurrency:
group: test-${{ github.ref }}
cancel-in-progress: true

jobs:
lint:
name: Lint & Format
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: actions/setup-python@v5
with:
python-version: "3.13"

- name: Install dependencies
run: pip install -e .[dev]

- name: Ruff lint check
run: ruff check .

- name: Black format check
run: black --check .

test:
name: Test (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
steps:
- uses: actions/checkout@v4

- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}

- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('pyproject.toml') }}
restore-keys: |
pip-${{ runner.os }}-${{ matrix.python-version }}-

- name: Install dependencies
run: pip install -e .[dev]

- name: Run tests with coverage
run: pytest --cov --cov-report=xml --cov-report=term-missing

- name: Upload coverage report
uses: actions/upload-artifact@v4
if: matrix.python-version == '3.13' && always()
with:
name: coverage-report
path: coverage.xml
retention-days: 30
99 changes: 72 additions & 27 deletions pt_snap_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,12 @@ def main(
@app.command("use")
def use_database(
db_path: Annotated[Path | None, typer.Argument(help="Path to SQLite database file")] = 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")] = False,
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")
] = False,
) -> None:
"""Set the current analysis database.

Expand Down Expand Up @@ -104,12 +108,24 @@ def use_database(

@app.command("query")
def query_database(
db_path: Annotated[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")] = None,
db_path: Annotated[
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")
] = 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,
list_templates: Annotated[bool, typer.Option("--list", help="List all available query templates")] = False,
template_info: Annotated[str | None, typer.Option("--template-info", help="Show detailed information about a template (including parameters and output schema)")] = None,
list_templates: Annotated[
bool, typer.Option("--list", help="List all available query templates")
] = False,
template_info: Annotated[
str | None,
typer.Option(
"--template-info",
help="Show detailed information about a template (including parameters and output schema)",
),
] = None,
) -> None:
"""Execute queries on the memory snapshot database.

Expand Down Expand Up @@ -150,48 +166,71 @@ def query_database(
typer.echo()

typer.echo("Parameters:")
if info['parameters']:
for param_name, param_details in info['parameters'].items():
required_str = " (required)" if param_details['required'] else " (optional)"
default_str = f" [default: {param_details['default']}]" if param_details['default'] is not None else ""
typer.secho(f" {param_name}: {param_details['type']}{required_str}{default_str}", fg=typer.colors.YELLOW)
if info["parameters"]:
for param_name, param_details in info["parameters"].items():
required_str = " (required)" if param_details["required"] else " (optional)"
default_str = (
f" [default: {param_details['default']}]"
if param_details["default"] is not None
else ""
)
typer.secho(
f" {param_name}: {param_details['type']}{required_str}{default_str}",
fg=typer.colors.YELLOW,
)
typer.echo(f" {param_details['description']}")
else:
typer.echo(" None")
typer.echo()

typer.echo("Output Schema:")
if info['output_schema']:
for col in info['output_schema']:
if info["output_schema"]:
for col in info["output_schema"]:
typer.echo(f" {col['column']}: {col['type']}")
else:
typer.echo(" Dynamic (depends on query)")
typer.echo()

typer.echo("Example Usage:")
example_params = {}
for param_name, param_details in info['parameters'].items():
if param_details['type'] == 'int':
example_params[param_name] = param_details['default'] if param_details['default'] is not None else 0
elif param_details['type'] == 'float':
example_params[param_name] = param_details['default'] if param_details['default'] is not None else 0.0
elif param_details['type'] == 'str':
example_params[param_name] = param_details['default'] if param_details['default'] is not None else "example"
elif param_details['type'] == 'bool':
for param_name, param_details in info["parameters"].items():
if param_details["type"] == "int":
example_params[param_name] = (
param_details["default"] if param_details["default"] is not None else 0
)
elif param_details["type"] == "float":
example_params[param_name] = (
param_details["default"] if param_details["default"] is not None else 0.0
)
elif param_details["type"] == "str":
example_params[param_name] = (
param_details["default"]
if param_details["default"] is not None
else "example"
)
elif param_details["type"] == "bool":
example_params[param_name] = True

if example_params:
import json

params_str = json.dumps(example_params)
typer.echo(f" pt-snap query {db_path or '<configured_db>'} --template-use {info['name']} --params '{params_str}'")
typer.echo(
f" pt-snap query {db_path or '<configured_db>'} --template-use {info['name']} --params '{params_str}'"
)
else:
typer.echo(f" pt-snap query {db_path or '<configured_db>'} --template-use {info['name']}")
typer.echo(
f" pt-snap query {db_path or '<configured_db>'} --template-use {info['name']}"
)
else:
typer.secho(f"Error: Template '{template_info}' not found", fg=typer.colors.RED)
raise typer.Exit()

if not template_use:
typer.secho("Error: --template-use is required when not using --list or --template-info", fg=typer.colors.RED)
typer.secho(
"Error: --template-use is required when not using --list or --template-info",
fg=typer.colors.RED,
)
raise typer.Exit(1)

config = Config()
Expand All @@ -207,7 +246,9 @@ def query_database(
"Error: No database path specified and no database configured.",
fg=typer.colors.RED,
)
typer.echo("Use 'pt-snap use <database_path>' to set a project database, or provide db_path argument.")
typer.echo(
"Use 'pt-snap use <database_path>' to set a project database, or provide db_path argument."
)
raise typer.Exit(1)
if not db_path.exists():
typer.secho(
Expand All @@ -216,7 +257,9 @@ def query_database(
)
if resolved.context_file:
typer.echo(f"Context file: {resolved.context_file}")
typer.echo("Use 'pt-snap use <new_database_path>' to set a new project database, or provide db_path argument.")
typer.echo(
"Use 'pt-snap use <new_database_path>' to set a new project database, or provide db_path argument."
)
raise typer.Exit(1)

try:
Expand All @@ -239,7 +282,9 @@ def query_database(
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)
results = executor.execute_template(
template_use, query_params, device_id=default_device
)

if results:
typer.echo(f"Found {len(results)} results:")
Expand Down
4 changes: 1 addition & 3 deletions pt_snap_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,7 @@ def get_project_db_path(self, start_dir: Path | None = None) -> tuple[Path, Path
with open(context_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 ContextResolutionError(f"Invalid project context file: {context_file}") from exc

db_path = data.get(CURRENT_DB_KEY)
if not db_path:
Expand Down
16 changes: 4 additions & 12 deletions pt_snap_cli/query/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,9 @@ def render(
jinja_template = self._env.from_string(template.query)
return jinja_template.render(render_context)
except TemplateSyntaxError as e:
raise TemplateRenderError(
f"Template syntax error in '{template.name}': {e}"
) from e
raise TemplateRenderError(f"Template syntax error in '{template.name}': {e}") from e
except Exception as e:
raise TemplateRenderError(
f"Failed to render template '{template.name}': {e}"
) from e
raise TemplateRenderError(f"Failed to render template '{template.name}': {e}") from e

def execute(
self,
Expand All @@ -124,9 +120,7 @@ def execute(
else:
cursor.execute(sql)
columns = [desc[0] for desc in cursor.description]
return [
dict(zip(columns, row, strict=False)) for row in cursor.fetchall()
]
return [dict(zip(columns, row, strict=False)) for row in cursor.fetchall()]
except Exception as e:
raise QueryExecutionError(f"Query execution failed: {e}") from e

Expand Down Expand Up @@ -186,9 +180,7 @@ def execute_on_all_devices(
results = {}
for device_id in self._context.device_ids:
try:
results[device_id] = self.execute_template(
name, params, device_id, config_name
)
results[device_id] = self.execute_template(name, params, device_id, config_name)
except QueryExecutionError:
results[device_id] = []

Expand Down
8 changes: 2 additions & 6 deletions pt_snap_cli/query/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ def __init__(self):
}
self._model_factories: dict[str, Callable[[dict], Any]] = {}

def register_type_converter(
self, type_name: str, converter: Callable[[Any], Any]
) -> None:
def register_type_converter(self, type_name: str, converter: Callable[[Any], Any]) -> None:
"""Register a type converter.

Args:
Expand All @@ -33,9 +31,7 @@ def register_type_converter(
"""
self._type_converters[type_name] = converter

def register_model_factory(
self, model_name: str, factory: Callable[[dict], Any]
) -> None:
def register_model_factory(self, model_name: str, factory: Callable[[dict], Any]) -> None:
"""Register a model factory.

Args:
Expand Down
Loading
Loading