From 01d84a5c271de74e565d90ad42f1086c7d42b69d Mon Sep 17 00:00:00 2001 From: jiatolentinoDM Date: Tue, 27 Oct 2026 07:19:36 +0800 Subject: [PATCH 01/11] build: depend on datamasque-python 1.6.0, the first release with projects --- pyproject.toml | 2 +- uv.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 79ae0d5..fae18c5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,7 +13,7 @@ dependencies = [ "typer>=0.16.0,<1", "rich>=13.8", "tomli-w>=1.0.0,<2", - "datamasque-python>=1.2.5,<2", + "datamasque-python>=1.6.0,<2", "pydantic>=2.5,<3", ] classifiers = [ diff --git a/uv.lock b/uv.lock index 7189372..fd6666d 100644 --- a/uv.lock +++ b/uv.lock @@ -162,7 +162,7 @@ dev = [ [package.metadata] requires-dist = [ - { name = "datamasque-python", specifier = ">=1.2.5,<2" }, + { name = "datamasque-python", specifier = ">=1.6.0,<2" }, { name = "pydantic", specifier = ">=2.5,<3" }, { name = "rich", specifier = ">=13.8" }, { name = "tomli-w", specifier = ">=1.0.0,<2" }, @@ -180,15 +180,15 @@ dev = [ [[package]] name = "datamasque-python" -version = "1.2.5" +version = "1.6.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pydantic" }, { name = "requests" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/dd/e3/2f48d7182c6e38abece16b7bb218fd94f2bce07d5025c1d2e532183c70b4/datamasque_python-1.2.5.tar.gz", hash = "sha256:5969e9a6303970433eddb9a6ca15f255666216f51d9a13ce7f23e26eb37ffb8b", size = 209710, upload-time = "2026-08-21T07:41:48.559Z" } +sdist = { url = "https://files.pythonhosted.org/packages/dd/78/930fbd2cecf2d5896908370d437cd2f1d242e9100b7f064e4d287894574e/datamasque_python-1.6.0.tar.gz", hash = "sha256:d97d2320a4e802b52c3dd0a4b2b6f0d247f50d944b2f35d810f0c88ac0493481", size = 259133, upload-time = "2026-11-20T01:39:31.755Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fe/69/61f3b32309773b3ff716334c3f4f75dbfb8b1e1939f066d2cfebe123e024/datamasque_python-1.2.5-py3-none-any.whl", hash = "sha256:ad3776f7b321308d827203f821e567255def52a7ef899d0aa80cc490a5a096e3", size = 77348, upload-time = "2026-08-21T07:41:47.19Z" }, + { url = "https://files.pythonhosted.org/packages/4e/87/749bb0310b7dfb48857d6e2767ea89ab591ff412d26a80ef5c3c4da11a93/datamasque_python-1.6.0-py3-none-any.whl", hash = "sha256:2f57e6fe6857e80adad0da1d2bc33e9b46be150c0328541f70b61159805ed68a", size = 108255, upload-time = "2026-11-20T01:39:30.272Z" }, ] [[package]] From 576934ffdf191500b46a902ba74886d93df166fe Mon Sep 17 00:00:00 2001 From: jiatolentinoDM Date: Tue, 27 Oct 2026 07:19:36 +0800 Subject: [PATCH 02/11] feat!: add --project to every project-scoped command and drop --namespace List commands show each resource's project and take --project to list one project's resources. Create, upload and validate commands put the resource in the --project project, else the instance's only project. Get, update and delete commands find a name in any project and ask for --project when the name exists in more than one. BREAKING CHANGE: --namespace is removed from `dm libraries` and `dm discover libraries`; use --project. The CLI needs a DataMasque version with projects. --- CONTRIBUTING.md | 2 +- README.md | 36 +- .../skills/datamasque-cli/SKILL.md | 13 +- .../skills/ruleset-builder/SKILL.md | 2 +- .../references/ruleset-libraries-guide.md | 12 +- .../references/ruleset-yaml-reference.md | 4 +- src/datamasque_cli/client.py | 25 +- src/datamasque_cli/commands/connections.py | 63 ++- src/datamasque_cli/commands/discovery.py | 33 +- .../commands/discovery_config_libraries.py | 82 ++-- .../commands/discovery_configs.py | 76 +++- src/datamasque_cli/commands/files.py | 38 +- .../commands/ruleset_libraries.py | 85 ++-- src/datamasque_cli/commands/rulesets.py | 79 +++- src/datamasque_cli/commands/runs.py | 81 ++-- src/datamasque_cli/commands/seeds.py | 37 +- .../commands/table_references.py | 87 ++-- src/datamasque_cli/projects.py | 123 ++++++ tests/commands/test_connections.py | 23 +- tests/commands/test_discovery.py | 117 ++--- .../test_discovery_config_libraries.py | 148 +++++-- tests/commands/test_discovery_configs.py | 53 ++- tests/commands/test_files.py | 13 +- tests/commands/test_project_options.py | 410 ++++++++++++++++++ tests/commands/test_ruleset_libraries.py | 146 ++++++- tests/commands/test_rulesets.py | 75 ++-- tests/commands/test_runs.py | 88 ++-- tests/commands/test_seeds.py | 11 +- tests/commands/test_table_references.py | 114 +++-- tests/conftest.py | 35 +- tests/integration/conftest.py | 54 ++- tests/integration/test_discovery_configs.py | 33 +- tests/integration/test_rulesets.py | 4 +- tests/test_projects.py | 131 ++++++ 34 files changed, 1770 insertions(+), 563 deletions(-) create mode 100644 src/datamasque_cli/projects.py create mode 100644 tests/commands/test_project_options.py create mode 100644 tests/test_projects.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 83b3fa1..5891694 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -97,7 +97,7 @@ so no DataMasque server is required. ### Integration tests `tests/integration/` hits a real DataMasque instance to catch the bugs unit tests can't — -ruleset namespace collisions, +a database and a file ruleset sharing a name, delete targeting, server-state resolution, and the full `run start → retry → logs --follow` lifecycle. diff --git a/README.md b/README.md index 8934bfe..3363b0b 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,28 @@ For instances with self-signed or expired TLS certificates pass `--insecure` to `dm auth login` to persist the toggle on the profile, or set `DATAMASQUE_VERIFY_SSL=false` to skip verification per call. +## Projects + +Every connection, ruleset, library, discovery config, seed, file and table reference belongs to one project. +This CLI needs a DataMasque version with projects (v3.26.21.0 or later); use an earlier CLI release with older versions. + +- `--project` takes a project name (any case) or its numeric ID. +- List commands show each resource's project, and `--project` lists only that project's resources + (plus the built-in seeds, for `dm seeds list`). +- Create, upload and validate commands put the resource in the `--project` project. + Without `--project`, a create updates the resource of that name in the one project that has it + (for rulesets and discovery configs, the one of the same type). + Otherwise they use the instance's only project, and fail asking for one when there are several. +- Get, update and delete commands find a resource by name in any project. + When the name exists in more than one project they fail asking for `--project`. + +```console +dm rulesets list --project Finance +dm rulesets create --name customers --file rules.yaml --type database --project Finance +dm seeds upload names.csv --project Finance +dm run start -c finance_db -r customers --project Finance +``` + ## Commands ### Authentication @@ -160,11 +182,11 @@ dm libraries list # List all libraries dm libraries get # Show library details dm libraries get --yaml # Print raw YAML only dm libraries create --name --file lib.yaml # Create/update from file -dm libraries create --name --file lib.yaml --namespace pii # With namespace +dm libraries create --name --file lib.yaml --project pii # In a given project dm libraries delete # Delete a library dm libraries validate # Re-validate against current server schema dm libraries status # Validation status; poll after creating YAML of 60 KiB+ -dm libraries usage # Show rulesets using it +dm libraries usage # Show rulesets using it, with their projects ``` ### Table references @@ -260,11 +282,11 @@ The same library can be imported by both database and file discovery configs. ```console dm discover libraries list -dm discover libraries get [--namespace org] [--yaml] -dm discover libraries create --name --namespace org -f lib.yaml -dm discover libraries delete [--namespace org] [--force] # --force if imported by configs -dm discover libraries validate -f lib.yaml -dm discover libraries status [--namespace org] +dm discover libraries get [--project org] [--yaml] +dm discover libraries create --name --project org -f lib.yaml +dm discover libraries delete [--project org] [--force] # --force if imported by configs +dm discover libraries validate -f lib.yaml [--project org] +dm discover libraries status [--project org] ``` ### Seeds diff --git a/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md b/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md index 15e00d6..13b4daf 100644 --- a/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md +++ b/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md @@ -54,12 +54,21 @@ Pass repeated `--options key=value` for server-side knobs ## Idioms and gotchas -- **Ruleset namespaces.** `database` and `file` rulesets share a name - namespace, so `customers` can exist in both. `dm run start` reads the +- **Database and file rulesets.** A `database` and a `file` ruleset can + share a name, so `customers` can exist as both. `dm run start` reads the source connection's type and picks the matching ruleset automatically. For `get` / `create` / `delete`, pass `--type database|file` only when two rows share the name and you need to disambiguate. +- **Projects.** Every resource belongs to one project, and names are unique + per project (per project and type for rulesets and discovery configs). Lists show each resource's project, and `--project ` + narrows a list to one project. A create with no `--project` updates the + resource of that name in the one project that has it (same type, for + rulesets and discovery configs). Otherwise a create or upload with no + `--project` goes into the instance's only project, and fails with + `ambiguous` when there are several. A get or delete fails with `ambiguous` when the name + exists in two projects; pass `--project` to pick one. + - **File masking needs a destination.** Database masking is in-place; file masking writes through to a destination connection and fails with `invalid_input` without `--destination`. diff --git a/claude-skills/ruleset-builder/skills/ruleset-builder/SKILL.md b/claude-skills/ruleset-builder/skills/ruleset-builder/SKILL.md index 7f56bce..23ac241 100644 --- a/claude-skills/ruleset-builder/skills/ruleset-builder/SKILL.md +++ b/claude-skills/ruleset-builder/skills/ruleset-builder/SKILL.md @@ -97,7 +97,7 @@ masks: ### Output format -`Global/RuleLib` below is a placeholder for `/` — substitute the operator's real values, and create the library with `dm libraries create` before running the ruleset. +`Global/RuleLib` below is a placeholder for `/` — substitute the operator's real values, and create the library with `dm libraries create` before running the ruleset. ```yaml version: '1.0' diff --git a/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-libraries-guide.md b/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-libraries-guide.md index b845b5e..99342ea 100644 --- a/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-libraries-guide.md +++ b/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-libraries-guide.md @@ -8,10 +8,10 @@ Define masking logic once, reuse it everywhere. ```bash dm libraries list # List all libraries -dm libraries get [--namespace ] [--yaml] # Show details or YAML -dm libraries create --name --file lib.yml [--namespace ] -dm libraries delete [--namespace ] [--force] -dm libraries usage [--namespace ] # Which rulesets use it +dm libraries get [--project

] [--yaml] # Show details or YAML +dm libraries create --name --file lib.yml [--project

] +dm libraries delete [--project

] [--force] +dm libraries usage [--project

] # Which rulesets use it ``` ## Library Structure @@ -78,8 +78,8 @@ other: Rulesets reference library content using `$ref`: ``` -$ref: "/#

/" -$ref: "#
/" # No namespace +$ref: "/#
/" +$ref: "#
/" # The ruleset's own project $ref: "#
//" # Nested access $ref: "#
/0" # Array index ``` diff --git a/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-yaml-reference.md b/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-yaml-reference.md index c7f20af..0f29528 100644 --- a/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-yaml-reference.md +++ b/claude-skills/ruleset-builder/skills/ruleset-builder/references/ruleset-yaml-reference.md @@ -187,12 +187,12 @@ See `ruleset-libraries-guide.md` for full details. ```yaml imports: - - namespace/library_name + - project/library_name tasks: - type: mask_table table: users key: id rules: - - $ref: "namespace/library_name#database_rules/email_rule" + - $ref: "project/library_name#database_rules/email_rule" ``` diff --git a/src/datamasque_cli/client.py b/src/datamasque_cli/client.py index adab959..ea60339 100644 --- a/src/datamasque_cli/client.py +++ b/src/datamasque_cli/client.py @@ -16,6 +16,7 @@ from datamasque_cli.config import Config, Profile, load_config from datamasque_cli.errors import ErrorCode, abort +from datamasque_cli.projects import in_project, require_single_or_abort, resolve_optional_project ENV_URL = "DATAMASQUE_URL" ENV_USERNAME = "DATAMASQUE_USERNAME" @@ -215,10 +216,22 @@ def get_ifm_client(profile_name: str | None = None) -> DataMasqueIfmClient: return client -def resolve_connection(client: DataMasqueClient, name_or_id: str) -> ConnectionConfig: - """Resolve a connection by name or ID via the connection listing, aborting when not found.""" +def resolve_connection(client: DataMasqueClient, name_or_id: str, project: str | None = None) -> ConnectionConfig: + """ + Resolve a connection by name, in the project `--project` names if given, else by ID. + + Aborts when nothing matches, or when the name matches connections in more than one project. + """ connections = client.list_connections() - match = next((c for c in connections if c.name == name_or_id or str(c.id) == name_or_id), None) - if match is None: - abort(f"Connection '{name_or_id}' not found.", code=ErrorCode.NOT_FOUND) - return match + by_name = in_project([c for c in connections if c.name == name_or_id], resolve_optional_project(client, project)) + if not by_name: + by_id = next((c for c in connections if str(c.id) == name_or_id), None) + if by_id is not None: + return by_id + return require_single_or_abort( + client, + by_name, + f"Connection '{name_or_id}'", + describe=lambda c: f"id={c.id}", + hint="Pass --project, or the connection's id, to disambiguate.", + ) diff --git a/src/datamasque_cli/commands/connections.py b/src/datamasque_cli/commands/connections.py index a9b5506..0046f0b 100644 --- a/src/datamasque_cli/commands/connections.py +++ b/src/datamasque_cli/commands/connections.py @@ -23,9 +23,17 @@ from pydantic import ValidationError from datamasque_cli.client import get_client, resolve_connection -from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort +from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort, require_id_or_abort from datamasque_cli.fileio import read_json_object_or_abort from datamasque_cli.output import print_success, redact_sensitive_fields, render_output +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + in_project, + project_label, + project_names, + resolve_create_project, + resolve_optional_project, +) class ConnectionType(StrEnum): @@ -92,18 +100,21 @@ def _parse_connection_type(raw: str) -> ConnectionType: @app.command("list") def list_connections( + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all configured connections.""" + """List all configured connections, or those in one project.""" client = get_client(profile) - connections = client.list_connections() + connections = in_project(client.list_connections(), resolve_optional_project(client, project)) + names = project_names(client) data = [] for conn in connections: class_name = type(conn).__name__ entry: dict[str, object] = { "id": conn.id, + "project": project_label(names, conn.project), "name": conn.name, "type": class_name.replace("ConnectionConfig", "").replace("Config", ""), "role": _format_role(conn), @@ -113,26 +124,26 @@ def list_connections( render_output( data, is_json=is_json, - columns=["id", "name", "type", "role"], + columns=["id", "project", "name", "type", "role"], title="Connections", ) @app.command("get") def get_connection( - name: str = typer.Argument(help="Connection name"), + name: str = typer.Argument(help="Connection name or ID"), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when connections in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show details for a specific connection.""" client = get_client(profile) - connections = client.list_connections() - - match = next((c for c in connections if c.name == name), None) - if match is None: - abort(f"Connection '{name}' not found.", code=ErrorCode.NOT_FOUND) + match = resolve_connection(client, name, project) data = redact_sensitive_fields(match.model_dump()) + data["project"] = project_label(project_names(client), match.project) render_output(data, is_json=is_json, title=f"Connection: {name}") @@ -154,6 +165,7 @@ def create_connection( is_source: bool = typer.Option(False, "--source", help="Is a file mask source"), is_destination: bool = typer.Option(False, "--destination", help="Is a file mask destination"), bucket: str | None = typer.Option(None, help="S3 bucket name"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a connection. @@ -178,9 +190,8 @@ def create_connection( dm connections create --file databricks.json """ client = get_client(profile) - if file is not None: - _create_from_file(client, file) + _create_from_file(client, file, project) return if name is None or conn_type is None: @@ -201,13 +212,14 @@ def create_connection( is_destination=is_destination, bucket=bucket, ) + config.project = resolve_create_project(client, project, [c for c in client.list_connections() if c.name == name]) client.create_or_update_connection(config) print_success(f"Connection '{name}' created/updated.") -def _create_from_file(client: DataMasqueClient, file: Path) -> None: - """Create a connection from a JSON file.""" +def _create_from_file(client: DataMasqueClient, file: Path, project: str | None) -> None: + """Create a connection from a JSON file, in the project `--project` names when given.""" data = read_json_object_or_abort(file) raw_type = data.pop("type", "database") if not isinstance(raw_type, str): @@ -223,6 +235,9 @@ def _create_from_file(client: DataMasqueClient, file: Path) -> None: config = klass(**data) except ValidationError as exc: abort(f"{file} does not match the expected format: {exc}", code=ErrorCode.INVALID_INPUT) + config.project = resolve_create_project( + client, project, [c for c in client.list_connections() if c.name == config.name] + ) client.create_or_update_connection(config) print_success(f"Connection '{config.name}' created/updated.") @@ -293,6 +308,9 @@ def _build_connection_config( @app.command("test") def test_connection( name: str = typer.Argument(help="Connection name or ID to test"), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when connections in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Verify a connection can reach its target. @@ -302,7 +320,7 @@ def test_connection( success, a warning, or a hard failure. """ client = get_client(profile) - match = resolve_connection(client, name) + match = resolve_connection(client, name, project) try: response = client.make_request("POST", f"/api/connections/{match.id}/test/", data={}) @@ -320,6 +338,9 @@ def test_connection( @app.command("update") def update_connection( name: str = typer.Argument(help="Connection name or ID to update"), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when connections in two projects share a name" + ), host: str | None = typer.Option(None, help="New database host"), port: str | None = typer.Option(None, help="New database port"), database: str | None = typer.Option(None, help="New database name"), @@ -335,7 +356,7 @@ def update_connection( references it stays intact. Pass only the fields that should change. """ client = get_client(profile) - match = resolve_connection(client, name) + match = resolve_connection(client, name, project) updates: dict[str, object] = { key: value @@ -364,17 +385,19 @@ def update_connection( @app.command("delete") def delete_connection( - name: str = typer.Argument(help="Connection name to delete"), + name: str = typer.Argument(help="Connection name or ID to delete"), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when connections in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a connection by name.""" client = get_client(profile) - if not any(c.name == name for c in client.list_connections()): - abort(f"Connection '{name}' not found.", code=ErrorCode.NOT_FOUND) + match = resolve_connection(client, name, project) if not is_confirmed: confirm_or_abort(f"Delete connection '{name}'?") - client.delete_connection_by_name_if_exists(name) + client.delete_connection_by_id_if_exists(require_id_or_abort(match.id, f"connection '{name}'")) print_success(f"Connection '{name}' deleted.") diff --git a/src/datamasque_cli/commands/discovery.py b/src/datamasque_cli/commands/discovery.py index 4094d03..d3d9abb 100644 --- a/src/datamasque_cli/commands/discovery.py +++ b/src/datamasque_cli/commands/discovery.py @@ -34,6 +34,7 @@ ) from datamasque_cli.fileio import write_bytes_or_abort, write_text_or_abort from datamasque_cli.output import print_info, print_json, print_success, render_output, should_emit_json +from datamasque_cli.projects import in_project, require_single_or_abort, resolve_optional_project app = typer.Typer(help="Data discovery operations.", no_args_is_help=True) app.add_typer(discovery_configs.app, name="configs") @@ -80,20 +81,22 @@ def _write_or_echo(content: str, output: Path | None, success_label: str) -> Non def _resolve_discovery_config_id( - client: DataMasqueClient, name: str, expected_type: DiscoveryConfigType + client: DataMasqueClient, name: str, expected_type: DiscoveryConfigType, project: str | None ) -> DiscoveryConfigId: """Resolve a discovery config name to its UUID, requiring it to be of `expected_type`. - Config names are unique per type, so name plus type identifies at most one config. + Config names are unique per type within a project, so name, type and project identify at most one config. """ - match = client.get_discovery_config_by_name(name, expected_type) - if match is not None: + named = in_project( + [c for c in client.list_discovery_configs() if c.name == name], resolve_optional_project(client, project) + ) + of_type = [c for c in named if c.config_type is expected_type] + if of_type: + match = require_single_or_abort(client, of_type, f"Discovery config '{name}'") return require_id_or_abort(match.id, f"discovery config '{name}'") - other_type = ( - DiscoveryConfigType.file if expected_type is DiscoveryConfigType.database else DiscoveryConfigType.database - ) - if client.get_discovery_config_by_name(name, other_type) is not None: + if named: + other_type = named[0].config_type abort( f"Discovery config '{name}' exists as {other_type.value}, " f"but {expected_type.value} discovery needs a {expected_type.value} config.", @@ -108,6 +111,9 @@ def schema_discovery( config: str | None = typer.Option( None, "--config", "-c", help="Run with a saved database discovery config (configurable discovery)" ), + project: str | None = typer.Option( + None, "--project", help="Project of the connection and config, when their names exist in more than one" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: @@ -118,11 +124,11 @@ def schema_discovery( (poll with `dm run status `). """ client = get_client(profile) - conn_id = str(resolve_connection(client, connection).id) + conn_id = str(resolve_connection(client, connection, project).id) try: if config is not None: - config_id = _resolve_discovery_config_id(client, config, DiscoveryConfigType.database) + config_id = _resolve_discovery_config_id(client, config, DiscoveryConfigType.database, project) from_config = SchemaDiscoveryFromConfigRequest(connection=ConnectionId(conn_id), discovery_config=config_id) run_id = client.start_schema_discovery_run_from_config(from_config) config_source = f"config '{config}'" @@ -151,6 +157,9 @@ def start_file_discovery( config: str | None = typer.Option( None, "--config", "-c", help="Run with a saved file discovery config (configurable discovery)" ), + project: str | None = typer.Option( + None, "--project", help="Project of the connection and config, when their names exist in more than one" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: @@ -160,11 +169,11 @@ def start_file_discovery( (poll with `dm run status `). """ client = get_client(profile) - conn_id = str(resolve_connection(client, connection).id) + conn_id = str(resolve_connection(client, connection, project).id) try: if config is not None: - config_id = _resolve_discovery_config_id(client, config, DiscoveryConfigType.file) + config_id = _resolve_discovery_config_id(client, config, DiscoveryConfigType.file, project) from_config = FileDataDiscoveryFromConfigRequest( connection=ConnectionId(conn_id), discovery_config=config_id ) diff --git a/src/datamasque_cli/commands/discovery_config_libraries.py b/src/datamasque_cli/commands/discovery_config_libraries.py index b486622..dad3129 100644 --- a/src/datamasque_cli/commands/discovery_config_libraries.py +++ b/src/datamasque_cli/commands/discovery_config_libraries.py @@ -6,36 +6,52 @@ from pathlib import Path import typer +from datamasque.client import DataMasqueClient from datamasque.client.exceptions import DataMasqueApiError from datamasque.client.models.discovery_config_library import DiscoveryConfigLibrary from datamasque.client.models.status import ValidationErrorDetails from datamasque_cli.client import get_client -from datamasque_cli.errors import ErrorCode, abort, abort_api_error, abort_if_invalid, confirm_or_abort +from datamasque_cli.errors import abort_api_error, abort_if_invalid, confirm_or_abort from datamasque_cli.fileio import read_text_or_abort from datamasque_cli.output import print_success, print_warning, render_output +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + in_project, + project_label, + project_names, + require_single_or_abort, + resolve_create_project, + resolve_optional_project, + resolve_target_project, +) app = typer.Typer(help="Manage discovery config libraries (configurable discovery).", no_args_is_help=True) -def _format_library_label(name: str, namespace: str) -> str: - """Render a library's display label as `namespace/name`, or bare `name` in the default namespace.""" - return f"{namespace}/{name}" if namespace else name +def _find_library(client: DataMasqueClient, name: str, project: str | None) -> DiscoveryConfigLibrary: + """Return the library named `name`, with its YAML, in `project` or in the one project that has it.""" + matches = [lib for lib in client.list_discovery_config_libraries() if lib.name == name] + matches = in_project(matches, resolve_optional_project(client, project)) + found = require_single_or_abort(client, matches, f"Discovery config library '{name}'") + return client.get_discovery_config_library(found.id) @app.command("list") def list_libraries( + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all discovery config libraries.""" + """List all discovery config libraries, or those in one project.""" client = get_client(profile) - libraries = client.list_discovery_config_libraries() + libraries = in_project(client.list_discovery_config_libraries(), resolve_optional_project(client, project)) + names = project_names(client) data = [ { "id": lib.id, - "namespace": lib.namespace or "", + "project": project_label(names, lib.project), "name": lib.name, "valid": lib.is_valid.value if lib.is_valid else "unknown", "used_by": lib.usage_count, @@ -46,7 +62,7 @@ def list_libraries( render_output( data, is_json=is_json, - columns=["id", "namespace", "name", "valid", "used_by"], + columns=["id", "project", "name", "valid", "used_by"], title="Discovery Config Libraries", ) @@ -54,20 +70,14 @@ def list_libraries( @app.command("get") def get_library( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_yaml: bool = typer.Option(False, "--yaml", help="Output raw YAML content only"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a discovery config library's details or YAML content.""" client = get_client(profile) - lib = client.get_discovery_config_library_by_name(name, namespace) - - if lib is None: - abort( - f"Discovery config library '{_format_library_label(name, namespace)}' not found.", - code=ErrorCode.NOT_FOUND, - ) + lib = _find_library(client, name, project) if is_yaml: typer.echo(lib.yaml) @@ -75,7 +85,7 @@ def get_library( data: dict[str, object] = { "id": lib.id, - "namespace": lib.namespace, + "project": project_label(project_names(client), lib.project), "name": lib.name, "valid": lib.is_valid.value if lib.is_valid else "unknown", "used_by": lib.usage_count, @@ -89,22 +99,25 @@ def get_library( def create_library( name: str = typer.Option(..., help="Library name"), file: Path = typer.Option(..., "--file", "-f", help="Path to YAML library file", exists=True, readable=True), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a discovery config library from a YAML file.""" yaml_content = read_text_or_abort(file) client = get_client(profile) - library = DiscoveryConfigLibrary(name=name, namespace=namespace, yaml=yaml_content) + existing = [lib for lib in client.list_discovery_config_libraries() if lib.name == name] + library = DiscoveryConfigLibrary( + name=name, project=resolve_create_project(client, project, existing), yaml=yaml_content + ) client.create_or_update_discovery_config_library(library) - print_success(f"Discovery config library '{_format_library_label(name, namespace)}' created/updated.") + print_success(f"Discovery config library '{name}' created/updated.") @app.command("delete") def delete_library( name: str = typer.Argument(help="Library name to delete"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), force: bool = typer.Option(False, "--force", help="Force delete even if imported by discovery configs"), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), @@ -114,17 +127,16 @@ def delete_library( If the library is imported by any discovery configs, the server rejects the delete unless --force is passed. """ - label = _format_library_label(name, namespace) + label = name client = get_client(profile) - if client.get_discovery_config_library_by_name(name, namespace) is None: - abort(f"Discovery config library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) if not is_confirmed: confirm_or_abort(f"Delete discovery config library '{label}'?") try: - client.delete_discovery_config_library_by_name_if_exists(name, namespace, force=force) + client.delete_discovery_config_library_by_id_if_exists(lib.id, force=force) except DataMasqueApiError as exc: abort_api_error( f"Failed to delete discovery config library '{label}'", @@ -138,18 +150,22 @@ def delete_library( @app.command("validate") def validate_library( file: Path = typer.Option(..., "--file", "-f", help="Path to YAML library file", exists=True, readable=True), + project: str | None = typer.Option( + None, "--project", help="Project to validate in; required when the instance has more than one" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Validate a discovery config library YAML file against the DataMasque server. - Creates a temporary library to trigger server-side validation, + Creates a temporary library in the project to trigger server-side validation, then deletes it. Reports any validation errors. """ yaml_content = read_text_or_abort(file) temp_name = f"__dm_cli_validate_{uuid.uuid4().hex}" client = get_client(profile) - library = DiscoveryConfigLibrary(name=temp_name, yaml=yaml_content) + target = resolve_target_project(client, project) + library = DiscoveryConfigLibrary(name=temp_name, project=target.reference, yaml=yaml_content) try: created = client.create_discovery_config_library(library) @@ -173,23 +189,17 @@ def validate_library( @app.command("status") def show_library_status( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a discovery config library's validation status.""" client = get_client(profile) - lib = client.get_discovery_config_library_by_name(name, namespace) - - if lib is None: - abort( - f"Discovery config library '{_format_library_label(name, namespace)}' not found.", - code=ErrorCode.NOT_FOUND, - ) + lib = _find_library(client, name, project) status = lib.is_valid.value if lib.is_valid else "unknown" data: dict[str, object] = { - "namespace": lib.namespace, + "project": project_label(project_names(client), lib.project), "name": lib.name, "status": status, "validation_error": lib.validation_error, diff --git a/src/datamasque_cli/commands/discovery_configs.py b/src/datamasque_cli/commands/discovery_configs.py index 98256bd..da66775 100644 --- a/src/datamasque_cli/commands/discovery_configs.py +++ b/src/datamasque_cli/commands/discovery_configs.py @@ -26,6 +26,15 @@ write_text_or_abort, ) from datamasque_cli.output import print_info, print_success, print_warning, render_output +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + in_project, + project_label, + project_names, + resolve_create_project, + resolve_optional_project, + resolve_target_project, +) app = typer.Typer(help="Manage discovery configs (configurable discovery).", no_args_is_help=True) @@ -34,24 +43,30 @@ def _find_by_name( client: DataMasqueClient, name: str, config_type: DiscoveryConfigType | None = None, + project: str | None = None, ) -> list[DiscoveryConfig]: - """Return all discovery configs matching `name`, optionally narrowed by `config_type`.""" + """Return all discovery configs matching `name`, optionally narrowed by `config_type` and `--project`.""" matches = [c for c in client.list_discovery_configs() if c.name == name] if config_type is not None: matches = [c for c in matches if c.config_type is config_type] - return matches + return in_project(matches, resolve_optional_project(client, project)) -def _require_single_matched_config_or_abort(matched_configs: list[DiscoveryConfig], name: str) -> DiscoveryConfig: - """Return the single discovery config matching `name`, or abort asking for `--type`.""" +def _require_single_matched_config_or_abort( + client: DataMasqueClient, matched_configs: list[DiscoveryConfig], name: str +) -> DiscoveryConfig: + """Return the single discovery config matching `name`, or abort asking for `--type` or `--project`.""" if not matched_configs: abort(f"Discovery config '{name}' not found.", code=ErrorCode.NOT_FOUND) if len(matched_configs) > 1: - options = "\n ".join(f"id={c.id} type={c.config_type.value}" for c in matched_configs) + names = project_names(client) + options = "\n ".join( + f"id={c.id} type={c.config_type.value} project={project_label(names, c.project)}" for c in matched_configs + ) abort( f"Multiple discovery configs named '{name}':\n {options}", code=ErrorCode.AMBIGUOUS, - hint="Pass --type database|file to disambiguate.", + hint="Pass --type database|file or --project to disambiguate.", ) return matched_configs[0] @@ -61,12 +76,14 @@ def list_configs( config_type: DiscoveryConfigType | None = typer.Option( None, "--type", "-t", help="Filter by type: database or file" ), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all discovery configs.""" + """List all discovery configs, or those in one project.""" client = get_client(profile) - configs = client.list_discovery_configs() + configs = in_project(client.list_discovery_configs(), resolve_optional_project(client, project)) + names = project_names(client) if config_type is not None: configs = [c for c in configs if c.config_type is config_type] @@ -74,6 +91,7 @@ def list_configs( data = [ { "id": c.id, + "project": project_label(names, c.project), "name": c.name, "type": c.config_type.value, "valid": c.is_valid.value if c.is_valid else "unknown", @@ -81,7 +99,7 @@ def list_configs( for c in configs ] - render_output(data, is_json=is_json, columns=["id", "name", "type", "valid"], title="Discovery Configs") + render_output(data, is_json=is_json, columns=["id", "project", "name", "type", "valid"], title="Discovery Configs") @app.command("get") @@ -90,13 +108,16 @@ def get_config( config_type: DiscoveryConfigType | None = typer.Option( None, "--type", "-t", help="Required when two configs share a name" ), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when configs in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_yaml: bool = typer.Option(False, "--yaml", help="Output raw YAML content only"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a discovery config's details or YAML content.""" client = get_client(profile) - match = _require_single_matched_config_or_abort(_find_by_name(client, name, config_type), name) + match = _require_single_matched_config_or_abort(client, _find_by_name(client, name, config_type, project), name) config_id = require_id_or_abort(match.id, f"discovery config '{name}'") full = client.get_discovery_config(config_id) @@ -107,6 +128,7 @@ def get_config( data: dict[str, object] = { "id": full.id, + "project": project_label(project_names(client), full.project), "name": full.name, "type": full.config_type.value, "valid": full.is_valid.value if full.is_valid else "unknown", @@ -151,6 +173,7 @@ def create_config( "Required when the config does not yet exist; defaults to the existing type on updates." ), ), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a discovery config from a YAML file. @@ -159,7 +182,7 @@ def create_config( type from; an update defaults to whatever the existing row is stored as. """ client = get_client(profile) - existing = _find_by_name(client, name) + existing = _find_by_name(client, name, project=project) if config_type is not None: resolved_type = config_type @@ -173,16 +196,22 @@ def create_config( hint="Pass --type database|file to create a new one.", ) else: - options = ", ".join(c.config_type.value for c in existing) + names = project_names(client) + options = ", ".join(f"{c.config_type.value} in {project_label(names, c.project)}" for c in existing) abort( f"Multiple discovery configs named '{name}' ({options}).", code=ErrorCode.AMBIGUOUS, - hint="Pass --type database|file to pick which one to update.", + hint="Pass --type database|file or --project to pick which one to update.", ) yaml_content = read_text_or_abort(file) - config = DiscoveryConfig(name=name, yaml=yaml_content, config_type=resolved_type) + config = DiscoveryConfig( + name=name, + yaml=yaml_content, + config_type=resolved_type, + project=resolve_create_project(client, project, [c for c in existing if c.config_type is resolved_type]), + ) client.create_or_update_discovery_config(config) print_success(f"Discovery config '{name}' ({resolved_type.value}) created/updated.") @@ -193,12 +222,15 @@ def delete_config( config_type: DiscoveryConfigType | None = typer.Option( None, "--type", "-t", help="Required when two configs share a name" ), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when configs in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a discovery config by name.""" client = get_client(profile) - match = _require_single_matched_config_or_abort(_find_by_name(client, name, config_type), name) + match = _require_single_matched_config_or_abort(client, _find_by_name(client, name, config_type, project), name) config_id = require_id_or_abort(match.id, f"discovery config '{name}'") if not is_confirmed: @@ -212,11 +244,14 @@ def delete_config( def validate_config( file: Path = typer.Option(..., "--file", "-f", help="Path to YAML config file", exists=True, readable=True), config_type: DiscoveryConfigType = typer.Option(..., "--type", "-t", help="Config type: database or file"), + project: str | None = typer.Option( + None, "--project", help="Project to validate in; required when the instance has more than one" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Validate a discovery config YAML file against the DataMasque server. - Creates a temporary config to trigger server-side validation, + Creates a temporary config in the project to trigger server-side validation, then deletes it. Reports any validation errors. Note that configs over 60 KiB validate asynchronously and cannot be validated here. @@ -231,7 +266,8 @@ def validate_config( temp_name = f"__dm_cli_validate_{uuid.uuid4().hex}" client = get_client(profile) - config = DiscoveryConfig(name=temp_name, yaml=yaml_content, config_type=config_type) + target = resolve_target_project(client, project) + config = DiscoveryConfig(name=temp_name, yaml=yaml_content, config_type=config_type, project=target.reference) try: created = client.create_discovery_config(config) @@ -260,15 +296,19 @@ def show_config_status( config_type: DiscoveryConfigType | None = typer.Option( None, "--type", "-t", help="Required when two configs share a name" ), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when configs in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a discovery config's validation status.""" client = get_client(profile) - match = _require_single_matched_config_or_abort(_find_by_name(client, name, config_type), name) + match = _require_single_matched_config_or_abort(client, _find_by_name(client, name, config_type, project), name) status = match.is_valid.value if match.is_valid else "unknown" data: dict[str, object] = { + "project": project_label(project_names(client), match.project), "name": match.name, "type": match.config_type.value, "status": status, diff --git a/src/datamasque_cli/commands/files.py b/src/datamasque_cli/commands/files.py index 03bbd10..5d263be 100644 --- a/src/datamasque_cli/commands/files.py +++ b/src/datamasque_cli/commands/files.py @@ -8,8 +8,17 @@ from datamasque.client.models.files import DataMasqueFile, SnowflakeKeyFile from datamasque_cli.client import get_client -from datamasque_cli.errors import ErrorCode, abort, confirm_or_abort +from datamasque_cli.errors import confirm_or_abort from datamasque_cli.output import print_success, render_output +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + in_project, + project_label, + project_names, + require_single_or_abort, + resolve_optional_project, + resolve_target_project, +) app = typer.Typer(help="Manage uploaded files (Oracle wallets, Snowflake keys).", no_args_is_help=True) @@ -30,22 +39,28 @@ def _resolve_file_type(type_name: str) -> type[DataMasqueFile]: @app.command("list") def list_files( file_type: str = typer.Argument(help="File type: snowflake-key"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List uploaded files of a given type.""" + """List uploaded files of a given type, or those in one project.""" klass = _resolve_file_type(file_type) client = get_client(profile) - files = client.list_files_of_type(klass) + target = resolve_optional_project(client, project) + files = client.list_files_of_type(klass, project=target.id if target else None) + names = project_names(client) - data = [{"id": f.id, "name": f.name} for f in files] - render_output(data, is_json=is_json, columns=["id", "name"], title=f"Files ({file_type})") + data = [{"id": f.id, "project": project_label(names, f.project), "name": f.name} for f in files] + render_output(data, is_json=is_json, columns=["id", "project", "name"], title=f"Files ({file_type})") @app.command("delete") def delete_file( file_type: str = typer.Argument(help="File type: snowflake-key"), name: str = typer.Argument(help="File name"), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when files in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: @@ -53,9 +68,10 @@ def delete_file( klass = _resolve_file_type(file_type) client = get_client(profile) - match = client.get_file_of_type_by_name(klass, name) - if match is None: - abort(f"File '{name}' ({file_type}) not found.", code=ErrorCode.NOT_FOUND) + named = [f for f in client.list_files_of_type(klass) if f.name == name] + match = require_single_or_abort( + client, in_project(named, resolve_optional_project(client, project)), f"File '{name}' ({file_type})" + ) if not is_confirmed: confirm_or_abort(f"Delete file '{name}' ({file_type})?") @@ -69,10 +85,14 @@ def upload_file( file_type: str = typer.Argument(help="File type: snowflake-key"), file: Path = typer.Option(..., "--file", "-f", help="Path to file", exists=True, readable=True), name: str = typer.Option(..., help="Name for the uploaded file"), + project: str | None = typer.Option( + None, "--project", help="Project to upload to; required when the instance has more than one" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Upload a file.""" klass = _resolve_file_type(file_type) client = get_client(profile) - client.upload_file(klass, name, file) + target = resolve_target_project(client, project) + client.upload_file(klass, name, file, project=target.id) print_success(f"File '{name}' uploaded as {file_type}.") diff --git a/src/datamasque_cli/commands/ruleset_libraries.py b/src/datamasque_cli/commands/ruleset_libraries.py index d43190b..dfe5fa1 100644 --- a/src/datamasque_cli/commands/ruleset_libraries.py +++ b/src/datamasque_cli/commands/ruleset_libraries.py @@ -5,55 +5,71 @@ from pathlib import Path import typer +from datamasque.client import DataMasqueClient from datamasque.client.exceptions import DataMasqueApiError from datamasque.client.models.ruleset_library import RulesetLibrary from datamasque.client.models.status import ValidationStatus from datamasque_cli.client import get_client -from datamasque_cli.errors import ErrorCode, abort, abort_api_error, abort_if_invalid, confirm_or_abort +from datamasque_cli.errors import abort_api_error, abort_if_invalid, confirm_or_abort from datamasque_cli.fileio import read_text_or_abort from datamasque_cli.output import print_info, print_success, render_output, should_emit_json +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + in_project, + project_label, + project_names, + require_single_or_abort, + resolve_create_project, + resolve_optional_project, +) app = typer.Typer(help="Manage ruleset libraries.", no_args_is_help=True) +def _find_library(client: DataMasqueClient, name: str, project: str | None) -> RulesetLibrary: + """Return the library named `name`, with its YAML, in `project` or in the one project that has it.""" + matches = [lib for lib in client.list_ruleset_libraries() if lib.name == name] + matches = in_project(matches, resolve_optional_project(client, project)) + found = require_single_or_abort(client, matches, f"Library '{name}'") + return client.get_ruleset_library(found.id) + + @app.command("list") def list_libraries( + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all ruleset libraries.""" + """List all ruleset libraries, or those in one project.""" client = get_client(profile) - libraries = client.list_ruleset_libraries() + libraries = in_project(client.list_ruleset_libraries(), resolve_optional_project(client, project)) + names = project_names(client) data = [ { "id": lib.id, - "namespace": lib.namespace or "", + "project": project_label(names, lib.project), "name": lib.name, "valid": lib.is_valid.value if lib.is_valid else "unknown", } for lib in libraries ] - render_output(data, is_json=is_json, columns=["id", "namespace", "name", "valid"], title="Ruleset Libraries") + render_output(data, is_json=is_json, columns=["id", "project", "name", "valid"], title="Ruleset Libraries") @app.command("get") def get_library( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_yaml: bool = typer.Option(False, "--yaml", help="Output raw YAML content only"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a library's details or YAML content.""" client = get_client(profile) - lib = client.get_ruleset_library_by_name(name, namespace) - - if lib is None: - label = f"{namespace}/{name}" if namespace else name - abort(f"Library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) if is_yaml: typer.echo(lib.yaml) @@ -61,7 +77,7 @@ def get_library( data: dict[str, object] = { "id": lib.id, - "namespace": lib.namespace, + "project": project_label(project_names(client), lib.project), "name": lib.name, "valid": lib.is_valid.value if lib.is_valid else "unknown", "created": lib.created, @@ -74,14 +90,15 @@ def get_library( def create_library( name: str = typer.Option(..., help="Library name"), file: Path = typer.Option(..., "--file", "-f", help="Path to YAML library file", exists=True, readable=True), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a ruleset library from a YAML file.""" yaml_content = read_text_or_abort(file) client = get_client(profile) - library = RulesetLibrary(name=name, namespace=namespace, yaml=yaml_content) + existing = [lib for lib in client.list_ruleset_libraries() if lib.name == name] + library = RulesetLibrary(name=name, project=resolve_create_project(client, project, existing), yaml=yaml_content) client.create_or_update_ruleset_library(library) print_success(f"Library '{name}' created/updated.") @@ -89,23 +106,22 @@ def create_library( @app.command("delete") def delete_library( name: str = typer.Argument(help="Library name to delete"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), force: bool = typer.Option(False, "--force", help="Force delete even if imported by rulesets"), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a ruleset library by name.""" - label = f"{namespace}/{name}" if namespace else name + label = name client = get_client(profile) - if client.get_ruleset_library_by_name(name, namespace) is None: - abort(f"Library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) if not is_confirmed: confirm_or_abort(f"Delete library '{label}'?") try: - client.delete_ruleset_library_by_name_if_exists(name, namespace, force=force) + client.delete_ruleset_library_by_id_if_exists(lib.id, force=force) except DataMasqueApiError as exc: abort_api_error( f"Failed to delete library '{label}'", @@ -119,20 +135,17 @@ def delete_library( @app.command("validate") def validate_library( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Re-validate a ruleset library against the current server schema. Triggers a server-side validation pass on an existing library and reports the result. """ - label = f"{namespace}/{name}" if namespace else name + label = name client = get_client(profile) - lib = client.get_ruleset_library_by_name(name, namespace) - - if lib is None: - abort(f"Library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) try: validated = client.validate_ruleset_library(lib.id) @@ -147,22 +160,18 @@ def validate_library( @app.command("status") def show_library_status( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a ruleset library's validation status.""" client = get_client(profile) - lib = client.get_ruleset_library_by_name(name, namespace) - - if lib is None: - label = f"{namespace}/{name}" if namespace else name - abort(f"Library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) status = lib.is_valid.value if lib.is_valid else "unknown" errors = lib.validation_errors or [] data: dict[str, object] = { - "namespace": lib.namespace, + "project": project_label(project_names(client), lib.project), "name": lib.name, "status": status, } @@ -179,27 +188,25 @@ def show_library_status( @app.command("usage") def library_usage( name: str = typer.Argument(help="Library name"), - namespace: str = typer.Option("", "--namespace", "-n", help="Library namespace"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show which rulesets import a given library.""" client = get_client(profile) - lib = client.get_ruleset_library_by_name(name, namespace) - - if lib is None: - label = f"{namespace}/{name}" if namespace else name - abort(f"Library '{label}' not found.", code=ErrorCode.NOT_FOUND) + lib = _find_library(client, name, project) rulesets = client.list_rulesets_using_library(lib.id) + names = project_names(client) data = [ { "id": rs.id, + "project": project_label(names, rs.project), "name": rs.name, "type": rs.ruleset_type.value, } for rs in rulesets ] - render_output(data, is_json=is_json, columns=["id", "name", "type"], title=f"Rulesets using '{name}'") + render_output(data, is_json=is_json, columns=["id", "project", "name", "type"], title=f"Rulesets using '{name}'") diff --git a/src/datamasque_cli/commands/rulesets.py b/src/datamasque_cli/commands/rulesets.py index 42b50a4..838c14f 100644 --- a/src/datamasque_cli/commands/rulesets.py +++ b/src/datamasque_cli/commands/rulesets.py @@ -31,6 +31,15 @@ write_text_or_abort, ) from datamasque_cli.output import print_info, print_success, print_warning, render_output, should_emit_json +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + in_project, + project_label, + project_names, + resolve_create_project, + resolve_optional_project, + resolve_target_project, +) app = typer.Typer(help="Manage masking rulesets.", no_args_is_help=True) @@ -39,24 +48,31 @@ def _find_by_name( client: DataMasqueClient, name: str, mask_type: RulesetType | None = None, + project: str | None = None, ) -> list[Ruleset]: - """Return all rulesets matching `name`, optionally narrowed by `mask_type`.""" + """Return all rulesets matching `name`, optionally narrowed by `mask_type` and by the project `--project` names.""" matches = [rs for rs in client.list_rulesets() if rs.name == name] if mask_type is not None: matches = [rs for rs in matches if rs.ruleset_type == mask_type] - return matches + return in_project(matches, resolve_optional_project(client, project)) -def _require_single_matched_ruleset_or_abort(matched_rulesets: list[Ruleset], name: str) -> Ruleset: - """Return the single ruleset matching `name`, or abort asking for `--type`.""" +def _require_single_matched_ruleset_or_abort( + client: DataMasqueClient, matched_rulesets: list[Ruleset], name: str +) -> Ruleset: + """Return the single ruleset matching `name`, or abort asking for `--type` or `--project`.""" if not matched_rulesets: abort(f"Ruleset '{name}' not found.", code=ErrorCode.NOT_FOUND) if len(matched_rulesets) > 1: - options = "\n ".join(f"id={rs.id} type={rs.ruleset_type.value}" for rs in matched_rulesets) + names = project_names(client) + options = "\n ".join( + f"id={rs.id} type={rs.ruleset_type.value} project={project_label(names, rs.project)}" + for rs in matched_rulesets + ) abort( f"Multiple rulesets named '{name}':\n {options}", code=ErrorCode.AMBIGUOUS, - hint="Pass --type database|file to disambiguate.", + hint="Pass --type database|file or --project to disambiguate.", ) return matched_rulesets[0] @@ -64,26 +80,29 @@ def _require_single_matched_ruleset_or_abort(matched_rulesets: list[Ruleset], na @app.command("list") def list_rulesets( ruleset_type: RulesetType | None = typer.Option(None, "--type", "-t", help="Filter by type: database or file"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all rulesets.""" + """List all rulesets, or those in one project.""" client = get_client(profile) - rulesets = client.list_rulesets() + rulesets = in_project(client.list_rulesets(), resolve_optional_project(client, project)) if ruleset_type is not None: rulesets = [rs for rs in rulesets if rs.ruleset_type == ruleset_type] + names = project_names(client) data = [ { "id": rs.id, + "project": project_label(names, rs.project), "name": rs.name, "type": rs.ruleset_type.value, } for rs in rulesets ] - render_output(data, is_json=is_json, columns=["id", "name", "type"], title="Rulesets") + render_output(data, is_json=is_json, columns=["id", "project", "name", "type"], title="Rulesets") @app.command("get") @@ -92,13 +111,16 @@ def get_ruleset( ruleset_type: RulesetType | None = typer.Option( None, "--type", "-t", help="Required when two rulesets share a name" ), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when rulesets in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_yaml: bool = typer.Option(False, "--yaml", help="Output raw YAML content only"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a ruleset's details or YAML content.""" client = get_client(profile) - match = _require_single_matched_ruleset_or_abort(_find_by_name(client, name, ruleset_type), name) + match = _require_single_matched_ruleset_or_abort(client, _find_by_name(client, name, ruleset_type, project), name) # `list_rulesets` omits the YAML body for performance; fetch the single ruleset # to populate `yaml` via the Ruleset pydantic model's `config_yaml` alias. @@ -111,6 +133,7 @@ def get_ruleset( data: dict[str, object] = { "id": full.id, + "project": project_label(project_names(client), full.project), "name": full.name, "type": full.ruleset_type.value, "yaml": full.yaml, @@ -131,16 +154,17 @@ def create_ruleset( "Required when the ruleset does not yet exist; defaults to the existing type on updates." ), ), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a ruleset from a YAML file. - Read the server first to decide which namespace the upload belongs in. A + Read the server first to decide which type the upload has. A brand-new ruleset needs --type because there is no stored row to copy the type from; an update defaults to whatever the existing row is stored as. """ client = get_client(profile) - existing = _find_by_name(client, name) + existing = _find_by_name(client, name, project=project) if ruleset_type is not None: rs_type = ruleset_type @@ -154,15 +178,21 @@ def create_ruleset( hint="Pass --type database|file to create a new one.", ) else: - options = ", ".join(r.ruleset_type.value for r in existing) + names = project_names(client) + options = ", ".join(f"{r.ruleset_type.value} in {project_label(names, r.project)}" for r in existing) abort( f"Multiple rulesets named '{name}' ({options}).", code=ErrorCode.AMBIGUOUS, - hint="Pass --type database|file to pick which one to update.", + hint="Pass --type database|file or --project to pick which one to update.", ) yaml_content = read_text_or_abort(file) - ruleset = Ruleset(name=name, yaml=yaml_content, ruleset_type=rs_type) + ruleset = Ruleset( + name=name, + yaml=yaml_content, + ruleset_type=rs_type, + project=resolve_create_project(client, project, [r for r in existing if r.ruleset_type is rs_type]), + ) client.create_or_update_ruleset(ruleset) print_success(f"Ruleset '{name}' ({rs_type.value}) created/updated.") @@ -173,12 +203,15 @@ def delete_ruleset( ruleset_type: RulesetType | None = typer.Option( None, "--type", "-t", help="Required when two rulesets share a name" ), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when rulesets in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a ruleset by name.""" client = get_client(profile) - match = _require_single_matched_ruleset_or_abort(_find_by_name(client, name, ruleset_type), name) + match = _require_single_matched_ruleset_or_abort(client, _find_by_name(client, name, ruleset_type, project), name) ruleset_id = require_id_or_abort(match.id, f"ruleset '{name}'") if not is_confirmed: @@ -197,11 +230,14 @@ def validate_ruleset( "-t", help="Ruleset type: database or file", ), + project: str | None = typer.Option( + None, "--project", help="Project to validate in; required when the instance has more than one" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Validate a ruleset YAML file against the DataMasque server. - Creates a temporary ruleset to trigger server-side validation, + Creates a temporary ruleset in the project to trigger server-side validation, then deletes it. Reports any validation errors. Note that rulesets over 60 KiB validate asynchronously and cannot be validated here. @@ -217,7 +253,8 @@ def validate_ruleset( temp_name = f"__dm_cli_validate_{uuid.uuid4().hex}" client = get_client(profile) - ruleset = Ruleset(name=temp_name, yaml=yaml_content, ruleset_type=ruleset_type) + target = resolve_target_project(client, project) + ruleset = Ruleset(name=temp_name, yaml=yaml_content, ruleset_type=ruleset_type, project=target.reference) try: created = client.create_or_update_ruleset(ruleset) @@ -318,16 +355,20 @@ def show_ruleset_status( ruleset_type: RulesetType | None = typer.Option( None, "--type", "-t", help="Required when two rulesets share a name" ), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when rulesets in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show a ruleset's validation status.""" client = get_client(profile) - match = _require_single_matched_ruleset_or_abort(_find_by_name(client, name, ruleset_type), name) + match = _require_single_matched_ruleset_or_abort(client, _find_by_name(client, name, ruleset_type, project), name) status = match.is_valid.value if match.is_valid else "unknown" errors = match.validation_errors or [] data: dict[str, object] = { + "project": project_label(project_names(client), match.project), "name": match.name, "type": match.ruleset_type.value, "status": status, diff --git a/src/datamasque_cli/commands/runs.py b/src/datamasque_cli/commands/runs.py index 56304c5..566303f 100644 --- a/src/datamasque_cli/commands/runs.py +++ b/src/datamasque_cli/commands/runs.py @@ -11,10 +11,9 @@ import typer from datamasque.client import DataMasqueClient, RunId from datamasque.client.exceptions import DataMasqueApiError, InvalidLibraryError, RunNotCancellableError -from datamasque.client.models.connection import ConnectionConfig from datamasque.client.models.runs import MaskingRunOptions, MaskingRunRequest, RunInfo -from datamasque_cli.client import get_client +from datamasque_cli.client import get_client, resolve_connection from datamasque_cli.errors import ErrorCode, abort, abort_api_error, abort_if_not_found from datamasque_cli.fileio import write_text_or_abort from datamasque_cli.output import ( @@ -27,18 +26,26 @@ stdout_console, style_status, ) +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + in_project, + project_label, + project_names, + resolve_optional_project, +) app = typer.Typer(help="Manage masking runs.", no_args_is_help=True) _POLL_INTERVAL_SECONDS = 5 -def _format_run_info(run: RunInfo, *, is_styled: bool = False) -> dict[str, object]: - """Extract the fields most useful for display from a `RunInfo`.""" +def _format_run_info(run: RunInfo, names: dict[str, str], *, is_styled: bool = False) -> dict[str, object]: + """Extract the fields most useful for display from a `RunInfo`, naming its project from `names`.""" status = run.status.value destination = run.destination_connection.name if run.destination_connection else None return { "id": run.id, + "project": project_label(names, run.project), "status": style_status(status) if is_styled else status, "ruleset": run.ruleset_name, "source": run.source_connection.name, @@ -47,11 +54,15 @@ def _format_run_info(run: RunInfo, *, is_styled: bool = False) -> dict[str, obje } -def _format_run_dict(run_data: dict[str, object], *, is_styled: bool = False) -> dict[str, object]: +def _format_run_dict( + run_data: dict[str, object], names: dict[str, str], *, is_styled: bool = False +) -> dict[str, object]: """Extract display fields from a raw run list-response dict (not yet modelled in dm-python 1.0.0).""" status = str(run_data.get("status") or run_data.get("run_status") or "") + project = run_data.get("project") return { "id": run_data.get("id"), + "project": project_label(names, project if isinstance(project, str) else None), "status": style_status(status) if is_styled else status, "ruleset": run_data.get("ruleset_name"), "source": run_data.get("source_connection_name"), @@ -89,36 +100,18 @@ def _get_run_log_or_abort(client: DataMasqueClient, run_id: int) -> str: return log -def _resolve_connection(client: DataMasqueClient, name_or_id: str) -> ConnectionConfig: - """Return the connection matching `name_or_id`, preferring name.""" - connections = client.list_connections() - - match = next((c for c in connections if c.name == name_or_id), None) - if match is not None: - return match - - match = next((c for c in connections if str(c.id) == name_or_id), None) - if match is not None: - return match - - available = ", ".join(c.name for c in connections) - abort(f"Connection '{name_or_id}' not found.", code=ErrorCode.NOT_FOUND, hint=f"Available: {available}") - - -def _resolve_connection_id(client: DataMasqueClient, name_or_id: str) -> str: - """Resolve a connection name to its UUID. Pass through if already a UUID.""" - return str(_resolve_connection(client, name_or_id).id) - - -def _resolve_ruleset_id(client: DataMasqueClient, name_or_id: str, mask_type: str | None = None) -> str: +def _resolve_ruleset_id( + client: DataMasqueClient, name_or_id: str, mask_type: str | None = None, project: str | None = None +) -> str: """Resolve a ruleset name to its UUID. `mask_type` is the source connection's type when called from `run start`. - Providing it narrows the lookup to the matching namespace, which is what + Providing it narrows the lookup to the matching type, which is what disambiguates same-named rulesets across the database/file split. + `project` narrows it to the project `--project` names. """ rulesets = client.list_rulesets() - by_name = [r for r in rulesets if r.name == name_or_id] + by_name = in_project([r for r in rulesets if r.name == name_or_id], resolve_optional_project(client, project)) if mask_type is not None: by_name_and_type = [r for r in by_name if r.ruleset_type.value == mask_type] @@ -135,11 +128,12 @@ def _resolve_ruleset_id(client: DataMasqueClient, name_or_id: str, mask_type: st if len(by_name) == 1: return str(by_name[0].id) if len(by_name) > 1: - options = ", ".join(f"{r.ruleset_type.value}:{r.id}" for r in by_name) + names = project_names(client) + options = ", ".join(f"{r.ruleset_type.value}:{project_label(names, r.project)}:{r.id}" for r in by_name) abort( f"Multiple rulesets named '{name_or_id}' ({options}).", code=ErrorCode.AMBIGUOUS, - hint="Pass a UUID instead, or rename one of them.", + hint="Pass --project or a UUID instead, or rename one of them.", ) by_id = next((r for r in rulesets if str(r.id) == name_or_id), None) @@ -197,14 +191,17 @@ def start_run( is_background: bool = typer.Option( False, "--background", "-b", help="Return immediately without waiting for completion" ), + project: str | None = typer.Option( + None, "--project", help="Project of the ruleset and connections, when their names exist in more than one" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Start a new masking run.""" client = get_client(profile) - source = _resolve_connection(client, connection) - ruleset_id = _resolve_ruleset_id(client, ruleset, mask_type=source.mask_type) + source = resolve_connection(client, connection, project) + ruleset_id = _resolve_ruleset_id(client, ruleset, mask_type=source.mask_type, project=project) # Without `destination_connection` in the payload the server defaults # `mask_type` to `database`, so a file source produces a confusing @@ -221,7 +218,7 @@ def start_run( destination_id: str | None = None if destination is not None: - dest = _resolve_connection(client, destination) + dest = resolve_connection(client, destination, project) if dest.mask_type != source.mask_type: abort( f"Connection type mismatch: source '{source.name}' is {source.mask_type} " @@ -261,13 +258,16 @@ def run_status( # Skip rich styling tags when output will be JSON — otherwise they'd appear # as literal "[status.finished]finished[/status.finished]" in the dump. is_styled = not should_emit_json(is_json) - render_output(_format_run_info(run, is_styled=is_styled), is_json=is_json, title=f"Run {run_id}") + render_output( + _format_run_info(run, project_names(client), is_styled=is_styled), is_json=is_json, title=f"Run {run_id}" + ) @app.command("list") def list_runs( status_filter: str | None = typer.Option(None, "--status", "-s", help="Filter by status"), limit: int = typer.Option(20, "--limit", "-l", help="Maximum number of runs to show"), + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: @@ -280,6 +280,10 @@ def list_runs( # `list_runs` is not yet wrapped in datamasque-python; hit the endpoint directly. params = [] + target = resolve_optional_project(client, project) + if target is not None: + # Filtered on the server, so `--limit` counts only this project's runs. + params.append(f"project={target.id}") if status_filter is not None: params.append(f"run_status={status_filter}") if limit is not None: @@ -299,12 +303,13 @@ def list_runs( else: runs = body is_styled = not should_emit_json(is_json) - data = [_format_run_dict(r, is_styled=is_styled) for r in runs] + names = project_names(client) + data = [_format_run_dict(r, names, is_styled=is_styled) for r in runs] render_output( data, is_json=is_json, - columns=["id", "status", "ruleset", "source", "destination", "created"], + columns=["id", "project", "status", "ruleset", "source", "destination", "created"], title="Masking Runs", ) @@ -500,7 +505,7 @@ def _wait_for_run( duration = _format_duration(int(elapsed)) if should_emit_json(is_json): - print_json(_format_run_info(run)) + print_json(_format_run_info(run, project_names(client))) status = run.status summary_parts = [f"Run {run_id} {status.value} in {duration}"] diff --git a/src/datamasque_cli/commands/seeds.py b/src/datamasque_cli/commands/seeds.py index 3f07b59..e188795 100644 --- a/src/datamasque_cli/commands/seeds.py +++ b/src/datamasque_cli/commands/seeds.py @@ -8,47 +8,66 @@ from datamasque.client.models.files import SeedFile from datamasque_cli.client import get_client -from datamasque_cli.errors import ErrorCode, abort, confirm_or_abort +from datamasque_cli.errors import confirm_or_abort from datamasque_cli.output import print_success, render_output +from datamasque_cli.projects import ( + in_project, + project_label, + project_names, + require_single_or_abort, + resolve_optional_project, + resolve_target_project, +) app = typer.Typer(help="Manage seed files.", no_args_is_help=True) @app.command("list") def list_seeds( + project: str | None = typer.Option(None, "--project", help="Project name or id; also lists the built-in seeds"), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all seed files.""" + """List all seed files, or those in one project plus the built-in seeds.""" client = get_client(profile) - seeds = client.list_files_of_type(SeedFile) + target = resolve_optional_project(client, project) + seeds = client.list_files_of_type(SeedFile, project=target.id if target else None) + names = project_names(client) - data = [{"id": s.id, "name": s.name} for s in seeds] - render_output(data, is_json=is_json, columns=["id", "name"], title="Seed Files") + data = [{"id": s.id, "project": project_label(names, s.project), "name": s.name} for s in seeds] + render_output(data, is_json=is_json, columns=["id", "project", "name"], title="Seed Files") @app.command("upload") def upload_seed( file: Path = typer.Argument(help="Path to seed file", exists=True, readable=True), + project: str | None = typer.Option( + None, "--project", help="Project to upload to; required when the instance has more than one" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Upload a seed file.""" client = get_client(profile) - client.upload_file(SeedFile, file.name, file) + target = resolve_target_project(client, project) + client.upload_file(SeedFile, file.name, file, project=target.id) print_success(f"Seed file '{file.name}' uploaded.") @app.command("delete") def delete_seed( filename: str = typer.Argument(help="Seed filename to delete"), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when seeds in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a seed file by filename.""" client = get_client(profile) - match = client.get_file_of_type_by_name(SeedFile, filename) - if match is None: - abort(f"Seed file '{filename}' not found.", code=ErrorCode.NOT_FOUND) + named = [seed for seed in client.list_files_of_type(SeedFile) if seed.name == filename] + match = require_single_or_abort( + client, in_project(named, resolve_optional_project(client, project)), f"Seed file '{filename}'" + ) if not is_confirmed: confirm_or_abort(f"Delete seed file '{filename}'?") diff --git a/src/datamasque_cli/commands/table_references.py b/src/datamasque_cli/commands/table_references.py index be4836a..e61b948 100644 --- a/src/datamasque_cli/commands/table_references.py +++ b/src/datamasque_cli/commands/table_references.py @@ -12,9 +12,18 @@ from datamasque.client.models.table_reference import TableReference, TableReferenceFormat, TableReferenceOptions from datamasque_cli.client import get_client, resolve_connection -from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort +from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort, require_id_or_abort from datamasque_cli.fileio import read_model_or_abort from datamasque_cli.output import print_success, render_output +from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, + in_project, + project_label, + project_names, + require_single_or_abort, + resolve_create_project, + resolve_optional_project, +) app = typer.Typer( help=( @@ -56,28 +65,29 @@ def _list_or_abort(client: DataMasqueClient) -> list[TableReference]: abort_api_error("Failed to list table references", exc) -def _get_or_abort(client: DataMasqueClient, name: str) -> TableReference | None: - """Return the table reference named `name`, or `None`, or abort with the reason the lookup failed.""" - try: - reference: TableReference | None = client.get_table_reference_by_name(name) - return reference - except DataMasqueApiError as exc: - _abort_if_unsupported(exc) - abort_api_error(f"Failed to look up table reference '{name}'", exc) +def _get_or_abort(client: DataMasqueClient, name: str, project: str | None) -> TableReference: + """Return the table reference named `name`, in `project` or in the one project that has it, else abort.""" + named = [ref for ref in _list_or_abort(client) if ref.name == name] + return require_single_or_abort( + client, in_project(named, resolve_optional_project(client, project)), f"Table reference '{name}'" + ) @app.command("list") def list_references( + project: str | None = typer.Option(None, "--project", help=PROJECT_OPTION_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """List all table references.""" + """List all table references, or those in one project.""" client = get_client(profile) - references = _list_or_abort(client) + references = in_project(_list_or_abort(client), resolve_optional_project(client, project)) + names = project_names(client) data = [ { "id": ref.id, + "project": project_label(names, ref.project), "name": ref.name, "connection": ref.connection_id, "source": ref.source, @@ -85,24 +95,28 @@ def list_references( for ref in references ] - render_output(data, is_json=is_json, columns=["id", "name", "connection", "source"], title="Table References") + render_output( + data, is_json=is_json, columns=["id", "project", "name", "connection", "source"], title="Table References" + ) @app.command("get") def get_reference( name: str = typer.Argument(help="Table reference name"), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when references in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: """Show details for a specific table reference.""" client = get_client(profile) - reference = _get_or_abort(client, name) - if reference is None: - abort(f"Table reference '{name}' not found.", code=ErrorCode.NOT_FOUND) + reference = _get_or_abort(client, name, project) options = reference.options data: dict[str, object] = { "id": reference.id, + "project": project_label(project_names(client), reference.project), "name": reference.name, "connection": reference.connection_id, "source": reference.source, @@ -117,9 +131,9 @@ def get_reference( render_output(data, is_json=is_json, title=f"Table Reference: {name}") -def _resolve_connection_id(client: DataMasqueClient, name_or_id: str) -> ConnectionId: - """Resolve a `--connection` value (name or ID) to a connection ID.""" - return resolve_connection(client, name_or_id).id +def _resolve_connection_id(client: DataMasqueClient, name_or_id: str, project: str | None) -> ConnectionId: + """Resolve a `--connection` value (name or ID), narrowed by `--project`, to a connection ID.""" + return resolve_connection(client, name_or_id, project).id def _option_overrides( @@ -155,6 +169,9 @@ def create_reference( encoding: str | None = typer.Option(None, help=f"CSV encoding {_CSV_OPTION_HELP}"), quotechar: str | None = typer.Option(None, help=f"CSV quote character {_CSV_OPTION_HELP}"), null_string: str | None = typer.Option(None, help=f"String read as null {_CSV_OPTION_HELP}"), + project: str | None = typer.Option( + None, "--project", help="Project for the reference, also used to find --connection by name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Create or update a table reference. @@ -186,26 +203,30 @@ def create_reference( "--file cannot be combined with --name/--connection/--source/--format/CSV-option flags.", code=ErrorCode.INVALID_INPUT, ) - _create_from_file(client, file) + _create_from_file(client, file, project) return if name is None or connection is None or source is None: abort("Provide either --file or all of --name, --connection, and --source.", code=ErrorCode.INVALID_INPUT) overrides = _option_overrides(file_format, delimiter, encoding, quotechar, null_string) + existing = [ref for ref in _list_or_abort(client) if ref.name == name] reference = TableReference( name=name, - connection=_resolve_connection_id(client, connection), + connection=_resolve_connection_id(client, connection, project), source=source, options=TableReferenceOptions(**overrides) if overrides else None, + project=resolve_create_project(client, project, existing), ) _create_or_update(client, reference) print_success(f"Table reference '{name}' created/updated.") -def _create_from_file(client: DataMasqueClient, file: Path) -> None: - """Create a table reference from a JSON file.""" +def _create_from_file(client: DataMasqueClient, file: Path, project: str | None) -> None: + """Create a table reference from a JSON file, in the project `--project` names when given.""" reference = read_model_or_abort(file, TableReference) + existing = [ref for ref in _list_or_abort(client) if ref.name == reference.name] + reference.project = resolve_create_project(client, project, existing) _create_or_update(client, reference) print_success(f"Table reference '{reference.name}' created/updated.") @@ -214,11 +235,11 @@ def _create_or_update(client: DataMasqueClient, reference: TableReference) -> No """Create or update `reference`, distinguishing an unsupported server from any other failure. `create_or_update_table_reference` itself makes two requests (a GET to look up an existing - reference by name, then a POST or PUT), so probe support with `_get_or_abort` first and let + reference by name, then a POST or PUT), so probe support with `_list_or_abort` first and let a 404 from the create/update call surface as a plain API error instead of being misread as "not supported". """ - _get_or_abort(client, reference.name) + _list_or_abort(client) try: client.create_or_update_table_reference(reference) except DataMasqueApiError as exc: @@ -235,6 +256,9 @@ def update_reference( encoding: str | None = typer.Option(None, help=f"New CSV encoding {_CSV_OPTION_HELP}"), quotechar: str | None = typer.Option(None, help=f"New CSV quote character {_CSV_OPTION_HELP}"), null_string: str | None = typer.Option(None, help=f"New null-string value {_CSV_OPTION_HELP}"), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when references in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Update selected fields on an existing table reference, preserving its ID.""" @@ -243,12 +267,10 @@ def update_reference( abort("Pass at least one field to update (e.g. --source, --format).", code=ErrorCode.INVALID_INPUT) client = get_client(profile) - reference = _get_or_abort(client, name) - if reference is None: - abort(f"Table reference '{name}' not found.", code=ErrorCode.NOT_FOUND) + reference = _get_or_abort(client, name, project) if connection is not None: - reference.connection = _resolve_connection_id(client, connection) + reference.connection = _resolve_connection_id(client, connection, project) if source is not None: reference.source = source if overrides: @@ -268,20 +290,21 @@ def update_reference( @app.command("delete") def delete_reference( name: str = typer.Argument(help="Table reference name to delete"), + project: str | None = typer.Option( + None, "--project", help="Project name or id; required when references in two projects share a name" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a table reference by name.""" client = get_client(profile) - reference = _get_or_abort(client, name) - if reference is None: - abort(f"Table reference '{name}' not found.", code=ErrorCode.NOT_FOUND) + reference = _get_or_abort(client, name, project) if not is_confirmed: confirm_or_abort(f"Delete table reference '{name}'?") try: - client.delete_table_reference_by_name_if_exists(name) + client.delete_table_reference_by_id_if_exists(require_id_or_abort(reference.id, f"table reference '{name}'")) except DataMasqueApiError as exc: abort_api_error(f"Failed to delete table reference '{name}'", exc) print_success(f"Table reference '{name}' deleted.") diff --git a/src/datamasque_cli/projects.py b/src/datamasque_cli/projects.py new file mode 100644 index 0000000..2eb5a55 --- /dev/null +++ b/src/datamasque_cli/projects.py @@ -0,0 +1,123 @@ +"""Resolve `--project` and name each resource's project in output.""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from typing import Protocol, TypeVar + +from datamasque.client import DataMasqueClient +from datamasque.client.models.project import Project + +from datamasque_cli.errors import ErrorCode, abort + +PROJECT_OPTION_HELP = "Project name or id" + + +class ProjectScoped(Protocol): + """A resource that records its project as an `-` reference.""" + + @property + def project(self) -> str | None: ... + + +ScopedT = TypeVar("ScopedT", bound=ProjectScoped) + + +def resolve_project(client: DataMasqueClient, name_or_id: str) -> Project: + """Return the active project named `name_or_id`, ignoring case, or with that numeric id.""" + projects = client.list_projects() + match = next((p for p in projects if p.name.casefold() == name_or_id.casefold()), None) + if match is None and name_or_id.isdigit(): + match = next((p for p in projects if p.id == int(name_or_id)), None) + if match is None: + abort(f"Project '{name_or_id}' not found.", code=ErrorCode.NOT_FOUND) + return match + + +def resolve_optional_project(client: DataMasqueClient, name_or_id: str | None) -> Project | None: + """Return the project `name_or_id` names, or `None` when no `--project` was given.""" + return None if name_or_id is None else resolve_project(client, name_or_id) + + +def resolve_target_project(client: DataMasqueClient, name_or_id: str | None) -> Project: + """ + Return the project to put a new resource in: the one `--project` names, else the only active project. + + Aborts when no `--project` was given and the instance has more than one active project, + as the server does for a create that names no project. + """ + if name_or_id is not None: + return resolve_project(client, name_or_id) + projects = client.list_projects() + if len(projects) == 1: + return projects[0] + abort( + f"The instance has {len(projects)} active projects.", + code=ErrorCode.AMBIGUOUS, + hint="Pass --project to choose one.", + ) + + +def resolve_create_project(client: DataMasqueClient, name_or_id: str | None, existing: Sequence[ProjectScoped]) -> str: + """ + Return the `-` reference of the project a create-or-update writes to. + + That is the project `--project` names; else the one project that already has a resource of that name, so an + update needs no `--project`; else the instance's only active project. + """ + references = {item.project for item in existing} + if name_or_id is None and len(references) == 1: + (reference,) = references + if reference is not None: + return reference + target: str = resolve_target_project(client, name_or_id).reference + return target + + +def project_names(client: DataMasqueClient) -> dict[str, str]: + """Map each project's `-` reference to its name, archived projects included.""" + return {p.reference: p.name for p in client.list_projects(include_archived=True)} + + +def project_label(names: dict[str, str], reference: str | None) -> str: + """Name the project `reference` points at, or "" for a resource in no project, such as a built-in seed.""" + if reference is None: + return "" + return names.get(reference, reference) + + +def in_project(items: Sequence[ScopedT], project: Project | None) -> list[ScopedT]: + """Keep the items in `project`, or all of them when `project` is `None`.""" + if project is None: + return list(items) + return [item for item in items if item.project == project.reference] + + +def require_single_or_abort( + client: DataMasqueClient, + matches: Sequence[ScopedT], + label: str, + *, + describe: Callable[[ScopedT], str] | None = None, + hint: str = "Pass --project to disambiguate.", +) -> ScopedT: + """ + Return the one resource in `matches`, or abort when there is none or several. + + Several matches means the name exists in more than one project, so the hint asks for `--project`. + `describe` adds a per-match detail, such as the id, to the list the error shows. + """ + if not matches: + abort(f"{label} not found.", code=ErrorCode.NOT_FOUND) + if len(matches) > 1: + names = project_names(client) + options = "\n ".join( + f"project={project_label(names, item.project)}" + (f" {describe(item)}" if describe else "") + for item in matches + ) + abort( + f"{label} exists in more than one project:\n {options}", + code=ErrorCode.AMBIGUOUS, + hint=hint, + ) + return matches[0] diff --git a/tests/commands/test_connections.py b/tests/commands/test_connections.py index cf92a84..10a242b 100644 --- a/tests/commands/test_connections.py +++ b/tests/commands/test_connections.py @@ -17,6 +17,7 @@ from datamasque_cli.commands.connections import _format_role from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import with_projects MODULE = "datamasque_cli.commands.connections" @@ -58,7 +59,7 @@ def test_format_role_for_database_connections_is_always_source() -> None: @patch(f"{MODULE}.get_client") def test_list_connections_includes_role_column(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ MountedShareConnectionConfig( @@ -82,7 +83,7 @@ def test_list_connections_includes_role_column(mock_get_client: MagicMock, runne @patch(f"{MODULE}.get_client") def test_create_connection_database(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client result = runner.invoke( @@ -114,7 +115,7 @@ def test_create_connection_database(mock_get_client: MagicMock, runner: CliRunne @patch(f"{MODULE}.get_client") def test_create_connection_mounted_share(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client result = runner.invoke( @@ -144,7 +145,7 @@ def test_create_connection_missing_name_aborts(mock_get_client: MagicMock, runne @patch(f"{MODULE}.get_client") def test_create_connection_from_json_file(mock_get_client: MagicMock, runner: CliRunner, tmp_path: MagicMock) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client conn_file = tmp_path / "conn.json" @@ -173,7 +174,7 @@ def test_create_connection_from_json_file_invalid_schema_aborts( mock_get_client: MagicMock, runner: CliRunner, tmp_path: MagicMock ) -> None: """Valid JSON that doesn't match the connection type's schema aborts cleanly instead of raising.""" - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client conn_file = tmp_path / "conn.json" @@ -191,7 +192,7 @@ def test_create_connection_from_json_file_invalid_schema_aborts( def test_create_databricks_connection_from_json_file( mock_get_client: MagicMock, runner: CliRunner, tmp_path: MagicMock ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client conn_file = tmp_path / "dbx.json" @@ -220,7 +221,7 @@ def test_create_databricks_connection_from_json_file( def test_create_mongodb_connection_from_json_file( mock_get_client: MagicMock, runner: CliRunner, tmp_path: MagicMock ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client conn_file = tmp_path / "mongo.json" @@ -253,7 +254,7 @@ def test_delete_connection_confirmed(mock_get_client: MagicMock, mock_client: Ma mock_get_client.return_value = mock_client runner.invoke(app, ["connections", "delete", "my_conn", "--yes"]) - mock_client.delete_connection_by_name_if_exists.assert_called_once_with("my_conn") + mock_client.delete_connection_by_id_if_exists.assert_called_once_with(1) @patch(f"{MODULE}.get_client") @@ -261,7 +262,7 @@ def test_delete_connection_declined(mock_get_client: MagicMock, mock_client: Mag mock_get_client.return_value = mock_client runner.invoke(app, ["connections", "delete", "my_conn"], input="n\n") - mock_client.delete_connection_by_name_if_exists.assert_not_called() + mock_client.delete_connection_by_id_if_exists.assert_not_called() @patch(f"{MODULE}.get_client") @@ -273,7 +274,7 @@ def test_delete_connection_aborts_when_missing( result = runner.invoke(app, ["connections", "delete", "no_such_conn", "--yes"]) assert result.exit_code == ExitCode.NOT_FOUND - mock_client.delete_connection_by_name_if_exists.assert_not_called() + mock_client.delete_connection_by_id_if_exists.assert_not_called() # -- test (reachability check) -------------------------------------------- @@ -369,7 +370,7 @@ def test_update_connection_aborts_when_missing( @patch(f"{MODULE}.get_client") def test_get_connection_redacts_password(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ DatabaseConnectionConfig( diff --git a/tests/commands/test_discovery.py b/tests/commands/test_discovery.py index d6f8cc3..fff83c4 100644 --- a/tests/commands/test_discovery.py +++ b/tests/commands/test_discovery.py @@ -1,7 +1,6 @@ from __future__ import annotations import json -from collections.abc import Callable from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock, patch @@ -33,6 +32,7 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, with_projects MODULE = "datamasque_cli.commands.discovery" @@ -57,7 +57,7 @@ def _make_numeric_preview() -> NumericPreview: @patch(f"{MODULE}.get_client") def test_sdd_report_writes_to_output_file(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_sdd_report.return_value = "col1,col2\na,b\n" @@ -70,7 +70,7 @@ def test_sdd_report_writes_to_output_file(mock_get_client: MagicMock, runner: Cl @patch(f"{MODULE}.get_client") def test_sdd_report_echoes_to_stdout_without_output(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_sdd_report.return_value = "col1,col2\na,b\n" @@ -82,7 +82,7 @@ def test_sdd_report_echoes_to_stdout_without_output(mock_get_client: MagicMock, @patch(f"{MODULE}.get_client") def test_db_report_writes_csv_to_output_file(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_db_discovery_result_report.return_value = "header\nrow1\n" @@ -95,7 +95,7 @@ def test_db_report_writes_csv_to_output_file(mock_get_client: MagicMock, runner: @patch(f"{MODULE}.get_client") def test_db_report_writes_zip_when_split(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client zip_bytes = b"PK\x03\x04 fake zip bytes" client.get_db_discovery_result_report.return_value = zip_bytes @@ -110,7 +110,7 @@ def test_db_report_writes_zip_when_split(mock_get_client: MagicMock, runner: Cli @patch(f"{MODULE}.get_client") def test_db_report_split_without_output_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_db_discovery_result_report.return_value = b"PK\x03\x04 fake zip bytes" @@ -138,7 +138,7 @@ def _make_file_report() -> list[FileDiscoveryResult]: @patch(f"{MODULE}.get_client") def test_file_report_writes_json_to_output(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_file_data_discovery_report.return_value = _make_file_report() @@ -152,7 +152,7 @@ def test_file_report_writes_json_to_output(mock_get_client: MagicMock, runner: C @patch(f"{MODULE}.get_client") def test_file_report_table_lists_locators(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_file_data_discovery_report.return_value = _make_file_report() @@ -182,7 +182,7 @@ def test_file_report_table_lists_locators(mock_get_client: MagicMock, runner: Cl def _client_missing_output(client_method: str, status: int, detail: str) -> MagicMock: - client = MagicMock() + client = with_projects(MagicMock()) response = MagicMock(status_code=status) response.json.return_value = {"detail": detail} getattr(client, client_method).side_effect = DataMasqueApiError(f"{status}", response=response) @@ -262,7 +262,7 @@ def test_output_missing_for_unknown_run_is_not_found( @patch(f"{MODULE}.get_client") def test_unexpected_api_error_is_not_swallowed(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client response = MagicMock(status_code=500) response.json.return_value = {"detail": "Report generation crashed."} @@ -280,10 +280,10 @@ def test_unexpected_api_error_is_not_swallowed(mock_get_client: MagicMock, runne @patch(f"{MODULE}.get_client") def test_schema_starts_discovery_run_and_points_at_results(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ - SimpleNamespace(id="abc-123", name="my_db", mask_type="database"), + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE), ] client.start_schema_discovery_run.return_value = 99 @@ -298,9 +298,11 @@ def test_schema_starts_discovery_run_and_points_at_results(mock_get_client: Magi @patch(f"{MODULE}.get_client") def test_schema_emits_run_id_as_json(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="abc-123", name="my_db", mask_type="database")] + client.list_connections.return_value = [ + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE) + ] client.start_schema_discovery_run.return_value = 99 result = runner.invoke(app, ["discover", "schema", "my_db", "--json"]) @@ -311,9 +313,11 @@ def test_schema_emits_run_id_as_json(mock_get_client: MagicMock, runner: CliRunn @patch(f"{MODULE}.get_client") def test_file_start_failure_reports_server_detail(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="fs-1", name="my_files", mask_type="file")] + client.list_connections.return_value = [ + SimpleNamespace(id="fs-1", name="my_files", mask_type="file", project=DEFAULT_PROJECT_REFERENCE) + ] response = MagicMock(status_code=400) response.json.return_value = {"detail": "Simultaneous runs on the same connection are not allowed."} client.start_file_data_discovery_run.side_effect = DataMasqueApiError("boom", response=response) @@ -327,7 +331,7 @@ def test_file_start_failure_reports_server_detail(mock_get_client: MagicMock, ru @patch(f"{MODULE}.get_client") def test_schema_results_lists_with_flattened_rows(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_schema_discovery_results.return_value = [ SimpleNamespace( @@ -371,7 +375,7 @@ def test_schema_results_lists_with_flattened_rows(mock_get_client: MagicMock, ru @patch(f"{MODULE}.get_client") def test_schema_results_skips_unlabelled_matches(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_schema_discovery_results.return_value = [ SimpleNamespace( @@ -413,7 +417,7 @@ def test_schema_results_skips_unlabelled_matches(mock_get_client: MagicMock, run @patch(f"{MODULE}.get_client") def test_schema_results_includes_safe_data_preview_in_json(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_schema_discovery_results.return_value = [ SimpleNamespace( @@ -447,7 +451,7 @@ def test_schema_results_includes_safe_data_preview_in_json(mock_get_client: Magi def test_schema_results_hints_at_json_only_when_safe_data_preview_present( mock_get_client: MagicMock, runner: CliRunner, has_safe_data_preview: bool ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_schema_discovery_results.return_value = [ SimpleNamespace( @@ -474,24 +478,25 @@ def test_schema_results_hints_at_json_only_when_safe_data_preview_present( # -- configurable-discovery run triggers ---------------------------------- -def _fake_config_lookup(**ids_by_type: str) -> Callable[[str, DiscoveryConfigType], SimpleNamespace | None]: - """Return a `get_discovery_config_by_name` side effect that knows only the given types.""" - - def lookup(name: str, config_type: DiscoveryConfigType) -> SimpleNamespace | None: - config_id = ids_by_type.get(config_type.value) - if config_id is None: - return None - return SimpleNamespace(id=config_id, name=name, config_type=config_type) - - return lookup +def _saved_configs(**ids_by_type: str) -> list[SimpleNamespace]: + """Return a `list_discovery_configs` result holding, under each test config name, only the given types.""" + return [ + SimpleNamespace( + id=config_id, name=name, config_type=DiscoveryConfigType(type_), project=DEFAULT_PROJECT_REFERENCE + ) + for type_, config_id in ids_by_type.items() + for name in ("emp", "docs") + ] @patch(f"{MODULE}.get_client") def test_schema_with_config_runs_from_saved_config(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="abc-123", name="my_db", mask_type="database")] - client.get_discovery_config_by_name.side_effect = _fake_config_lookup(database="cfg-1") + client.list_connections.return_value = [ + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_discovery_configs.return_value = _saved_configs(database="cfg-1") client.start_schema_discovery_run_from_config.return_value = 77 result = runner.invoke(app, ["discover", "schema", "my_db", "--config", "emp"]) @@ -507,10 +512,12 @@ def test_schema_with_config_runs_from_saved_config(mock_get_client: MagicMock, r @patch(f"{MODULE}.get_client") def test_schema_config_wrong_type_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="abc-123", name="my_db", mask_type="database")] - client.get_discovery_config_by_name.side_effect = _fake_config_lookup(file="cfg-2") + client.list_connections.return_value = [ + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_discovery_configs.return_value = _saved_configs(file="cfg-2") result = runner.invoke(app, ["discover", "schema", "my_db", "--config", "docs"]) @@ -522,10 +529,12 @@ def test_schema_config_wrong_type_aborts(mock_get_client: MagicMock, runner: Cli @patch(f"{MODULE}.get_client") def test_schema_config_not_found_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: """Neither type holds the name, so this is not-found rather than a type mismatch.""" - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="abc-123", name="my_db", mask_type="database")] - client.get_discovery_config_by_name.side_effect = _fake_config_lookup() + client.list_connections.return_value = [ + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_discovery_configs.return_value = _saved_configs() result = runner.invoke(app, ["discover", "schema", "my_db", "--config", "nope"]) @@ -535,9 +544,11 @@ def test_schema_config_not_found_aborts(mock_get_client: MagicMock, runner: CliR @patch(f"{MODULE}.get_client") def test_file_without_config_runs_keyword_discovery(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="fs-1", name="my_files", mask_type="file")] + client.list_connections.return_value = [ + SimpleNamespace(id="fs-1", name="my_files", mask_type="file", project=DEFAULT_PROJECT_REFERENCE) + ] client.start_file_data_discovery_run.return_value = 88 result = runner.invoke(app, ["discover", "file", "my_files"]) @@ -552,10 +563,12 @@ def test_file_without_config_runs_keyword_discovery(mock_get_client: MagicMock, @patch(f"{MODULE}.get_client") def test_file_with_config_runs_from_saved_config(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="fs-1", name="my_files", mask_type="file")] - client.get_discovery_config_by_name.side_effect = _fake_config_lookup(file="cfg-3") + client.list_connections.return_value = [ + SimpleNamespace(id="fs-1", name="my_files", mask_type="file", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_discovery_configs.return_value = _saved_configs(file="cfg-3") client.start_file_data_discovery_run_from_config.return_value = 89 result = runner.invoke(app, ["discover", "file", "my_files", "--config", "docs"]) @@ -570,13 +583,13 @@ def test_file_with_config_runs_from_saved_config(mock_get_client: MagicMock, run _CONFIG_RUN_STARTS = [ ( ["discover", "schema", "my_db", "--config", "emp"], - SimpleNamespace(id="abc-123", name="my_db", mask_type="database"), + SimpleNamespace(id="abc-123", name="my_db", mask_type="database", project=DEFAULT_PROJECT_REFERENCE), {"database": "cfg-1"}, "start_schema_discovery_run_from_config", ), ( ["discover", "file", "my_files", "--config", "docs"], - SimpleNamespace(id="fs-1", name="my_files", mask_type="file"), + SimpleNamespace(id="fs-1", name="my_files", mask_type="file", project=DEFAULT_PROJECT_REFERENCE), {"file": "cfg-3"}, "start_file_data_discovery_run_from_config", ), @@ -602,10 +615,10 @@ def test_config_run_start_error_keeps_its_own_code( config_ids: dict[str, str], start_method: str, ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [connection] - client.get_discovery_config_by_name.side_effect = _fake_config_lookup(**config_ids) + client.list_discovery_configs.return_value = _saved_configs(**config_ids) getattr(client, start_method).side_effect = error( "run failed to start: the config is unusable", response=MagicMock(status_code=400) ) @@ -618,9 +631,11 @@ def test_config_run_start_error_keeps_its_own_code( @patch(f"{MODULE}.get_client") def test_file_emits_run_id_as_json(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="fs-1", name="my_files", mask_type="file")] + client.list_connections.return_value = [ + SimpleNamespace(id="fs-1", name="my_files", mask_type="file", project=DEFAULT_PROJECT_REFERENCE) + ] client.start_file_data_discovery_run.return_value = 88 result = runner.invoke(app, ["discover", "file", "my_files", "--json"]) @@ -631,7 +646,7 @@ def test_file_emits_run_id_as_json(mock_get_client: MagicMock, runner: CliRunner @patch(f"{MODULE}.get_client") def test_config_snapshot_writes_to_output(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_discovery_run_config_snapshot_yaml.return_value = "# provenance\nlabels: []\n" diff --git a/tests/commands/test_discovery_config_libraries.py b/tests/commands/test_discovery_config_libraries.py index f92add3..a36bfec 100644 --- a/tests/commands/test_discovery_config_libraries.py +++ b/tests/commands/test_discovery_config_libraries.py @@ -13,13 +13,14 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, make_project, with_projects MODULE = "datamasque_cli.commands.discovery_config_libraries" def _make_library( name: str, - namespace: str = "", + project: str = DEFAULT_PROJECT_REFERENCE, library_id: str = "lib-uuid", is_valid: ValidationStatus | None = ValidationStatus.valid, usage_count: int = 0, @@ -30,7 +31,7 @@ def _make_library( return SimpleNamespace( id=library_id, name=name, - namespace=namespace, + project=project, is_valid=is_valid, validation_error=validation_error, usage_count=usage_count, @@ -40,78 +41,141 @@ def _make_library( ) +ORG = make_project(2, "Org") +ORG_REFERENCE = ORG.reference + + +def _given_libraries(client: MagicMock, *libraries: SimpleNamespace) -> None: + """Make the mock serve `libraries` from the listing and, by id, with their YAML, in `Default` and `Org`.""" + with_projects(client, make_project(), ORG) + client.list_discovery_config_libraries.return_value = list(libraries) + client.get_discovery_config_library.side_effect = lambda library_id: next( + lib for lib in libraries if lib.id == library_id + ) + + @patch(f"{MODULE}.get_client") -def test_list_shows_namespace_and_usage(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() +def test_list_shows_project_and_usage(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.list_discovery_config_libraries.return_value = [ - _make_library("finance", namespace="org", usage_count=3), - ] + _given_libraries(client, _make_library("finance", project=ORG_REFERENCE, usage_count=3)) result = runner.invoke(app, ["discover", "libraries", "list", "--json"]) assert result.exit_code == 0 assert '"finance"' in result.stdout - assert '"org"' in result.stdout + assert '"project": "Org"' in result.stdout assert '"used_by": 3' in result.stdout @patch(f"{MODULE}.get_client") -def test_get_yaml_fetches_full_library(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() +def test_list_project_keeps_only_that_projects_libraries(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = _make_library( - "finance", namespace="org", yaml="labels: []\n" + _given_libraries( + client, + _make_library("finance", library_id="default-lib"), + _make_library("payroll", project=ORG_REFERENCE, library_id="org-lib"), ) - result = runner.invoke(app, ["discover", "libraries", "get", "finance", "--namespace", "org", "--yaml"]) + result = runner.invoke(app, ["discover", "libraries", "list", "--project", "org", "--json"]) + + assert result.exit_code == 0 + assert '"payroll"' in result.stdout + assert '"finance"' not in result.stdout + + +@patch(f"{MODULE}.get_client") +def test_get_yaml_fetches_the_named_projects_library(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) + mock_get_client.return_value = client + _given_libraries( + client, + _make_library("finance", library_id="default-lib", yaml="default: []\n"), + _make_library("finance", project=ORG_REFERENCE, library_id="org-lib", yaml="labels: []\n"), + ) + + result = runner.invoke(app, ["discover", "libraries", "get", "finance", "--project", "Org", "--yaml"]) assert result.exit_code == 0 assert "labels: []" in result.stdout - client.get_discovery_config_library_by_name.assert_called_once_with("finance", "org") + client.get_discovery_config_library.assert_called_once_with("org-lib") @patch(f"{MODULE}.get_client") -def test_get_namespace_scopes_lookup(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() +def test_get_name_in_two_projects_asks_for_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = None + _given_libraries( + client, + _make_library("finance", library_id="default-lib"), + _make_library("finance", project=ORG_REFERENCE, library_id="org-lib"), + ) result = runner.invoke(app, ["discover", "libraries", "get", "finance"]) + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == ( + "Error: Discovery config library 'finance' exists in more than one project:\n" + " project=Default\n" + " project=Org\n" + "Hint: Pass --project to disambiguate.\n" + ) + client.get_discovery_config_library.assert_not_called() + + +@patch(f"{MODULE}.get_client") +def test_get_unknown_name_is_not_found(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) + mock_get_client.return_value = client + _given_libraries(client) + + result = runner.invoke(app, ["discover", "libraries", "get", "finance"]) + + assert result.exit_code == ExitCode.NOT_FOUND + + +@patch(f"{MODULE}.get_client") +def test_get_unknown_project_is_not_found(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = with_projects(MagicMock()) + mock_get_client.return_value = client + _given_libraries(client, _make_library("finance")) + + result = runner.invoke(app, ["discover", "libraries", "get", "finance", "--project", "nope"]) + assert result.exit_code == ExitCode.NOT_FOUND - client.get_discovery_config_library_by_name.assert_called_once_with("finance", "") + assert "Project 'nope' not found" in result.stderr @patch(f"{MODULE}.get_client") def test_create_posts_library(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock(), make_project(), ORG) mock_get_client.return_value = client lib = tmp_path / "lib.yaml" lib.write_text("labels: []\n") result = runner.invoke( app, - ["discover", "libraries", "create", "--name", "finance", "-n", "org", "-f", str(lib)], + ["discover", "libraries", "create", "--name", "finance", "--project", "Org", "-f", str(lib)], ) assert result.exit_code == 0 client.create_or_update_discovery_config_library.assert_called_once() created = client.create_or_update_discovery_config_library.call_args.args[0] assert created.name == "finance" - assert created.namespace == "org" + assert created.project == ORG_REFERENCE @patch(f"{MODULE}.get_client") def test_delete_force_passes_through(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = _make_library("finance", namespace="org") + _given_libraries(client, _make_library("finance", project=ORG_REFERENCE, library_id="org-lib")) - result = runner.invoke(app, ["discover", "libraries", "delete", "finance", "-n", "org", "--force", "--yes"]) + result = runner.invoke(app, ["discover", "libraries", "delete", "finance", "--project", "Org", "--force", "--yes"]) assert result.exit_code == 0 - client.delete_discovery_config_library_by_name_if_exists.assert_called_once_with("finance", "org", force=True) + client.delete_discovery_config_library_by_id_if_exists.assert_called_once_with("org-lib", force=True) @patch(f"{MODULE}.get_client") @@ -122,16 +186,16 @@ def test_delete_in_use_reports_server_reason(mock_get_client: MagicMock, runner: its `detail` names the count. Without handling, the raised `DataMasqueApiError` escapes as an unhandled exception and the user only sees a stack trace. """ - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = _make_library("finance") + _given_libraries(client, _make_library("finance")) response = MagicMock() response.status_code = HTTPStatus.CONFLICT response.json.return_value = { "detail": 'Cannot delete library "finance": used by 2 active config(s)', "configs": [{"id": "cfg-1", "name": "employees"}], } - client.delete_discovery_config_library_by_name_if_exists.side_effect = DataMasqueApiError( + client.delete_discovery_config_library_by_id_if_exists.side_effect = DataMasqueApiError( "API request to https://dm/api/discovery/config-libraries/lib-uuid/ failed with status 409", response=response, ) @@ -146,13 +210,13 @@ def test_delete_in_use_reports_server_reason(mock_get_client: MagicMock, runner: @patch(f"{MODULE}.get_client") def test_delete_other_api_error_is_generic_failure(mock_get_client: MagicMock, runner: CliRunner) -> None: """Non-409 API failures still abort cleanly rather than raising.""" - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = _make_library("finance") + _given_libraries(client, _make_library("finance")) response = MagicMock() response.status_code = HTTPStatus.INTERNAL_SERVER_ERROR response.json.side_effect = ValueError("no body") - client.delete_discovery_config_library_by_name_if_exists.side_effect = DataMasqueApiError( + client.delete_discovery_config_library_by_id_if_exists.side_effect = DataMasqueApiError( "API request failed with status 500", response=response ) @@ -164,14 +228,14 @@ def test_delete_other_api_error_is_generic_failure(mock_get_client: MagicMock, r @patch(f"{MODULE}.get_client") def test_delete_missing_is_not_found(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = None + _given_libraries(client) result = runner.invoke(app, ["discover", "libraries", "delete", "finance", "--yes"]) assert result.exit_code == ExitCode.NOT_FOUND - client.delete_discovery_config_library_by_name_if_exists.assert_not_called() + client.delete_discovery_config_library_by_id_if_exists.assert_not_called() @patch(f"{MODULE}.get_client") @@ -189,7 +253,7 @@ def test_validate_empty_file_aborts_before_any_request( @patch(f"{MODULE}.get_client") def test_validate_reports_valid(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config_library.return_value = _make_library("finance", is_valid=ValidationStatus.valid) lib = tmp_path / "lib.yaml" @@ -209,7 +273,7 @@ def test_validate_reports_valid(mock_get_client: MagicMock, runner: CliRunner, t def test_validate_rejected_create_aborts_without_delete( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client response = MagicMock() response.status_code = HTTPStatus.BAD_REQUEST @@ -229,7 +293,7 @@ def test_validate_rejected_create_aborts_without_delete( @patch(f"{MODULE}.get_client") def test_validate_invalid_exits_4(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config_library.return_value = _make_library( "finance", is_valid=ValidationStatus.invalid, validation_error="duplicate label 'email'" @@ -249,7 +313,7 @@ def test_validate_puts_the_reason_in_the_agent_envelope( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setenv("DM_OUTPUT", "json") - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config_library.return_value = _make_library( "finance", is_valid=ValidationStatus.invalid, validation_error="duplicate label 'email'" @@ -269,7 +333,7 @@ def test_validate_puts_the_reason_in_the_agent_envelope( def test_validate_warns_when_temp_library_cleanup_fails( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config_library.return_value = _make_library("finance", is_valid=ValidationStatus.valid) client.delete_discovery_config_library_by_id_if_exists.side_effect = DataMasqueApiError( @@ -299,11 +363,9 @@ def test_status_reports_state( is_valid: ValidationStatus, validation_error: str | None, ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_discovery_config_library_by_name.return_value = _make_library( - "finance", is_valid=is_valid, validation_error=validation_error - ) + _given_libraries(client, _make_library("finance", is_valid=is_valid, validation_error=validation_error)) result = runner.invoke(app, ["discover", "libraries", "status", "finance", "--json"]) diff --git a/tests/commands/test_discovery_configs.py b/tests/commands/test_discovery_configs.py index e79f497..d94f5c9 100644 --- a/tests/commands/test_discovery_configs.py +++ b/tests/commands/test_discovery_configs.py @@ -14,6 +14,7 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, make_project, with_projects MODULE = "datamasque_cli.commands.discovery_configs" @@ -28,6 +29,7 @@ def _make_discovery_config( ) -> SimpleNamespace: """A discovery config as the server returns it, carrying its validation status.""" return SimpleNamespace( + project=DEFAULT_PROJECT_REFERENCE, id=config_id, name=name, config_type=config_type, @@ -51,7 +53,7 @@ def test_unknown_type_is_rejected_before_any_request(mock_get_client: MagicMock, @patch(f"{MODULE}.get_client") def test_list_filters_by_type(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [ _make_discovery_config("emp", DiscoveryConfigType.database), @@ -67,7 +69,7 @@ def test_list_filters_by_type(mock_get_client: MagicMock, runner: CliRunner) -> @patch(f"{MODULE}.get_client") def test_get_yaml_fetches_full_config(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [_make_discovery_config("emp")] client.get_discovery_config.return_value = _make_discovery_config("emp", yaml="labels: []\n") @@ -81,7 +83,7 @@ def test_get_yaml_fetches_full_config(mock_get_client: MagicMock, runner: CliRun @patch(f"{MODULE}.get_client") def test_get_ambiguous_name_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [ _make_discovery_config("shared", DiscoveryConfigType.database, config_id="a"), @@ -96,7 +98,7 @@ def test_get_ambiguous_name_aborts(mock_get_client: MagicMock, runner: CliRunner @patch(f"{MODULE}.get_client") def test_get_ambiguous_resolved_by_type(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [ _make_discovery_config("shared", DiscoveryConfigType.database, config_id="a"), @@ -112,7 +114,7 @@ def test_get_ambiguous_resolved_by_type(mock_get_client: MagicMock, runner: CliR @patch(f"{MODULE}.get_client") def test_defaults_requests_typed_default(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.make_request.return_value = SimpleNamespace(content=b"labels: []\n") @@ -127,7 +129,7 @@ def test_defaults_requests_typed_default(mock_get_client: MagicMock, runner: Cli @patch(f"{MODULE}.get_client") def test_create_new_requires_type(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [] cfg = tmp_path / "cfg.yaml" @@ -146,7 +148,7 @@ def test_create_new_requires_type(mock_get_client: MagicMock, runner: CliRunner, @patch(f"{MODULE}.get_client") def test_create_update_defaults_to_existing_type(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [_make_discovery_config("emp", DiscoveryConfigType.database)] cfg = tmp_path / "cfg.yaml" @@ -158,9 +160,30 @@ def test_create_update_defaults_to_existing_type(mock_get_client: MagicMock, run client.create_or_update_discovery_config.assert_called_once() +@patch(f"{MODULE}.get_client") +def test_create_of_a_new_type_ignores_the_other_types_project( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = with_projects(MagicMock(), make_project(1, "Default"), make_project(2, "Finance")) + mock_get_client.return_value = client + file_config = _make_discovery_config("emp", DiscoveryConfigType.file) + file_config.project = "2-finance" + client.list_discovery_configs.return_value = [file_config] + cfg = tmp_path / "cfg.yaml" + cfg.write_text("labels: []\n") + + result = runner.invoke( + app, ["discover", "configs", "create", "--name", "emp", "-f", str(cfg), "--type", "database"] + ) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert "The instance has 2 active projects." in result.output + client.create_or_update_discovery_config.assert_not_called() + + @patch(f"{MODULE}.get_client") def test_delete_proceeds_when_present(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [_make_discovery_config("emp")] @@ -172,7 +195,7 @@ def test_delete_proceeds_when_present(mock_get_client: MagicMock, runner: CliRun @patch(f"{MODULE}.get_client") def test_delete_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [] @@ -184,7 +207,7 @@ def test_delete_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunne @patch(f"{MODULE}.get_client") def test_validate_reports_valid(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config.return_value = _make_discovery_config("emp", is_valid=ValidationStatus.valid) cfg = tmp_path / "cfg.yaml" @@ -203,7 +226,7 @@ def test_validate_reports_valid(mock_get_client: MagicMock, runner: CliRunner, t @patch(f"{MODULE}.get_client") def test_validate_invalid_exits_4(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config.return_value = _make_discovery_config( "emp", is_valid=ValidationStatus.invalid, validation_error="unknown label 'foo'" @@ -223,7 +246,7 @@ def test_validate_puts_the_reason_in_the_agent_envelope( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setenv("DM_OUTPUT", "json") - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config.return_value = _make_discovery_config( "emp", is_valid=ValidationStatus.invalid, validation_error="unknown label 'foo'" @@ -243,7 +266,7 @@ def test_validate_puts_the_reason_in_the_agent_envelope( def test_validate_rejected_create_aborts_without_delete( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client response = MagicMock() response.status_code = HTTPStatus.BAD_REQUEST @@ -265,7 +288,7 @@ def test_validate_rejected_create_aborts_without_delete( def test_validate_warns_when_temp_config_cleanup_fails( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_discovery_config.return_value = _make_discovery_config("emp", is_valid=ValidationStatus.valid) client.delete_discovery_config_by_id_if_exists.side_effect = DataMasqueApiError("boom", response=MagicMock()) @@ -322,7 +345,7 @@ def test_status_reports_state( is_valid: ValidationStatus, validation_error: str | None, ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_discovery_configs.return_value = [ _make_discovery_config("emp", is_valid=is_valid, validation_error=validation_error) diff --git a/tests/commands/test_files.py b/tests/commands/test_files.py index cdfd7d5..65b58df 100644 --- a/tests/commands/test_files.py +++ b/tests/commands/test_files.py @@ -8,16 +8,19 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, with_projects MODULE = "datamasque_cli.commands.files" @patch(f"{MODULE}.get_client") def test_delete_file_proceeds_when_present(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - match = SnowflakeKeyFile(id="abc", name="mykey", created_date=datetime.now(tz=UTC)) - client.get_file_of_type_by_name.return_value = match + match = SnowflakeKeyFile( + id="abc", name="mykey", created_date=datetime.now(tz=UTC), project=DEFAULT_PROJECT_REFERENCE + ) + client.list_files_of_type.return_value = [match] result = runner.invoke(app, ["files", "delete", "snowflake-key", "mykey", "--yes"]) @@ -27,9 +30,9 @@ def test_delete_file_proceeds_when_present(mock_get_client: MagicMock, runner: C @patch(f"{MODULE}.get_client") def test_delete_file_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_file_of_type_by_name.return_value = None + client.list_files_of_type.return_value = [] result = runner.invoke(app, ["files", "delete", "snowflake-key", "nope", "--yes"]) diff --git a/tests/commands/test_project_options.py b/tests/commands/test_project_options.py new file mode 100644 index 0000000..1da3d06 --- /dev/null +++ b/tests/commands/test_project_options.py @@ -0,0 +1,410 @@ +"""`--project` on list and create commands, and the project in their output.""" + +from __future__ import annotations + +import json +from datetime import UTC, datetime +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +from datamasque.client.models.discovery_config import DiscoveryConfigType +from datamasque.client.models.files import SeedFile, SnowflakeKeyFile +from datamasque.client.models.ruleset import RulesetType +from typer.testing import CliRunner + +from datamasque_cli.errors import ExitCode +from datamasque_cli.main import app +from tests.conftest import make_api_response, make_project, with_projects + +DEFAULT = make_project(1, "Default") +FINANCE = make_project(2, "Finance") + + +def _client() -> MagicMock: + return with_projects(MagicMock(), DEFAULT, FINANCE) + + +def _ruleset(id_: int | str, name: str, project: str) -> SimpleNamespace: + return SimpleNamespace(id=id_, name=name, ruleset_type=RulesetType.database, yaml="", project=project) + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_list_names_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [_ruleset(1, "customers", FINANCE.reference)] + + result = runner.invoke(app, ["rulesets", "list", "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout) == [{"id": 1, "project": "Finance", "name": "customers", "type": "database"}] + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_list_project_keeps_only_that_projects_rulesets(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [ + _ruleset(1, "customers", DEFAULT.reference), + _ruleset(2, "payroll", FINANCE.reference), + ] + + result = runner.invoke(app, ["rulesets", "list", "--project", "finance", "--json"]) + + assert result.exit_code == 0 + assert [row["name"] for row in json.loads(result.stdout)] == ["payroll"] + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_create_sends_the_project(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [] + ruleset_file = tmp_path / "rules.yaml" + ruleset_file.write_text("version: '1.0'\ntasks: []\n") + + result = runner.invoke( + app, + [ + "rulesets", + "create", + "--name", + "customers", + "--type", + "database", + "-f", + str(ruleset_file), + "--project", + "Finance", + ], + ) + + assert result.exit_code == 0 + assert client.create_or_update_ruleset.call_args.args[0].project == FINANCE.reference + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_create_updates_where_the_name_already_is( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [_ruleset(1, "customers", FINANCE.reference)] + ruleset_file = tmp_path / "rules.yaml" + ruleset_file.write_text("version: '1.0'\ntasks: []\n") + + result = runner.invoke(app, ["rulesets", "create", "--name", "customers", "-f", str(ruleset_file)]) + + assert result.exit_code == 0 + assert client.create_or_update_ruleset.call_args.args[0].project == FINANCE.reference + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_create_new_name_needs_a_project_once_there_are_two( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [] + ruleset_file = tmp_path / "rules.yaml" + ruleset_file.write_text("version: '1.0'\ntasks: []\n") + + result = runner.invoke( + app, ["rulesets", "create", "--name", "customers", "--type", "database", "-f", str(ruleset_file)] + ) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == "Error: The instance has 2 active projects.\nHint: Pass --project to choose one.\n" + client.create_or_update_ruleset.assert_not_called() + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_get_name_in_two_projects_asks_for_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [ + _ruleset(1, "customers", DEFAULT.reference), + _ruleset(2, "customers", FINANCE.reference), + ] + + result = runner.invoke(app, ["rulesets", "get", "customers"]) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == ( + "Error: Multiple rulesets named 'customers':\n" + " id=1 type=database project=Default\n" + " id=2 type=database project=Finance\n" + "Hint: Pass --type database|file or --project to disambiguate.\n" + ) + + +@patch("datamasque_cli.commands.rulesets.get_client") +def test_rulesets_get_project_picks_between_same_named_rulesets(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_rulesets.return_value = [ + _ruleset("rs-1", "customers", DEFAULT.reference), + _ruleset("rs-2", "customers", FINANCE.reference), + ] + client.make_request.return_value = make_api_response( + {"id": "rs-2", "name": "customers", "mask_type": "database", "config_yaml": "x", "project": FINANCE.reference} + ) + + result = runner.invoke(app, ["rulesets", "get", "customers", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + client.make_request.assert_called_once_with("GET", "/api/rulesets/rs-2/") + assert json.loads(result.stdout)["project"] == "Finance" + + +@patch("datamasque_cli.commands.connections.get_client") +def test_connections_create_sends_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + + result = runner.invoke( + app, + [ + "connections", + "create", + "--name", + "share", + "--type", + "mounted_share", + "--base-dir", + "in", + "--source", + "--project", + "Finance", + ], + ) + + assert result.exit_code == 0 + assert client.create_or_update_connection.call_args.args[0].project == FINANCE.reference + + +@patch("datamasque_cli.commands.connections.get_client") +def test_connections_list_names_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_connections.return_value = [ + SimpleNamespace(id=1, name="db", project=FINANCE.reference, is_file_mask_source=False) + ] + + result = runner.invoke(app, ["connections", "list", "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout)[0]["project"] == "Finance" + + +@patch("datamasque_cli.commands.seeds.get_client") +def test_seeds_upload_needs_a_project_once_there_are_two( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = _client() + mock_get_client.return_value = client + seed = tmp_path / "names.csv" + seed.write_text("name\nann\n") + + result = runner.invoke(app, ["seeds", "upload", str(seed)]) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == "Error: The instance has 2 active projects.\nHint: Pass --project to choose one.\n" + client.upload_file.assert_not_called() + + +@patch("datamasque_cli.commands.seeds.get_client") +def test_seeds_upload_goes_to_the_named_project(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: + client = _client() + mock_get_client.return_value = client + seed = tmp_path / "names.csv" + seed.write_text("name\nann\n") + + result = runner.invoke(app, ["seeds", "upload", str(seed), "--project", "Finance"]) + + assert result.exit_code == 0 + client.upload_file.assert_called_once_with(SeedFile, "names.csv", seed, project=FINANCE.id) + + +@patch("datamasque_cli.commands.seeds.get_client") +def test_seeds_list_project_asks_the_server_and_names_built_ins_blank( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _client() + mock_get_client.return_value = client + stamp = datetime.now(tz=UTC) + client.list_files_of_type.return_value = [ + SeedFile(id="a", name="names.csv", created_date=stamp, project=FINANCE.reference), + SeedFile(id="b", name="DataMasque_first_names.csv", created_date=stamp, project=None), + ] + + result = runner.invoke(app, ["seeds", "list", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + client.list_files_of_type.assert_called_once_with(SeedFile, project=FINANCE.id) + assert [row["project"] for row in json.loads(result.stdout)] == ["Finance", ""] + + +@patch("datamasque_cli.commands.runs.get_client") +def test_runs_list_project_is_filtered_on_the_server(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.make_request.return_value = make_api_response( + {"results": [{"id": 7, "run_status": "finished", "project": FINANCE.reference}]} + ) + + result = runner.invoke(app, ["run", "list", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + query = client.make_request.call_args.args[1] + assert "project=2" in query + assert json.loads(result.stdout)[0]["project"] == "Finance" + + +@patch("datamasque_cli.commands.table_references.get_client") +def test_table_references_create_sends_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = _client() + mock_get_client.return_value = client + client.list_table_references.return_value = [] + client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input", project=FINANCE.reference)] + + result = runner.invoke( + app, + [ + "table-references", + "create", + "--name", + "ids", + "--connection", + "input", + "--source", + "a.csv", + "--project", + "Finance", + ], + ) + + assert result.exit_code == 0 + assert client.create_or_update_table_reference.call_args.args[0].project == FINANCE.reference + + +@patch("datamasque_cli.commands.connections.get_client") +def test_connections_list_project_keeps_only_that_projects_connections( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_connections.return_value = [ + SimpleNamespace(id=1, name="db", project=DEFAULT.reference, is_file_mask_source=False), + SimpleNamespace(id=2, name="warehouse", project=FINANCE.reference, is_file_mask_source=False), + ] + + result = runner.invoke(app, ["connections", "list", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + assert [row["name"] for row in json.loads(result.stdout)] == ["warehouse"] + + +def _discovery_config(id_: str, name: str, project: str) -> SimpleNamespace: + return SimpleNamespace( + id=id_, name=name, config_type=DiscoveryConfigType.database, is_valid=None, yaml="", project=project + ) + + +@patch("datamasque_cli.commands.discovery_configs.get_client") +def test_discovery_configs_list_names_the_project_and_keeps_only_that_projects_configs( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_discovery_configs.return_value = [ + _discovery_config("c-1", "pii", DEFAULT.reference), + _discovery_config("c-2", "payroll", FINANCE.reference), + ] + + result = runner.invoke(app, ["discover", "configs", "list", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + assert [(row["name"], row["project"]) for row in json.loads(result.stdout)] == [("payroll", "Finance")] + + +@patch("datamasque_cli.commands.discovery_configs.get_client") +def test_discovery_configs_create_sends_the_project( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_discovery_configs.return_value = [] + config_file = tmp_path / "config.yaml" + config_file.write_text("labels: []\n") + + result = runner.invoke( + app, + [ + "discover", + "configs", + "create", + "--name", + "payroll", + "--type", + "database", + "-f", + str(config_file), + "--project", + "Finance", + ], + ) + + assert result.exit_code == 0 + assert client.create_or_update_discovery_config.call_args.args[0].project == FINANCE.reference + + +@patch("datamasque_cli.commands.files.get_client") +def test_files_list_project_asks_the_server_and_names_the_project( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _client() + mock_get_client.return_value = client + stamp = datetime.now(tz=UTC) + client.list_files_of_type.return_value = [ + SnowflakeKeyFile(id="k", name="key.p8", created_date=stamp, project=FINANCE.reference) + ] + + result = runner.invoke(app, ["files", "list", "snowflake-key", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + client.list_files_of_type.assert_called_once_with(SnowflakeKeyFile, project=FINANCE.id) + assert json.loads(result.stdout) == [{"id": "k", "project": "Finance", "name": "key.p8"}] + + +@patch("datamasque_cli.commands.files.get_client") +def test_files_upload_goes_to_the_named_project(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: + client = _client() + mock_get_client.return_value = client + key = tmp_path / "key.p8" + key.write_text("-----BEGIN PRIVATE KEY-----\n") + + result = runner.invoke( + app, ["files", "upload", "snowflake-key", "-f", str(key), "--name", "key.p8", "--project", "Finance"] + ) + + assert result.exit_code == 0 + client.upload_file.assert_called_once_with(SnowflakeKeyFile, "key.p8", key, project=FINANCE.id) + + +@patch("datamasque_cli.commands.table_references.get_client") +def test_table_references_list_project_keeps_only_that_projects_references( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _client() + mock_get_client.return_value = client + client.list_table_references.return_value = [ + SimpleNamespace(id="t-1", name="ids", connection_id="c", source="a.csv", project=DEFAULT.reference), + SimpleNamespace(id="t-2", name="codes", connection_id="c", source="b.csv", project=FINANCE.reference), + ] + + result = runner.invoke(app, ["table-references", "list", "--project", "Finance", "--json"]) + + assert result.exit_code == 0 + assert [(row["name"], row["project"]) for row in json.loads(result.stdout)] == [("codes", "Finance")] diff --git a/tests/commands/test_ruleset_libraries.py b/tests/commands/test_ruleset_libraries.py index 78635e8..44df5d7 100644 --- a/tests/commands/test_ruleset_libraries.py +++ b/tests/commands/test_ruleset_libraries.py @@ -2,37 +2,153 @@ import json from http import HTTPStatus +from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock, patch import pytest from datamasque.client.exceptions import DataMasqueApiError +from datamasque.client.models.ruleset import RulesetType from datamasque.client.models.status import ValidationErrorDetails, ValidationStatus from typer.testing import CliRunner from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, make_project, with_projects MODULE = "datamasque_cli.commands.ruleset_libraries" def _make_ruleset_library( name: str, - namespace: str = "", + project: str = DEFAULT_PROJECT_REFERENCE, library_id: str = "lib-uuid", is_valid: ValidationStatus | None = None, validation_errors: list[ValidationErrorDetails] | None = None, + yaml: str = "", ) -> SimpleNamespace: """A ruleset library as the server returns it, carrying its validation status.""" return SimpleNamespace( id=library_id, name=name, - namespace=namespace, + project=project, is_valid=is_valid, validation_errors=validation_errors or [], + yaml=yaml, + created=None, + modified=None, ) +ORG = make_project(2, "Org") +ORG_REFERENCE = ORG.reference + + +def _given_libraries(client: MagicMock, *libraries: SimpleNamespace) -> None: + """Make the mock serve `libraries` from the listing and, by id, with their YAML, in `Default` and `Org`.""" + with_projects(client, make_project(), ORG) + client.list_ruleset_libraries.return_value = list(libraries) + client.get_ruleset_library.side_effect = lambda library_id: next(lib for lib in libraries if lib.id == library_id) + + +@patch(f"{MODULE}.get_client") +def test_list_project_keeps_only_that_projects_libraries(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries( + client, + _make_ruleset_library("finance", library_id="default-lib"), + _make_ruleset_library("payroll", project=ORG_REFERENCE, library_id="org-lib"), + ) + + result = runner.invoke(app, ["libraries", "list", "--project", "org", "--json"]) + + assert result.exit_code == 0 + assert [lib["name"] for lib in json.loads(result.stdout)] == ["payroll"] + + +@patch(f"{MODULE}.get_client") +def test_list_names_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries(client, _make_ruleset_library("payroll", project=ORG_REFERENCE, library_id="org-lib")) + + result = runner.invoke(app, ["libraries", "list", "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout) == [{"id": "org-lib", "project": "Org", "name": "payroll", "valid": "unknown"}] + + +@patch(f"{MODULE}.get_client") +def test_usage_names_each_rulesets_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries(client, _make_ruleset_library("finance", library_id="lib-1")) + client.list_rulesets_using_library.return_value = [ + SimpleNamespace(id="rs-1", name="customers", ruleset_type=RulesetType.database, project=ORG_REFERENCE) + ] + + result = runner.invoke(app, ["libraries", "usage", "finance", "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout) == [{"id": "rs-1", "project": "Org", "name": "customers", "type": "database"}] + + +@patch(f"{MODULE}.get_client") +def test_get_yaml_fetches_the_named_projects_library(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries( + client, + _make_ruleset_library("finance", library_id="default-lib", yaml="default: []\n"), + _make_ruleset_library("finance", project=ORG_REFERENCE, library_id="org-lib", yaml="org: []\n"), + ) + + result = runner.invoke(app, ["libraries", "get", "finance", "--project", "Org", "--yaml"]) + + assert result.exit_code == 0 + assert result.stdout == "org: []\n\n" + client.get_ruleset_library.assert_called_once_with("org-lib") + + +@patch(f"{MODULE}.get_client") +def test_get_name_in_two_projects_asks_for_the_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries( + client, + _make_ruleset_library("finance", library_id="default-lib"), + _make_ruleset_library("finance", project=ORG_REFERENCE, library_id="org-lib"), + ) + + result = runner.invoke(app, ["libraries", "get", "finance"]) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert result.stderr == ( + "Error: Library 'finance' exists in more than one project:\n" + " project=Default\n" + " project=Org\n" + "Hint: Pass --project to disambiguate.\n" + ) + client.get_ruleset_library.assert_not_called() + + +@patch(f"{MODULE}.get_client") +def test_create_sends_the_named_project(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: + client = MagicMock() + mock_get_client.return_value = client + _given_libraries(client) + lib = tmp_path / "lib.yaml" + lib.write_text("version: '1.0'\n") + + result = runner.invoke(app, ["libraries", "create", "--name", "finance", "--project", "Org", "-f", str(lib)]) + + assert result.exit_code == 0 + created = client.create_or_update_ruleset_library.call_args.args[0] + assert created.name == "finance" + assert created.project == ORG_REFERENCE + + @patch(f"{MODULE}.get_client") def test_delete_in_use_reports_server_reason(mock_get_client: MagicMock, runner: CliRunner) -> None: """A 409 must surface the server's explanation, not a traceback. @@ -43,14 +159,14 @@ def test_delete_in_use_reports_server_reason(mock_get_client: MagicMock, runner: """ client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library("lib") + _given_libraries(client, _make_ruleset_library("lib")) response = MagicMock() response.status_code = HTTPStatus.CONFLICT response.json.return_value = { "detail": 'Cannot delete library "lib": used by 3 active ruleset(s)', "rulesets": [{"id": "rs-1", "name": "customers"}], } - client.delete_ruleset_library_by_name_if_exists.side_effect = DataMasqueApiError( + client.delete_ruleset_library_by_id_if_exists.side_effect = DataMasqueApiError( "API request to https://dm/api/ruleset-libraries/lib-uuid/ failed with status 409", response=response ) @@ -65,31 +181,31 @@ def test_delete_in_use_reports_server_reason(mock_get_client: MagicMock, runner: def test_delete_library_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = None + _given_libraries(client) result = runner.invoke(app, ["libraries", "delete", "nope", "--yes"]) assert result.exit_code == ExitCode.NOT_FOUND - client.delete_ruleset_library_by_name_if_exists.assert_not_called() + client.delete_ruleset_library_by_id_if_exists.assert_not_called() @patch(f"{MODULE}.get_client") def test_delete_library_proceeds_when_present(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = SimpleNamespace(id=1, name="lib", namespace="") + _given_libraries(client, SimpleNamespace(id=1, name="lib", project=DEFAULT_PROJECT_REFERENCE)) result = runner.invoke(app, ["libraries", "delete", "lib", "--yes"]) assert result.exit_code == 0 - client.delete_ruleset_library_by_name_if_exists.assert_called_once_with("lib", "", force=False) + client.delete_ruleset_library_by_id_if_exists.assert_called_once_with(1, force=False) @patch(f"{MODULE}.get_client") def test_validate_library_reports_status(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library("my-lib") + _given_libraries(client, _make_ruleset_library("my-lib")) client.validate_ruleset_library.return_value = _make_ruleset_library("my-lib", is_valid=ValidationStatus.valid) result = runner.invoke(app, ["libraries", "validate", "my-lib"]) @@ -103,7 +219,7 @@ def test_validate_library_reports_status(mock_get_client: MagicMock, runner: Cli def test_validate_library_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = None + _given_libraries(client) result = runner.invoke(app, ["libraries", "validate", "missing"]) @@ -115,7 +231,7 @@ def test_validate_library_aborts_when_missing(mock_get_client: MagicMock, runner def test_validate_library_invalid_prints_errors_and_exits_4(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library("my-lib") + _given_libraries(client, _make_ruleset_library("my-lib")) client.validate_ruleset_library.return_value = _make_ruleset_library( "my-lib", is_valid=ValidationStatus.invalid, @@ -140,7 +256,7 @@ def test_validate_library_puts_every_reason_in_the_agent_envelope( monkeypatch.setenv("DM_OUTPUT", "json") client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library("my-lib") + _given_libraries(client, _make_ruleset_library("my-lib")) client.validate_ruleset_library.return_value = _make_ruleset_library( "my-lib", is_valid=ValidationStatus.invalid, @@ -164,7 +280,7 @@ def test_validate_library_puts_every_reason_in_the_agent_envelope( def test_validate_library_nonterminal_status_passes_through(mock_get_client: MagicMock, runner: CliRunner) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library("my-lib") + _given_libraries(client, _make_ruleset_library("my-lib")) client.validate_ruleset_library.return_value = _make_ruleset_library( "my-lib", is_valid=ValidationStatus.in_progress ) @@ -195,9 +311,7 @@ def test_status_reports_state( ) -> None: client = MagicMock() mock_get_client.return_value = client - client.get_ruleset_library_by_name.return_value = _make_ruleset_library( - "lib", is_valid=is_valid, validation_errors=errors - ) + _given_libraries(client, _make_ruleset_library("lib", is_valid=is_valid, validation_errors=errors)) result = runner.invoke(app, ["libraries", "status", "lib", "--json"]) diff --git a/tests/commands/test_rulesets.py b/tests/commands/test_rulesets.py index 8970ec3..10d24ea 100644 --- a/tests/commands/test_rulesets.py +++ b/tests/commands/test_rulesets.py @@ -13,12 +13,13 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, make_project, with_projects MODULE = "datamasque_cli.commands.rulesets" def _ruleset(id_: int, name: str, rs_type: RulesetType) -> SimpleNamespace: - return SimpleNamespace(id=id_, name=name, ruleset_type=rs_type, yaml="") + return SimpleNamespace(id=id_, name=name, ruleset_type=rs_type, yaml="", project=DEFAULT_PROJECT_REFERENCE) def _make_ruleset_with_status( @@ -28,6 +29,7 @@ def _make_ruleset_with_status( ) -> SimpleNamespace: """A ruleset as the server returns it, carrying its validation status.""" return SimpleNamespace( + project=DEFAULT_PROJECT_REFERENCE, id=id_, name="demo", ruleset_type=RulesetType.database, @@ -52,7 +54,7 @@ def test_unknown_type_is_rejected_before_any_request(mock_get_client: MagicMock, def test_create_requires_type_when_ruleset_is_new( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [] @@ -67,7 +69,7 @@ def test_create_requires_type_when_ruleset_is_new( @patch(f"{MODULE}.get_client") def test_create_uses_existing_type_on_update(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [_ruleset(1, "demo", RulesetType.file)] @@ -82,10 +84,10 @@ def test_create_uses_existing_type_on_update(mock_get_client: MagicMock, runner: @patch(f"{MODULE}.get_client") -def test_create_requires_type_when_both_namespaces_hold_same_name( +def test_create_requires_type_when_database_and_file_rulesets_share_a_name( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "demo", RulesetType.database), @@ -105,7 +107,7 @@ def test_create_requires_type_when_both_namespaces_hold_same_name( def test_create_honours_explicit_type_for_new_ruleset( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [] @@ -126,7 +128,7 @@ def test_create_honours_explicit_type_for_new_ruleset( def test_create_explicit_type_overrides_existing_type( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [_ruleset(1, "demo", RulesetType.database)] @@ -143,12 +145,35 @@ def test_create_explicit_type_overrides_existing_type( assert args[0].ruleset_type == RulesetType.file +@patch(f"{MODULE}.get_client") +def test_create_of_a_new_type_ignores_the_other_types_project( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = with_projects(MagicMock(), make_project(1, "Default"), make_project(2, "Finance")) + mock_get_client.return_value = client + file_ruleset = _ruleset(1, "demo", RulesetType.file) + file_ruleset.project = "2-finance" + client.list_rulesets.return_value = [file_ruleset] + + yaml_file = tmp_path / "rs.yaml" + yaml_file.write_text("tasks: []\n") + + result = runner.invoke( + app, + ["rulesets", "create", "--name", "demo", "--file", str(yaml_file), "--type", "database"], + ) + + assert result.exit_code == ExitCode.AMBIGUOUS + assert "The instance has 2 active projects." in result.output + client.create_or_update_ruleset.assert_not_called() + + # -- get / delete disambiguation ------------------------------------------ @patch(f"{MODULE}.get_client") def test_get_aborts_when_multiple_same_name_without_type(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "demo", RulesetType.database), @@ -161,7 +186,7 @@ def test_get_aborts_when_multiple_same_name_without_type(mock_get_client: MagicM @patch(f"{MODULE}.get_client") def test_get_disambiguates_with_type_flag(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "demo", RulesetType.database), @@ -184,7 +209,7 @@ def test_get_disambiguates_with_type_flag(mock_get_client: MagicMock, runner: Cl @patch(f"{MODULE}.get_client") def test_delete_only_removes_matched_type(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "demo", RulesetType.database), @@ -200,7 +225,7 @@ def test_delete_only_removes_matched_type(mock_get_client: MagicMock, runner: Cl @patch(f"{MODULE}.get_client") def test_delete_aborts_when_ambiguous(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "demo", RulesetType.database), @@ -215,7 +240,7 @@ def test_delete_aborts_when_ambiguous(mock_get_client: MagicMock, runner: CliRun @patch(f"{MODULE}.get_client") def test_delete_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [] @@ -230,7 +255,7 @@ def test_delete_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunne @patch(f"{MODULE}.get_client") def test_list_filters_by_type(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [ _ruleset(1, "a", RulesetType.database), @@ -249,7 +274,7 @@ def test_list_filters_by_type(mock_get_client: MagicMock, runner: CliRunner) -> @patch(f"{MODULE}.get_client") def test_validate_requires_type_flag(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client yaml_file = tmp_path / "rs.yaml" @@ -265,7 +290,7 @@ def test_validate_requires_type_flag(mock_get_client: MagicMock, runner: CliRunn def test_validate_uses_unique_temp_name_and_cleans_by_id( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status(ValidationStatus.valid) @@ -289,7 +314,7 @@ def test_validate_cleans_up_when_print_success_interrupted( tmp_path: Path, ) -> None: """`try/finally` guarantees the temp ruleset is deleted even if a later step raises.""" - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status(ValidationStatus.valid) @@ -303,7 +328,7 @@ def test_validate_cleans_up_when_print_success_interrupted( @patch(f"{MODULE}.get_client") def test_validate_warns_when_cleanup_fails(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status(ValidationStatus.valid) client.delete_ruleset_by_id_if_exists.side_effect = DataMasqueApiError("boom", response=MagicMock()) @@ -321,7 +346,7 @@ def test_validate_warns_when_cleanup_fails(mock_get_client: MagicMock, runner: C def test_validate_sync_invalid_prints_errors_and_cleans_up( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status( ValidationStatus.invalid, @@ -348,7 +373,7 @@ def test_validate_puts_every_reason_in_the_agent_envelope( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setenv("DM_OUTPUT", "json") - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status( ValidationStatus.invalid, @@ -371,7 +396,7 @@ def test_validate_puts_every_reason_in_the_agent_envelope( def test_validate_nonterminal_status_reports_valid( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path, initial_status: ValidationStatus | None ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.create_or_update_ruleset.return_value = _make_ruleset_with_status(initial_status) @@ -389,7 +414,7 @@ def test_validate_nonterminal_status_reports_valid( @patch(f"{MODULE}.get_client") def test_export_bundle_writes_binary_zip(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client mock_response = MagicMock() mock_response.content = b"PK\x03\x04fake-zip-bytes" @@ -405,7 +430,7 @@ def test_export_bundle_writes_binary_zip(mock_get_client: MagicMock, runner: Cli @patch(f"{MODULE}.get_client") def test_import_bundle_requires_confirmation(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client bundle = tmp_path / "bundle.zip" @@ -421,7 +446,7 @@ def test_import_bundle_requires_confirmation(mock_get_client: MagicMock, runner: def test_import_bundle_uploads_zip_archive_as_multipart( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client mock_response = MagicMock() mock_response.content = b"" @@ -458,7 +483,7 @@ def test_import_bundle_uploads_zip_archive_as_multipart( @patch(f"{MODULE}.get_client") def test_system_export_alias_warns_and_delegates(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client mock_response = MagicMock() mock_response.content = b"zip-body" @@ -509,7 +534,7 @@ def test_status_reports_state( is_valid: ValidationStatus, errors: list[ValidationErrorDetails], ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_rulesets.return_value = [_make_ruleset_with_status(is_valid, errors)] diff --git a/tests/commands/test_runs.py b/tests/commands/test_runs.py index 6fa8a0c..aea6883 100644 --- a/tests/commands/test_runs.py +++ b/tests/commands/test_runs.py @@ -19,12 +19,11 @@ _format_run_info, _parse_options, _print_pretty_logs, - _resolve_connection, - _resolve_connection_id, _resolve_ruleset_id, ) from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, with_projects MODULE = "datamasque_cli.commands.runs" @@ -38,6 +37,7 @@ def _run_info(**overrides: Any) -> RunInfo: "source_connection": "src-uuid", "source_connection_name": "my_src", "ruleset_name": "demo", + "project": DEFAULT_PROJECT_REFERENCE, } data.update(overrides) return RunInfo.model_validate(data) @@ -47,35 +47,22 @@ def _run_info(**overrides: Any) -> RunInfo: def test_format_run_info_uses_nested_connection_name() -> None: - result = _format_run_info(_run_info()) + result = _format_run_info(_run_info(), {DEFAULT_PROJECT_REFERENCE: "Default"}) assert result["status"] == "finished" assert result["source"] == "my_src" def test_format_run_dict_prefers_status_over_run_status() -> None: - result = _format_run_dict({"id": 1, "status": "finished", "run_status": "queued"}) + result = _format_run_dict({"id": 1, "status": "finished", "run_status": "queued"}, {}) assert result["status"] == "finished" def test_format_run_dict_falls_back_to_run_status() -> None: - result = _format_run_dict({"id": 1, "run_status": "running"}) + result = _format_run_dict({"id": 1, "run_status": "running"}, {}) assert result["status"] == "running" -# -- _resolve_connection_id / _resolve_ruleset_id -------------------------- - - -def test_resolve_connection_id_by_name(mock_client: MagicMock) -> None: - assert _resolve_connection_id(mock_client, "my_conn") == "1" - - -def test_resolve_connection_id_by_id(mock_client: MagicMock) -> None: - assert _resolve_connection_id(mock_client, "2") == "2" - - -def test_resolve_connection_id_not_found(mock_client: MagicMock) -> None: - with pytest.raises(SystemExit): - _resolve_connection_id(mock_client, "nonexistent") +# -- _resolve_ruleset_id -------------------------------------------------- def test_resolve_ruleset_id_by_name(mock_client: MagicMock) -> None: @@ -88,40 +75,34 @@ def test_resolve_ruleset_id_not_found(mock_client: MagicMock) -> None: def test_resolve_ruleset_id_prefers_matching_mask_type() -> None: - client = MagicMock() + client = with_projects(MagicMock()) client.list_rulesets.return_value = [ - SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database), - SimpleNamespace(id=2, name="demo", ruleset_type=RulesetType.file), + SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database, project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=2, name="demo", ruleset_type=RulesetType.file, project=DEFAULT_PROJECT_REFERENCE), ] assert _resolve_ruleset_id(client, "demo", mask_type="file") == "2" assert _resolve_ruleset_id(client, "demo", mask_type="database") == "1" def test_resolve_ruleset_id_aborts_when_type_missing() -> None: - client = MagicMock() + client = with_projects(MagicMock()) client.list_rulesets.return_value = [ - SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database), + SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database, project=DEFAULT_PROJECT_REFERENCE), ] with pytest.raises(SystemExit): _resolve_ruleset_id(client, "demo", mask_type="file") def test_resolve_ruleset_id_ambiguous_without_type() -> None: - client = MagicMock() + client = with_projects(MagicMock()) client.list_rulesets.return_value = [ - SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database), - SimpleNamespace(id=2, name="demo", ruleset_type=RulesetType.file), + SimpleNamespace(id=1, name="demo", ruleset_type=RulesetType.database, project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=2, name="demo", ruleset_type=RulesetType.file, project=DEFAULT_PROJECT_REFERENCE), ] with pytest.raises(SystemExit): _resolve_ruleset_id(client, "demo") -def test_resolve_connection_returns_name_and_type(mock_client: MagicMock) -> None: - conn = _resolve_connection(mock_client, "my_conn") - assert conn.name == "my_conn" - assert conn.mask_type == "database" - - # -- start_run (behaviour, not wiring) ------------------------------------ @@ -162,15 +143,15 @@ def test_start_run_uses_connection_name_for_run_label( @patch(f"{MODULE}.get_client") def test_start_run_passes_connection_type_to_ruleset_resolver(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ - SimpleNamespace(id=1, name="files_in", mask_type="file"), - SimpleNamespace(id=2, name="files_out", mask_type="file"), + SimpleNamespace(id=1, name="files_in", mask_type="file", project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=2, name="files_out", mask_type="file", project=DEFAULT_PROJECT_REFERENCE), ] client.list_rulesets.return_value = [ - SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.database), - SimpleNamespace(id=20, name="demo", ruleset_type=RulesetType.file), + SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.database, project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=20, name="demo", ruleset_type=RulesetType.file, project=DEFAULT_PROJECT_REFERENCE), ] client.start_masking_run.return_value = RunId(42) client.get_run_info.return_value = _run_info(id=42, status="finished", mask_type="file") @@ -184,14 +165,14 @@ def test_start_run_passes_connection_type_to_ruleset_resolver(mock_get_client: M @patch(f"{MODULE}.get_client") def test_start_run_aborts_on_destination_type_mismatch(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ - SimpleNamespace(id=1, name="db_src", mask_type="database"), - SimpleNamespace(id=2, name="files_dst", mask_type="file"), + SimpleNamespace(id=1, name="db_src", mask_type="database", project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=2, name="files_dst", mask_type="file", project=DEFAULT_PROJECT_REFERENCE), ] client.list_rulesets.return_value = [ - SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.database), + SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.database, project=DEFAULT_PROJECT_REFERENCE), ] result = runner.invoke(app, ["run", "start", "-c", "db_src", "-r", "demo", "-d", "files_dst"]) @@ -276,13 +257,13 @@ def test_start_run_passes_parsed_options_into_payload( @patch(f"{MODULE}.get_client") def test_start_run_aborts_when_file_source_has_no_destination(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.list_connections.return_value = [ - SimpleNamespace(id=1, name="files_src", mask_type="file"), + SimpleNamespace(id=1, name="files_src", mask_type="file", project=DEFAULT_PROJECT_REFERENCE), ] client.list_rulesets.return_value = [ - SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.file), + SimpleNamespace(id=10, name="demo", ruleset_type=RulesetType.file, project=DEFAULT_PROJECT_REFERENCE), ] result = runner.invoke(app, ["run", "start", "-c", "files_src", "-r", "demo"]) @@ -299,10 +280,11 @@ def test_start_run_aborts_when_file_source_has_no_destination(mock_get_client: M def test_retry_run_preserves_source_ruleset_destination_and_options( mock_get_client: MagicMock, runner: CliRunner ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_run_info.return_value = RunInfo.model_validate( { + "project": DEFAULT_PROJECT_REFERENCE, "id": 100, "source_connection": "src-uuid", "source_connection_name": "my_src", @@ -331,11 +313,12 @@ def test_retry_run_preserves_source_ruleset_destination_and_options( @patch(f"{MODULE}.get_client") def test_retry_run_strips_server_managed_option_keys(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client # `get_run_info` echoes server-managed option keys the POST endpoint rejects. client.get_run_info.return_value = RunInfo.model_validate( { + "project": DEFAULT_PROJECT_REFERENCE, "id": 300, "source_connection": "src-uuid", "source_connection_name": "my_src", @@ -363,10 +346,11 @@ def test_retry_run_strips_server_managed_option_keys(mock_get_client: MagicMock, @patch(f"{MODULE}.get_client") def test_retry_run_aborts_when_original_missing_ruleset(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_run_info.return_value = RunInfo.model_validate( { + "project": DEFAULT_PROJECT_REFERENCE, "id": 200, "source_connection": "src-uuid", "source_connection_name": "my_src", @@ -389,7 +373,7 @@ def test_retry_run_aborts_when_original_missing_ruleset(mock_get_client: MagicMo @patch(f"{MODULE}.time") @patch(f"{MODULE}.get_client") def test_logs_follow_polls_until_terminal(mock_get_client: MagicMock, _mock_time: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_run_log.side_effect = ["line 1\n", "line 1\nline 2\n", "line 1\nline 2\nline 3\n"] client.get_run_info.side_effect = [ @@ -413,7 +397,7 @@ def test_logs_follow_polls_until_terminal(mock_get_client: MagicMock, _mock_time def test_logs_follow_recovers_when_server_rotates_log( mock_get_client: MagicMock, _mock_time: MagicMock, runner: CliRunner ) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client # Second poll returns a shorter log (server rotated / compacted). # Third poll adds a new line to the rotated buffer; it must still print. @@ -440,7 +424,7 @@ def test_logs_follow_recovers_when_server_rotates_log( @patch(f"{MODULE}.time") @patch(f"{MODULE}.get_client") def test_wait_run_polls_until_terminal(mock_get_client: MagicMock, _mock_time: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_run_info.side_effect = [ _run_info(id=1, status="queued"), @@ -456,7 +440,7 @@ def test_wait_run_polls_until_terminal(mock_get_client: MagicMock, _mock_time: M @patch(f"{MODULE}.time") @patch(f"{MODULE}.get_client") def test_wait_run_failure_exits_1(mock_get_client: MagicMock, _mock_time: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client client.get_run_info.return_value = _run_info(id=1, status="failed") diff --git a/tests/commands/test_seeds.py b/tests/commands/test_seeds.py index 6f1e0c3..4d8fd38 100644 --- a/tests/commands/test_seeds.py +++ b/tests/commands/test_seeds.py @@ -8,15 +8,16 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, with_projects MODULE = "datamasque_cli.commands.seeds" @patch(f"{MODULE}.get_client") def test_delete_seed_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - client.get_file_of_type_by_name.return_value = None + client.list_files_of_type.return_value = [] result = runner.invoke(app, ["seeds", "delete", "nope.csv", "--yes"]) @@ -26,10 +27,10 @@ def test_delete_seed_aborts_when_missing(mock_get_client: MagicMock, runner: Cli @patch(f"{MODULE}.get_client") def test_delete_seed_proceeds_when_present(mock_get_client: MagicMock, runner: CliRunner) -> None: - client = MagicMock() + client = with_projects(MagicMock()) mock_get_client.return_value = client - match = SeedFile(id="abc", name="foo.csv", created_date=datetime.now(tz=UTC)) - client.get_file_of_type_by_name.return_value = match + match = SeedFile(id="abc", name="foo.csv", created_date=datetime.now(tz=UTC), project=DEFAULT_PROJECT_REFERENCE) + client.list_files_of_type.return_value = [match] result = runner.invoke(app, ["seeds", "delete", "foo.csv", "--yes"]) diff --git a/tests/commands/test_table_references.py b/tests/commands/test_table_references.py index 1930668..998397f 100644 --- a/tests/commands/test_table_references.py +++ b/tests/commands/test_table_references.py @@ -13,16 +13,22 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app +from tests.conftest import DEFAULT_PROJECT_REFERENCE, with_projects MODULE = "datamasque_cli.commands.table_references" def _mock_client() -> MagicMock: - return MagicMock(spec=DataMasqueClient) + return with_projects(MagicMock(spec=DataMasqueClient)) def _reference(**overrides: object) -> TableReference: - defaults: dict[str, object] = {"name": "customer_identities", "connection": "conn-1", "source": "in/customers.csv"} + defaults: dict[str, object] = { + "name": "customer_identities", + "connection": "conn-1", + "source": "in/customers.csv", + "project": DEFAULT_PROJECT_REFERENCE, + } defaults.update(overrides) return TableReference(**defaults) @@ -48,7 +54,13 @@ def test_list_references(mock_get_client: MagicMock, runner: CliRunner) -> None: assert result.exit_code == 0 payload = json.loads(result.stdout) assert payload == [ - {"id": "ref-1", "name": "customer_identities", "connection": "conn-1", "source": "in/customers.csv"} + { + "id": "ref-1", + "project": "Default", + "name": "customer_identities", + "connection": "conn-1", + "source": "in/customers.csv", + } ] @@ -97,9 +109,9 @@ def test_list_references_non_404_error_surfaces_cleanly(mock_get_client: MagicMo def test_get_reference(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference( - id="ref-1", options=TableReferenceOptions(format=TableReferenceFormat.parquet) - ) + client.list_table_references.return_value = [ + _reference(id="ref-1", options=TableReferenceOptions(format=TableReferenceFormat.parquet)) + ] result = runner.invoke(app, ["table-references", "get", "customer_identities", "--json"]) @@ -115,7 +127,7 @@ def test_get_reference_with_no_options_shows_null_not_fabricated_defaults( ) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] result = runner.invoke(app, ["table-references", "get", "customer_identities", "--json"]) @@ -129,7 +141,7 @@ def test_get_reference_with_no_options_shows_null_not_fabricated_defaults( def test_get_reference_not_found(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = None + client.list_table_references.return_value = [] result = runner.invoke(app, ["table-references", "get", "missing"]) @@ -141,7 +153,7 @@ def test_get_reference_not_found(mock_get_client: MagicMock, runner: CliRunner) def test_get_reference_not_supported_by_server(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.side_effect = _api_error(HTTPStatus.NOT_FOUND) + client.list_table_references.side_effect = _api_error(HTTPStatus.NOT_FOUND) result = runner.invoke(app, ["table-references", "get", "customer_identities"]) @@ -156,7 +168,9 @@ def test_get_reference_not_supported_by_server(mock_get_client: MagicMock, runne def test_create_reference_by_connection_name(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke( app, @@ -183,7 +197,9 @@ def test_create_reference_by_connection_name(mock_get_client: MagicMock, runner: def test_create_reference_by_connection_id(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke( app, @@ -208,7 +224,9 @@ def test_create_reference_by_connection_id(mock_get_client: MagicMock, runner: C def test_create_reference_unknown_connection_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke( app, @@ -232,7 +250,9 @@ def test_create_reference_unknown_connection_aborts(mock_get_client: MagicMock, def test_create_reference_with_csv_options(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke( app, @@ -272,7 +292,9 @@ def test_create_reference_parquet_with_csv_options_passes_through( """CSV options are unfiltered pass-through — the server, not the CLI, decides whether they apply.""" client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke( app, @@ -315,7 +337,9 @@ def test_create_reference_server_validation_error_surfaces_cleanly( ) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] client.create_or_update_table_reference.side_effect = _api_error( HTTPStatus.BAD_REQUEST, "table reference with this name already exists" ) @@ -343,8 +367,10 @@ def test_create_reference_server_validation_error_surfaces_cleanly( def test_create_reference_not_supported_by_server(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] - client.get_table_reference_by_name.side_effect = _api_error(HTTPStatus.NOT_FOUND) + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_table_references.side_effect = _api_error(HTTPStatus.NOT_FOUND) result = runner.invoke( app, @@ -372,8 +398,10 @@ def test_create_reference_missing_on_write_is_not_reported_as_unsupported( """A 404 from the create/update call itself is a real failure, not evidence the endpoint is missing.""" client = _mock_client() mock_get_client.return_value = client - client.list_connections.return_value = [SimpleNamespace(id="conn-1", name="input")] - client.get_table_reference_by_name.return_value = None + client.list_connections.return_value = [ + SimpleNamespace(id="conn-1", name="input", project=DEFAULT_PROJECT_REFERENCE) + ] + client.list_table_references.return_value = [] client.create_or_update_table_reference.side_effect = _api_error(HTTPStatus.NOT_FOUND, "Not found.") result = runner.invoke( @@ -493,9 +521,9 @@ def test_create_reference_file_with_other_flags_aborts( def test_update_reference_merges_only_passed_fields(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference( - id="ref-1", options=TableReferenceOptions(delimiter=",", encoding="utf-8") - ) + client.list_table_references.return_value = [ + _reference(id="ref-1", options=TableReferenceOptions(delimiter=",", encoding="utf-8")) + ] result = runner.invoke( app, ["table-references", "update", "customer_identities", "--source", "in/new.csv", "--delimiter", ";"] @@ -516,7 +544,7 @@ def test_update_reference_format_when_options_previously_none(mock_get_client: M """A reference whose options were never set has no existing values to preserve on a full PUT.""" client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] result = runner.invoke(app, ["table-references", "update", "customer_identities", "--format", "parquet"]) @@ -530,8 +558,10 @@ def test_update_reference_format_when_options_previously_none(mock_get_client: M def test_update_reference_connection_by_name(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") - client.list_connections.return_value = [SimpleNamespace(id="conn-2", name="other")] + client.list_table_references.return_value = [_reference(id="ref-1")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-2", name="other", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke(app, ["table-references", "update", "customer_identities", "--connection", "other"]) @@ -545,8 +575,10 @@ def test_update_reference_connection_by_name(mock_get_client: MagicMock, runner: def test_update_reference_unknown_connection_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") - client.list_connections.return_value = [SimpleNamespace(id="conn-2", name="other")] + client.list_table_references.return_value = [_reference(id="ref-1")] + client.list_connections.return_value = [ + SimpleNamespace(id="conn-2", name="other", project=DEFAULT_PROJECT_REFERENCE) + ] result = runner.invoke(app, ["table-references", "update", "customer_identities", "--connection", "nope"]) @@ -558,12 +590,12 @@ def test_update_reference_unknown_connection_aborts(mock_get_client: MagicMock, def test_update_reference_aborts_without_any_fields(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] result = runner.invoke(app, ["table-references", "update", "customer_identities"]) assert result.exit_code == ExitCode.INVALID_INPUT - client.get_table_reference_by_name.assert_not_called() + client.list_table_references.assert_not_called() client.update_table_reference.assert_not_called() @@ -571,7 +603,7 @@ def test_update_reference_aborts_without_any_fields(mock_get_client: MagicMock, def test_update_reference_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = None + client.list_table_references.return_value = [] result = runner.invoke(app, ["table-references", "update", "missing", "--source", "in/new.csv"]) @@ -583,7 +615,7 @@ def test_update_reference_aborts_when_missing(mock_get_client: MagicMock, runner def test_update_reference_not_supported_by_server(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.side_effect = _api_error(HTTPStatus.NOT_FOUND) + client.list_table_references.side_effect = _api_error(HTTPStatus.NOT_FOUND) result = runner.invoke(app, ["table-references", "update", "customer_identities", "--source", "in/new.csv"]) @@ -597,7 +629,7 @@ def test_update_reference_missing_on_write_is_not_reported_as_unsupported( ) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] client.update_table_reference.side_effect = _api_error(HTTPStatus.NOT_FOUND, "Not found.") result = runner.invoke(app, ["table-references", "update", "customer_identities", "--source", "in/new.csv"]) @@ -613,43 +645,43 @@ def test_update_reference_missing_on_write_is_not_reported_as_unsupported( def test_delete_reference_confirmed(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] result = runner.invoke(app, ["table-references", "delete", "customer_identities", "--yes"]) assert result.exit_code == 0 - client.delete_table_reference_by_name_if_exists.assert_called_once_with("customer_identities") + client.delete_table_reference_by_id_if_exists.assert_called_once_with("ref-1") @patch(f"{MODULE}.get_client") def test_delete_reference_declined(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") + client.list_table_references.return_value = [_reference(id="ref-1")] result = runner.invoke(app, ["table-references", "delete", "customer_identities"], input="n\n") assert result.exit_code == ExitCode.CANCELLED - client.delete_table_reference_by_name_if_exists.assert_not_called() + client.delete_table_reference_by_id_if_exists.assert_not_called() @patch(f"{MODULE}.get_client") def test_delete_reference_aborts_when_missing(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = None + client.list_table_references.return_value = [] result = runner.invoke(app, ["table-references", "delete", "missing", "--yes"]) assert result.exit_code == ExitCode.NOT_FOUND - client.delete_table_reference_by_name_if_exists.assert_not_called() + client.delete_table_reference_by_id_if_exists.assert_not_called() @patch(f"{MODULE}.get_client") def test_delete_reference_not_supported_by_server(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.side_effect = _api_error(HTTPStatus.NOT_FOUND) + client.list_table_references.side_effect = _api_error(HTTPStatus.NOT_FOUND) result = runner.invoke(app, ["table-references", "delete", "customer_identities", "--yes"]) @@ -661,8 +693,8 @@ def test_delete_reference_not_supported_by_server(mock_get_client: MagicMock, ru def test_delete_reference_non_404_error_surfaces_cleanly(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() mock_get_client.return_value = client - client.get_table_reference_by_name.return_value = _reference(id="ref-1") - client.delete_table_reference_by_name_if_exists.side_effect = _api_error(HTTPStatus.CONFLICT, "referenced by a run") + client.list_table_references.return_value = [_reference(id="ref-1")] + client.delete_table_reference_by_id_if_exists.side_effect = _api_error(HTTPStatus.CONFLICT, "referenced by a run") result = runner.invoke(app, ["table-references", "delete", "customer_identities", "--yes"]) diff --git a/tests/conftest.py b/tests/conftest.py index f6ad2f5..b19690f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,10 +1,12 @@ from __future__ import annotations +from datetime import UTC, datetime from types import SimpleNamespace from typing import Any from unittest.mock import MagicMock import pytest +from datamasque.client.models.project import Project, ProjectId from datamasque.client.models.ruleset import RulesetType from typer.testing import CliRunner @@ -31,18 +33,41 @@ def runner() -> CliRunner: @pytest.fixture() def mock_client() -> MagicMock: - """Pre-configured mock with two connections and one ruleset.""" - client = MagicMock() + """Pre-configured mock with one project, two connections and one ruleset, all in `Default`.""" + client = with_projects(MagicMock()) client.list_connections.return_value = [ - SimpleNamespace(id=1, name="my_conn", mask_type="database"), - SimpleNamespace(id=2, name="other_conn", mask_type="database"), + SimpleNamespace(id=1, name="my_conn", mask_type="database", project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id=2, name="other_conn", mask_type="database", project=DEFAULT_PROJECT_REFERENCE), ] client.list_rulesets.return_value = [ - SimpleNamespace(id=10, name="my_ruleset", ruleset_type=RulesetType.database, yaml=""), + SimpleNamespace( + id=10, name="my_ruleset", ruleset_type=RulesetType.database, yaml="", project=DEFAULT_PROJECT_REFERENCE + ), ] return client +DEFAULT_PROJECT_REFERENCE = "1-default" + + +def make_project(project_id: int = 1, name: str = "Default") -> Project: + """A project as `list_projects` returns it, with the `-` reference the server derives from its name.""" + stamp = datetime(2026, 1, 1, tzinfo=UTC) + return Project( + id=ProjectId(project_id), + reference=f"{project_id}-{name.lower()}", + name=name, + created=stamp, + updated=stamp, + ) + + +def with_projects(client: MagicMock, *projects: Project) -> MagicMock: + """Make `client.list_projects` return `projects`, or just `Default` when none are given.""" + client.list_projects.return_value = list(projects) or [make_project()] + return client + + def make_api_response(data: Any, *, is_ok: bool = True) -> MagicMock: resp = MagicMock() resp.json.return_value = data diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 7e6a7f8..4b81a36 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -8,8 +8,10 @@ from pathlib import Path import pytest +from datamasque.client.models.project import ProjectCreateRequest from typer.testing import CliRunner +from datamasque_cli.client import get_client from datamasque_cli.errors import ErrorEnvelope from datamasque_cli.main import app @@ -186,26 +188,42 @@ def db_yaml(tmp_path: Path) -> Path: return path -DISCOVERY_TEST_NAMESPACE = "dm_int_ns" +def create_discovery_config( + runner: CliRunner, name: str, config_type: str, yaml_file: Path, project: str | None = None +) -> None: + """Create a discovery config, in `project` when given, and fail the test when the CLI rejects it.""" + args = ["discover", "configs", "create", "--name", name, "--type", config_type, "-f", str(yaml_file)] + if project: + args += ["--project", project] + result = runner.invoke(app, args) + assert result.exit_code == 0, f"could not create {config_type} config '{name}': {result.stdout}{result.stderr}" -def create_discovery_config(runner: CliRunner, name: str, config_type: str, yaml_file: Path) -> None: - """Create a discovery config, and fail the test when the CLI rejects it.""" - result = runner.invoke( - app, - ["discover", "configs", "create", "--name", name, "--type", config_type, "-f", str(yaml_file)], - ) - assert result.exit_code == 0, f"could not create {config_type} config '{name}': {result.stdout}{result.stderr}" +def create_discovery_config_library(runner: CliRunner, name: str, yaml_file: Path, project: str | None = None) -> None: + """Create a discovery config library, in `project` when given, and fail the test when the CLI rejects it.""" + args = ["discover", "libraries", "create", "--name", name, "-f", str(yaml_file)] + if project: + args += ["--project", project] + result = runner.invoke(app, args) + label = f"{project}/{name}" if project else name + assert result.exit_code == 0, f"could not create library '{label}': {result.stdout}{result.stderr}" -def create_discovery_config_library(runner: CliRunner, name: str, yaml_file: Path, namespace: str = "") -> None: - """Create a discovery config library, and fail the test when the CLI rejects it.""" - result = runner.invoke( - app, - ["discover", "libraries", "create", "--name", name, "--namespace", namespace, "-f", str(yaml_file)], +@pytest.fixture() +def second_project() -> Iterator[str]: + """ + A second project for the duration of one test, deleted afterwards into the lowest-id project. + + While it exists, a create that names no project fails, so the test passes `--project` on every create. + """ + client = get_client() + project = client.create_project(ProjectCreateRequest(name=f"dm_int_{uuid.uuid4().hex[:8]}")) + yield project.name + home = min( + (p for p in client.list_projects() if p.id != project.id), + key=lambda p: p.id, ) - label = f"{namespace}/{name}" if namespace else name - assert result.exit_code == 0, f"could not create library '{label}': {result.stdout}{result.stderr}" + client.delete_project(project, home) @pytest.fixture() @@ -220,11 +238,7 @@ def discovery_config_name(runner: CliRunner) -> Iterator[str]: def discovery_library_name(runner: CliRunner) -> Iterator[str]: name = f"dm_int_{uuid.uuid4().hex[:8]}" yield name - for namespace in ("", DISCOVERY_TEST_NAMESPACE): - args = ["discover", "libraries", "delete", name, "--yes", "--force"] - if namespace: - args += ["--namespace", namespace] - runner.invoke(app, args) + runner.invoke(app, ["discover", "libraries", "delete", name, "--yes", "--force"]) @pytest.fixture() diff --git a/tests/integration/test_discovery_configs.py b/tests/integration/test_discovery_configs.py index 291a4ed..e5cfc98 100644 --- a/tests/integration/test_discovery_configs.py +++ b/tests/integration/test_discovery_configs.py @@ -9,7 +9,6 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app from tests.integration.conftest import ( - DISCOVERY_TEST_NAMESPACE, create_discovery_config, create_discovery_config_library, get_error_envelope_from_stderr, @@ -123,22 +122,25 @@ def test_library_create_get_delete_lifecycle( assert gone.exit_code == ExitCode.NOT_FOUND -def test_library_namespace_is_isolated( +def test_library_project_is_isolated( runner: CliRunner, discovery_library_name: str, + second_project: str, discovery_library_yaml: Path, ) -> None: - create_discovery_config_library( - runner, discovery_library_name, discovery_library_yaml, namespace=DISCOVERY_TEST_NAMESPACE - ) + create_discovery_config_library(runner, discovery_library_name, discovery_library_yaml, project=second_project) - in_namespace = runner.invoke( - app, ["discover", "libraries", "get", discovery_library_name, "--namespace", DISCOVERY_TEST_NAMESPACE] + in_project = runner.invoke( + app, ["discover", "libraries", "get", discovery_library_name, "--project", second_project] ) - assert in_namespace.exit_code == 0 + assert in_project.exit_code == 0 - default_namespace = runner.invoke(app, ["discover", "libraries", "get", discovery_library_name]) - assert default_namespace.exit_code == ExitCode.NOT_FOUND + other_projects = [ + row["project"] + for row in json.loads(runner.invoke(app, ["discover", "libraries", "list", "--json"]).stdout) + if row["name"] == discovery_library_name + ] + assert other_projects == [second_project] def test_library_validate_rejects_invalid_yaml( @@ -158,6 +160,7 @@ def test_library_delete_refuses_while_imported_then_force_succeeds( runner: CliRunner, discovery_library_name: str, discovery_config_name: str, + second_project: str, tmp_path: Path, ) -> None: library = tmp_path / "importable.yaml" @@ -173,9 +176,9 @@ def test_library_delete_refuses_while_imported_then_force_succeeds( " type: regex\n" " pattern: dm_int_column\n" ) - create_discovery_config_library(runner, discovery_library_name, library, namespace=DISCOVERY_TEST_NAMESPACE) + create_discovery_config_library(runner, discovery_library_name, library, project=second_project) - ref = f"{DISCOVERY_TEST_NAMESPACE}/{discovery_library_name}" + ref = f"{second_project}/{discovery_library_name}" config = tmp_path / "importing.yaml" config.write_text( f"imports:\n" @@ -189,15 +192,15 @@ def test_library_delete_refuses_while_imported_then_force_succeeds( f" include:\n" f' - "*.csv"\n' ) - create_discovery_config(runner, discovery_config_name, "file", config) + create_discovery_config(runner, discovery_config_name, "file", config, project=second_project) delete = [ "discover", "libraries", "delete", discovery_library_name, - "--namespace", - DISCOVERY_TEST_NAMESPACE, + "--project", + second_project, "--yes", ] diff --git a/tests/integration/test_rulesets.py b/tests/integration/test_rulesets.py index e087902..520a268 100644 --- a/tests/integration/test_rulesets.py +++ b/tests/integration/test_rulesets.py @@ -49,7 +49,7 @@ def test_create_without_type_aborts_when_name_is_ambiguous( assert "Multiple rulesets" in result.stderr -def test_create_with_type_updates_only_matching_namespace( +def test_create_with_type_updates_only_the_ruleset_of_that_type( runner: CliRunner, ruleset_name: str, file_yaml: Path, @@ -70,7 +70,7 @@ def test_create_with_type_updates_only_matching_namespace( assert "mask_table" in db_after.stdout -def test_delete_with_type_leaves_other_namespace_intact( +def test_delete_with_type_leaves_the_other_types_ruleset( runner: CliRunner, ruleset_name: str, file_yaml: Path, diff --git a/tests/test_projects.py b/tests/test_projects.py new file mode 100644 index 0000000..499a53e --- /dev/null +++ b/tests/test_projects.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +from datamasque.client.models.project import Project + +from datamasque_cli.errors import ExitCode +from datamasque_cli.projects import ( + in_project, + project_label, + project_names, + require_single_or_abort, + resolve_create_project, + resolve_project, + resolve_target_project, +) +from tests.conftest import make_project, with_projects + +DEFAULT = make_project(1, "Default") +FINANCE = make_project(2, "Finance") + + +def _client(*projects: Project) -> MagicMock: + return with_projects(MagicMock(), *projects) + + +@pytest.mark.parametrize("name_or_id", ["Finance", "finance", "FINANCE", "2"]) +def test_resolve_project_by_name_ignoring_case_or_by_id(name_or_id: str) -> None: + assert resolve_project(_client(DEFAULT, FINANCE), name_or_id) == FINANCE + + +def test_resolve_project_prefers_a_name_over_an_equal_id() -> None: + """A project named `1` wins over the project with id 1, as names are tried first.""" + named_one = make_project(5, "1") + + assert resolve_project(_client(DEFAULT, named_one), "1") == named_one + + +def test_resolve_project_unknown_is_not_found() -> None: + with pytest.raises(SystemExit) as raised: + resolve_project(_client(DEFAULT), "Finance") + + assert raised.value.code == ExitCode.NOT_FOUND + + +def test_resolve_target_project_uses_the_only_project_when_none_is_given() -> None: + assert resolve_target_project(_client(DEFAULT), None) == DEFAULT + + +def test_resolve_target_project_needs_a_project_once_there_are_two() -> None: + with pytest.raises(SystemExit) as raised: + resolve_target_project(_client(DEFAULT, FINANCE), None) + + assert raised.value.code == ExitCode.AMBIGUOUS + + +def test_project_names_include_archived_projects() -> None: + client = _client(DEFAULT, FINANCE) + + assert project_names(client) == {"1-default": "Default", "2-finance": "Finance"} + client.list_projects.assert_called_once_with(include_archived=True) + + +def test_project_label_names_the_project_and_leaves_a_built_in_blank() -> None: + names = {"2-finance": "Finance"} + + assert project_label(names, "2-finance") == "Finance" + assert project_label(names, None) == "" + + +def test_in_project_keeps_only_that_projects_items() -> None: + items = [SimpleNamespace(project="1-default"), SimpleNamespace(project="2-finance")] + + assert in_project(items, FINANCE) == [items[1]] + assert in_project(items, None) == items + + +def test_require_single_returns_the_only_match() -> None: + match = SimpleNamespace(project="1-default") + + assert require_single_or_abort(_client(DEFAULT), [match], "Ruleset 'r'") is match + + +def test_require_single_with_no_match_is_not_found() -> None: + with pytest.raises(SystemExit) as raised: + require_single_or_abort(_client(DEFAULT), [], "Ruleset 'r'") + + assert raised.value.code == ExitCode.NOT_FOUND + + +def test_require_single_with_a_match_in_two_projects_is_ambiguous(capsys: pytest.CaptureFixture[str]) -> None: + matches = [SimpleNamespace(project="1-default"), SimpleNamespace(project="2-finance")] + + with pytest.raises(SystemExit) as raised: + require_single_or_abort(_client(DEFAULT, FINANCE), matches, "Ruleset 'r'") + + assert raised.value.code == ExitCode.AMBIGUOUS + assert capsys.readouterr().err == ( + "Error: Ruleset 'r' exists in more than one project:\n" + " project=Default\n" + " project=Finance\n" + "Hint: Pass --project to disambiguate.\n" + ) + + +def test_resolve_create_project_prefers_the_named_project() -> None: + existing = [SimpleNamespace(project="1-default")] + + assert resolve_create_project(_client(DEFAULT, FINANCE), "Finance", existing) == "2-finance" + + +def test_resolve_create_project_updates_where_the_name_already_is() -> None: + """An update needs no `--project` when only one project has the name, even on a multi-project instance.""" + existing = [SimpleNamespace(project="2-finance"), SimpleNamespace(project="2-finance")] + + assert resolve_create_project(_client(DEFAULT, FINANCE), None, existing) == "2-finance" + + +def test_resolve_create_project_with_the_name_in_two_projects_is_ambiguous() -> None: + existing = [SimpleNamespace(project="1-default"), SimpleNamespace(project="2-finance")] + + with pytest.raises(SystemExit) as raised: + resolve_create_project(_client(DEFAULT, FINANCE), None, existing) + + assert raised.value.code == ExitCode.AMBIGUOUS + + +def test_resolve_create_project_for_a_new_name_uses_the_only_project() -> None: + assert resolve_create_project(_client(DEFAULT), None, []) == "1-default" From 4c0a0d44d86cd82f7db6a968eb64df1c3ae97023 Mon Sep 17 00:00:00 2001 From: jiatolentinoDM Date: Wed, 28 Oct 2026 09:24:46 +0800 Subject: [PATCH 03/11] feat!: export and import bundles through v2 with --fallback-project `dm rulesets export-bundle` and `import-bundle` call the v2 endpoints, so a bundle files each item under its project and an import puts it back there. `import-bundle --fallback-project` names the project, by name or id, for the items a bundle files under no project, and the command warns when the server marks the bundle as the older format. BREAKING CHANGE: the bundle commands need a server with the v2 export and import endpoints. --- README.md | 3 +- src/datamasque_cli/commands/rulesets.py | 41 ++++++++++++----- src/datamasque_cli/commands/system.py | 1 + tests/commands/test_rulesets.py | 61 ++++++++++++++++++++++++- 4 files changed, 91 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 3363b0b..47acb81 100644 --- a/README.md +++ b/README.md @@ -170,9 +170,10 @@ dm rulesets generate --file request.json # Generate from schema dm rulesets generate --file req.json -o out.yaml # Generate to file dm rulesets validate --file rules.yaml --type database|file # Validate against server (YAML under 60 KiB) dm rulesets status # Validation status; poll after creating YAML of 60 KiB+ -dm rulesets export-bundle -o bundle.zip # Export rulesets + libraries + seeds +dm rulesets export-bundle -o bundle.zip # Export rulesets + libraries + seeds, by project dm rulesets import-bundle --file bundle.zip # Import a previously exported bundle dm rulesets import-bundle -f bundle.zip --overwrite-rulesets --overwrite-libraries # Replace existing entries +dm rulesets import-bundle -f bundle.zip --fallback-project # Project for items filed under none ``` ### Ruleset libraries diff --git a/src/datamasque_cli/commands/rulesets.py b/src/datamasque_cli/commands/rulesets.py index 838c14f..b291a29 100644 --- a/src/datamasque_cli/commands/rulesets.py +++ b/src/datamasque_cli/commands/rulesets.py @@ -38,6 +38,7 @@ project_names, resolve_create_project, resolve_optional_project, + resolve_project, resolve_target_project, ) @@ -283,11 +284,11 @@ def export_bundle( """Export rulesets, ruleset libraries, and any referenced seed files as a ZIP bundle. Bundles only rulesets + libraries + optional seed files — not connections, - users, licences, or instance settings. + users, licences, or instance settings. Each item is filed under its project. """ client = get_client(profile) # `export_configuration` is not yet wrapped in datamasque-python; hit the endpoint directly. - response = client.make_request("GET", "/api/export/v1/") + response = client.make_request("GET", "/api/export/v2/") write_bytes_or_abort(output_path, response.content) print_success(f"Bundle exported to {output_path}") @@ -304,31 +305,43 @@ def import_bundle( overwrite_seeds: bool = typer.Option( False, "--overwrite-seeds", help="Overwrite seed files that already exist with the same name" ), + fallback_project: str | None = typer.Option( + None, + "--fallback-project", + help="Project name or id for the items the bundle files under no project. " + "Defaults to the server's default project.", + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Import rulesets, ruleset libraries, and seed files from a ZIP bundle. Bundle must have been produced by `dm rulesets export-bundle` or the - server's `/api/export/v1/` endpoint. By default, duplicates are skipped; - pass `--overwrite-*` flags to replace existing entries. + server's export endpoint. Each item goes into the project the bundle files it + under; items under no project, such as those in an older bundle, go into + `--fallback-project`. By default, duplicates are skipped; pass `--overwrite-*` + flags to replace existing entries. """ if not is_confirmed: confirm_or_abort("This will modify rulesets, libraries, and seed files. Continue?") client = get_client(profile) - # `/api/import/v1/` expects a multipart `zip_archive` upload plus three - # optional boolean overwrite flags; `import_configuration` is not yet + data = { + "overwrite_rulesets": str(overwrite_rulesets).lower(), + "overwrite_libraries": str(overwrite_libraries).lower(), + "overwrite_seed_files": str(overwrite_seeds).lower(), + } + if fallback_project is not None: + data["fallback_project"] = str(resolve_project(client, fallback_project).id) + + # `/api/import/v2/` expects a multipart `zip_archive` upload plus the overwrite + # flags and an optional `fallback_project`; `import_configuration` is not yet # wrapped in datamasque-python, so we call `make_request` directly. with file.open("rb") as zip_content: response = client.make_request( "POST", - "/api/import/v1/", - data={ - "overwrite_rulesets": str(overwrite_rulesets).lower(), - "overwrite_libraries": str(overwrite_libraries).lower(), - "overwrite_seed_files": str(overwrite_seeds).lower(), - }, + "/api/import/v2/", + data=data, files=[ UploadFile( field_name="zip_archive", @@ -340,6 +353,10 @@ def import_bundle( ) print_success("Bundle imported successfully.") + if response.headers.get("Deprecation") == "true": + print_warning( + "This bundle is in the older format. Items it files under no project went into the fallback project." + ) if response.content: try: summary = response.json() diff --git a/src/datamasque_cli/commands/system.py b/src/datamasque_cli/commands/system.py index 5eb527c..8b0b058 100644 --- a/src/datamasque_cli/commands/system.py +++ b/src/datamasque_cli/commands/system.py @@ -94,6 +94,7 @@ def import_config( overwrite_rulesets=False, overwrite_libraries=False, overwrite_seeds=False, + fallback_project=None, profile=profile, is_confirmed=is_confirmed, ) diff --git a/tests/commands/test_rulesets.py b/tests/commands/test_rulesets.py index 10d24ea..90d18d5 100644 --- a/tests/commands/test_rulesets.py +++ b/tests/commands/test_rulesets.py @@ -425,7 +425,7 @@ def test_export_bundle_writes_binary_zip(mock_get_client: MagicMock, runner: Cli assert result.exit_code == 0 assert output.read_bytes() == b"PK\x03\x04fake-zip-bytes" - client.make_request.assert_called_once_with("GET", "/api/export/v1/") + client.make_request.assert_called_once_with("GET", "/api/export/v2/") @patch(f"{MODULE}.get_client") @@ -469,7 +469,7 @@ def test_import_bundle_uploads_zip_archive_as_multipart( assert result.exit_code == 0 (call,) = client.make_request.call_args_list - assert call.args == ("POST", "/api/import/v1/") + assert call.args == ("POST", "/api/import/v2/") assert call.kwargs["data"] == { "overwrite_rulesets": "true", "overwrite_libraries": "false", @@ -481,6 +481,63 @@ def test_import_bundle_uploads_zip_archive_as_multipart( assert upload.content_type == "application/zip" +@patch(f"{MODULE}.get_client") +def test_import_bundle_sends_the_fallback_project_id( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = with_projects(MagicMock(), make_project(), make_project(project_id=7, name="Bank")) + mock_get_client.return_value = client + client.make_request.return_value = MagicMock(content=b"", headers={}) + + bundle = tmp_path / "bundle.zip" + bundle.write_bytes(b"PK\x03\x04") + + result = runner.invoke( + app, ["rulesets", "import-bundle", "--file", str(bundle), "--fallback-project", "bank", "--yes"] + ) + + assert result.exit_code == 0 + (call,) = client.make_request.call_args_list + assert call.kwargs["data"]["fallback_project"] == "7" + + +@patch(f"{MODULE}.get_client") +def test_import_bundle_rejects_an_unknown_fallback_project( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = with_projects(MagicMock()) + mock_get_client.return_value = client + + bundle = tmp_path / "bundle.zip" + bundle.write_bytes(b"PK\x03\x04") + + result = runner.invoke( + app, ["rulesets", "import-bundle", "--file", str(bundle), "--fallback-project", "nope", "--yes"] + ) + + assert result.exit_code == ExitCode.NOT_FOUND + client.make_request.assert_not_called() + + +@patch(f"{MODULE}.get_client") +def test_import_bundle_warns_about_an_older_bundle( + mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path +) -> None: + client = with_projects(MagicMock()) + mock_get_client.return_value = client + client.make_request.return_value = MagicMock(content=b"", headers={"Deprecation": "true"}) + + bundle = tmp_path / "bundle.zip" + bundle.write_bytes(b"PK\x03\x04") + + result = runner.invoke(app, ["rulesets", "import-bundle", "--file", str(bundle), "--yes"]) + + assert result.exit_code == 0 + assert "older format" in result.output + (call,) = client.make_request.call_args_list + assert "fallback_project" not in call.kwargs["data"] + + @patch(f"{MODULE}.get_client") def test_system_export_alias_warns_and_delegates(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: client = with_projects(MagicMock()) From b35d78dfe9dc9f807f6669e2b753fa43227029a4 Mon Sep 17 00:00:00 2001 From: jiatolentinoDM Date: Fri, 30 Oct 2026 06:20:04 +0800 Subject: [PATCH 04/11] fix(table-references): look up --connection in the reference's own project first Without --project, a connection name that several projects share now resolves to the one in the reference's project instead of aborting as ambiguous. A connection in another project is still found. Also drop the repeated listing request before a create. --- .../commands/table_references.py | 31 ++++---- tests/commands/test_table_references.py | 70 ++++++++++++++++++- 2 files changed, 87 insertions(+), 14 deletions(-) diff --git a/src/datamasque_cli/commands/table_references.py b/src/datamasque_cli/commands/table_references.py index e61b948..6b185d0 100644 --- a/src/datamasque_cli/commands/table_references.py +++ b/src/datamasque_cli/commands/table_references.py @@ -131,8 +131,19 @@ def get_reference( render_output(data, is_json=is_json, title=f"Table Reference: {name}") -def _resolve_connection_id(client: DataMasqueClient, name_or_id: str, project: str | None) -> ConnectionId: - """Resolve a `--connection` value (name or ID), narrowed by `--project`, to a connection ID.""" +def _resolve_connection_id( + client: DataMasqueClient, name_or_id: str, project: str | None, reference_project: str | None +) -> ConnectionId: + """ + Resolve a `--connection` value (name or ID), narrowed by `--project`, to a connection ID. + + Without `--project`, a connection of that name in the reference's own project is used, + so a name that other projects share needs no `--project`. Otherwise every project is searched. + """ + if project is None: + own = [c for c in client.list_connections() if c.name == name_or_id and c.project == reference_project] + if own: + return own[0].id return resolve_connection(client, name_or_id, project).id @@ -211,12 +222,13 @@ def create_reference( overrides = _option_overrides(file_format, delimiter, encoding, quotechar, null_string) existing = [ref for ref in _list_or_abort(client) if ref.name == name] + reference_project = resolve_create_project(client, project, existing) reference = TableReference( name=name, - connection=_resolve_connection_id(client, connection, project), + connection=_resolve_connection_id(client, connection, project, reference_project), source=source, options=TableReferenceOptions(**overrides) if overrides else None, - project=resolve_create_project(client, project, existing), + project=reference_project, ) _create_or_update(client, reference) print_success(f"Table reference '{name}' created/updated.") @@ -232,14 +244,7 @@ def _create_from_file(client: DataMasqueClient, file: Path, project: str | None) def _create_or_update(client: DataMasqueClient, reference: TableReference) -> None: - """Create or update `reference`, distinguishing an unsupported server from any other failure. - - `create_or_update_table_reference` itself makes two requests (a GET to look up an existing - reference by name, then a POST or PUT), so probe support with `_list_or_abort` first and let - a 404 from the create/update call surface as a plain API error instead of being misread as - "not supported". - """ - _list_or_abort(client) + """Create or update `reference`.""" try: client.create_or_update_table_reference(reference) except DataMasqueApiError as exc: @@ -270,7 +275,7 @@ def update_reference( reference = _get_or_abort(client, name, project) if connection is not None: - reference.connection = _resolve_connection_id(client, connection, project) + reference.connection = _resolve_connection_id(client, connection, project, reference.project) if source is not None: reference.source = source if overrides: diff --git a/tests/commands/test_table_references.py b/tests/commands/test_table_references.py index 998397f..c41a4a6 100644 --- a/tests/commands/test_table_references.py +++ b/tests/commands/test_table_references.py @@ -13,7 +13,7 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.main import app -from tests.conftest import DEFAULT_PROJECT_REFERENCE, with_projects +from tests.conftest import DEFAULT_PROJECT_REFERENCE, make_project, with_projects MODULE = "datamasque_cli.commands.table_references" @@ -571,6 +571,74 @@ def test_update_reference_connection_by_name(mock_get_client: MagicMock, runner: assert updated.connection == "conn-2" +def _shared_connection_names(client: MagicMock) -> None: + """Give `Default` and `Finance` a connection each named `input`, and only `Finance` one named `archive`.""" + with_projects(client, make_project(1, "Default"), make_project(2, "Finance")) + client.list_connections.return_value = [ + SimpleNamespace(id="conn-default", name="input", project=DEFAULT_PROJECT_REFERENCE), + SimpleNamespace(id="conn-finance", name="input", project="2-finance"), + SimpleNamespace(id="conn-archive", name="archive", project="2-finance"), + ] + + +@patch(f"{MODULE}.get_client") +def test_update_reference_connection_prefers_the_references_own_project( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _mock_client() + mock_get_client.return_value = client + _shared_connection_names(client) + client.list_table_references.return_value = [_reference(id="ref-1", project="2-finance")] + + for connection, expected in (("input", "conn-finance"), ("archive", "conn-archive")): + result = runner.invoke(app, ["table-references", "update", "customer_identities", "--connection", connection]) + + assert result.exit_code == 0, result.output + assert client.update_table_reference.call_args[0][0].connection == expected + + +@patch(f"{MODULE}.get_client") +def test_update_reference_connection_in_another_project_only_is_found( + mock_get_client: MagicMock, runner: CliRunner +) -> None: + client = _mock_client() + mock_get_client.return_value = client + _shared_connection_names(client) + client.list_table_references.return_value = [_reference(id="ref-1")] + + result = runner.invoke(app, ["table-references", "update", "customer_identities", "--connection", "archive"]) + + assert result.exit_code == 0, result.output + assert client.update_table_reference.call_args[0][0].connection == "conn-archive" + + +@patch(f"{MODULE}.get_client") +def test_create_reference_connection_prefers_the_target_project(mock_get_client: MagicMock, runner: CliRunner) -> None: + """An update through `create` with no `--project` targets the existing reference's project, and so its connection.""" + client = _mock_client() + mock_get_client.return_value = client + _shared_connection_names(client) + client.list_table_references.return_value = [_reference(id="ref-1", project="2-finance")] + + result = runner.invoke( + app, + [ + "table-references", + "create", + "--name", + "customer_identities", + "--connection", + "input", + "--source", + "in/customers.csv", + ], + ) + + assert result.exit_code == 0, result.output + created = client.create_or_update_table_reference.call_args[0][0] + assert (created.connection, created.project) == ("conn-finance", "2-finance") + + @patch(f"{MODULE}.get_client") def test_update_reference_unknown_connection_aborts(mock_get_client: MagicMock, runner: CliRunner) -> None: client = _mock_client() From b5ef01fd8d1692faf6951cde1fd6266986d9c989 Mon Sep 17 00:00:00 2001 From: jiatolentinoDM Date: Mon, 2 Nov 2026 12:13:34 +0800 Subject: [PATCH 05/11] feat: add dm projects `dm projects` lists, shows, creates, renames and deletes projects. `list --include-deleted` adds deleted projects. Delete takes `--to`, the project that receives the deleted project's resources, and `--check` lists what would stop the delete without deleting. `dm projects update` needs a datamasque-python release with `update_project`. --- README.md | 15 ++ .../skills/datamasque-cli/SKILL.md | 2 + src/datamasque_cli/commands/projects.py | 137 +++++++++++++ src/datamasque_cli/main.py | 2 + src/datamasque_cli/projects.py | 10 +- tests/commands/test_projects.py | 185 ++++++++++++++++++ 6 files changed, 348 insertions(+), 3 deletions(-) create mode 100644 src/datamasque_cli/commands/projects.py create mode 100644 tests/commands/test_projects.py diff --git a/README.md b/README.md index 47acb81..9da5748 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,21 @@ dm table-references update --delimiter ';' --null-string NULL # Any CS dm table-references delete # Delete a table reference ``` +### Projects + +```console +dm projects list # id, name, description, created +dm projects list --include-deleted # Adds deleted projects, with a deleted column +dm projects get # Show a project's details +dm projects create --name --description "" +dm projects update --name # Rename; --description changes the description +dm projects delete --to # Move every resource to the --to project, then delete +dm projects delete --to --check # Only list what would stop the delete +``` + +Creating, renaming and deleting projects needs an admin user. +Renaming makes rulesets and configurations that import one of the project's libraries by the old project name invalid. + ### In-flight masking The IFM service runs alongside the admin server, diff --git a/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md b/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md index 13b4daf..590d7a6 100644 --- a/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md +++ b/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md @@ -68,6 +68,8 @@ Pass repeated `--options key=value` for server-side knobs `--project` goes into the instance's only project, and fails with `ambiguous` when there are several. A get or delete fails with `ambiguous` when the name exists in two projects; pass `--project` to pick one. + `dm projects` creates, renames and deletes projects (delete needs `--to`, the + project that takes its resources). - **File masking needs a destination.** Database masking is in-place; file masking writes through to a destination connection and fails diff --git a/src/datamasque_cli/commands/projects.py b/src/datamasque_cli/commands/projects.py new file mode 100644 index 0000000..250d244 --- /dev/null +++ b/src/datamasque_cli/commands/projects.py @@ -0,0 +1,137 @@ +"""Project management commands.""" + +from __future__ import annotations + +import typer +from datamasque.client.exceptions import DataMasqueApiError, ProjectDeleteConflictError +from datamasque.client.models.project import Project, ProjectCreateRequest, ProjectUpdateRequest + +from datamasque_cli.client import get_client +from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort +from datamasque_cli.output import print_success, render_output +from datamasque_cli.projects import PROJECT_OPTION_HELP, get_named_project, resolve_project + +app = typer.Typer(help="Manage projects.", no_args_is_help=True) + +DELETE_CONFLICT_MESSAGE = "The project's resources cannot move to the destination project" + + +def _build_project_row(project: Project) -> dict[str, object]: + return { + "id": project.id, + "name": project.name, + "description": project.description, + "created": project.created, + } + + +@app.command("list") +def list_projects( + is_deleted_included: bool = typer.Option(False, "--include-deleted", help="Also list deleted projects"), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), + is_json: bool = typer.Option(False, "--json", help="Output as JSON"), +) -> None: + """List the active projects, or every project with --include-deleted.""" + client = get_client(profile) + columns = ["id", "name", "description", "created"] + if not is_deleted_included: + data = [_build_project_row(project) for project in client.list_projects()] + render_output(data, is_json=is_json, columns=columns, title="Projects") + return + + active_ids = {project.id for project in client.list_projects()} + data = [ + {**_build_project_row(project), "deleted": project.id not in active_ids} + for project in client.list_projects(include_archived=True) + ] + render_output(data, is_json=is_json, columns=[*columns, "deleted"], title="Projects") + + +@app.command("get") +def get_project( + project: str = typer.Argument(help=PROJECT_OPTION_HELP), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), + is_json: bool = typer.Option(False, "--json", help="Output as JSON"), +) -> None: + """Show a project's details.""" + client = get_client(profile) + found = resolve_project(client, project) + data = {**_build_project_row(found), "updated": found.updated} + render_output(data, is_json=is_json, title=f"Project: {found.name}") + + +@app.command("create") +def create_project( + name: str = typer.Option(..., help="Project name"), + description: str = typer.Option("", help="Project description"), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), +) -> None: + """Create a project.""" + client = get_client(profile) + try: + created = client.create_project(ProjectCreateRequest(name=name, description=description)) + except DataMasqueApiError as exc: + abort_api_error(f"Failed to create project '{name}'", exc) + print_success(f"Project '{created.name}' created (id {created.id}).") + + +@app.command("update") +def update_project( + project: str = typer.Argument(help=PROJECT_OPTION_HELP), + new_name: str | None = typer.Option(None, "--name", help="New project name"), + description: str | None = typer.Option(None, help="New project description"), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), +) -> None: + """ + Rename a project or change its description. + + Renaming moves the project's seed and credential files. + Rulesets and configurations that import one of its libraries by the old project name become invalid, + and seed and table references that name the old project are not changed. + """ + if new_name is None and description is None: + abort("Nothing to update.", code=ErrorCode.INVALID_INPUT, hint="Pass --name, --description or both.") + + client = get_client(profile) + found = resolve_project(client, project) + try: + updated = client.update_project(found, ProjectUpdateRequest(name=new_name, description=description)) + except DataMasqueApiError as exc: + abort_api_error(f"Failed to update project '{found.name}'", exc) + print_success(f"Project '{updated.name}' updated.") + + +@app.command("delete") +def delete_project( + project: str = typer.Argument(help=PROJECT_OPTION_HELP), + destination: str = typer.Option(..., "--to", help="Project to move the resources to: name or id"), + is_check_only: bool = typer.Option(False, "--check", help="Only list what would stop the delete"), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), + is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), +) -> None: + """Delete a project, after moving all of its resources to another project.""" + client = get_client(profile) + projects = client.list_projects() + found = get_named_project(projects, project) + target = get_named_project(projects, destination) + + if is_check_only: + try: + conflicts = client.get_project_delete_conflicts(found, target) + except DataMasqueApiError as exc: + abort_api_error(f"Failed to check project '{found.name}'", exc) + if conflicts: + abort(DELETE_CONFLICT_MESSAGE, code=ErrorCode.CONFLICT, details=[c.detail for c in conflicts]) + print_success(f"Project '{found.name}' can be deleted, moving its resources to '{target.name}'.") + return + + if not is_confirmed: + confirm_or_abort(f"Delete project '{found.name}' and move its resources to '{target.name}'?") + + try: + client.delete_project(found, target) + except ProjectDeleteConflictError as exc: + abort(DELETE_CONFLICT_MESSAGE, code=ErrorCode.CONFLICT, details=[c.detail for c in exc.conflicts]) + except DataMasqueApiError as exc: + abort_api_error(f"Failed to delete project '{found.name}'", exc) + print_success(f"Project '{found.name}' deleted; its resources moved to '{target.name}'.") diff --git a/src/datamasque_cli/main.py b/src/datamasque_cli/main.py index 3545039..8df520f 100644 --- a/src/datamasque_cli/main.py +++ b/src/datamasque_cli/main.py @@ -27,6 +27,7 @@ discovery, files, ifm, + projects, ruleset_libraries, rulesets, runs, @@ -65,6 +66,7 @@ app.add_typer(ruleset_libraries.app, name="libraries") app.add_typer(ifm.app, name="ifm") app.add_typer(table_references.app, name="table-references") +app.add_typer(projects.app, name="projects") @app.command() diff --git a/src/datamasque_cli/projects.py b/src/datamasque_cli/projects.py index 2eb5a55..658e350 100644 --- a/src/datamasque_cli/projects.py +++ b/src/datamasque_cli/projects.py @@ -23,9 +23,8 @@ def project(self) -> str | None: ... ScopedT = TypeVar("ScopedT", bound=ProjectScoped) -def resolve_project(client: DataMasqueClient, name_or_id: str) -> Project: - """Return the active project named `name_or_id`, ignoring case, or with that numeric id.""" - projects = client.list_projects() +def get_named_project(projects: Sequence[Project], name_or_id: str) -> Project: + """Return the project in `projects` named `name_or_id`, ignoring case, or with that numeric id.""" match = next((p for p in projects if p.name.casefold() == name_or_id.casefold()), None) if match is None and name_or_id.isdigit(): match = next((p for p in projects if p.id == int(name_or_id)), None) @@ -34,6 +33,11 @@ def resolve_project(client: DataMasqueClient, name_or_id: str) -> Project: return match +def resolve_project(client: DataMasqueClient, name_or_id: str) -> Project: + """Return the active project named `name_or_id`, ignoring case, or with that numeric id.""" + return get_named_project(client.list_projects(), name_or_id) + + def resolve_optional_project(client: DataMasqueClient, name_or_id: str | None) -> Project | None: """Return the project `name_or_id` names, or `None` when no `--project` was given.""" return None if name_or_id is None else resolve_project(client, name_or_id) diff --git a/tests/commands/test_projects.py b/tests/commands/test_projects.py new file mode 100644 index 0000000..c8fd523 --- /dev/null +++ b/tests/commands/test_projects.py @@ -0,0 +1,185 @@ +from __future__ import annotations + +import json +from collections.abc import Iterator +from http import HTTPStatus +from unittest.mock import MagicMock, patch + +import pytest +from datamasque.client.exceptions import DataMasqueApiError, ProjectDeleteConflictError +from datamasque.client.models.project import ( + ProjectCreateRequest, + ProjectDeleteConflict, + ProjectDeleteConflictReason, + ProjectUpdateRequest, +) +from typer.testing import CliRunner + +from datamasque_cli.errors import ExitCode +from datamasque_cli.main import app +from tests.conftest import make_api_response, make_project, with_projects + +MODULE = "datamasque_cli.commands.projects" + +DEFAULT = make_project(1, "Default") +FINANCE = make_project(2, "Finance") +OLD = make_project(3, "Old") + +NAME_CLASH = ProjectDeleteConflict( + reason=ProjectDeleteConflictReason.name_in_use, + detail='Ruleset "customers" exists.', +) + +CONFLICT_ERROR = ( + 'Error: The project\'s resources cannot move to the destination project:\n Ruleset "customers" exists.\n' +) + + +def _api_error(status: HTTPStatus, detail: str) -> DataMasqueApiError: + response = make_api_response({"detail": detail}, is_ok=False) + response.status_code = status + return DataMasqueApiError(detail, response=response) + + +@pytest.fixture() +def client() -> Iterator[MagicMock]: + client = with_projects(MagicMock(), DEFAULT, FINANCE) + with patch(f"{MODULE}.get_client", return_value=client): + yield client + + +def test_list_shows_the_active_projects(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["projects", "list", "--json"]) + + assert result.exit_code == 0 + assert [(p["id"], p["name"]) for p in json.loads(result.stdout)] == [(1, "Default"), (2, "Finance")] + client.list_projects.assert_called_once_with() + + +def test_list_include_deleted_marks_the_deleted_projects(client: MagicMock, runner: CliRunner) -> None: + client.list_projects.side_effect = lambda include_archived=False: ( + [DEFAULT, FINANCE, OLD] if include_archived else [DEFAULT, FINANCE] + ) + + result = runner.invoke(app, ["projects", "list", "--include-deleted", "--json"]) + + assert result.exit_code == 0 + assert [(p["name"], p["deleted"]) for p in json.loads(result.stdout)] == [ + ("Default", False), + ("Finance", False), + ("Old", True), + ] + + +@pytest.mark.parametrize("given", ["finance", "2"]) +def test_get_finds_a_project_by_name_in_any_case_or_by_id(client: MagicMock, runner: CliRunner, given: str) -> None: + result = runner.invoke(app, ["projects", "get", given, "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout)["name"] == "Finance" + + +def test_get_of_an_unknown_project_is_not_found(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["projects", "get", "nope"]) + + assert result.exit_code == ExitCode.NOT_FOUND + assert result.stderr == "Error: Project 'nope' not found.\n" + + +def test_create_sends_the_name_and_description(client: MagicMock, runner: CliRunner) -> None: + client.create_project.return_value = make_project(4, "Sales") + + result = runner.invoke(app, ["projects", "create", "--name", "Sales", "--description", "Sales team"]) + + assert result.exit_code == 0 + client.create_project.assert_called_once_with(ProjectCreateRequest(name="Sales", description="Sales team")) + + +def test_create_rejected_by_the_server_shows_its_reason(client: MagicMock, runner: CliRunner) -> None: + client.create_project.side_effect = _api_error(HTTPStatus.BAD_REQUEST, "Name in use.") + + result = runner.invoke(app, ["projects", "create", "--name", "finance"]) + + assert result.exit_code == ExitCode.INVALID_INPUT + assert result.stderr == "Error: Failed to create project 'finance': Name in use.\n" + + +@pytest.mark.parametrize( + ("options", "request_sent"), + [ + (["--name", "Accounts"], ProjectUpdateRequest(name="Accounts")), + (["--description", "Accounts team"], ProjectUpdateRequest(description="Accounts team")), + ], + ids=["name", "description"], +) +def test_update_sends_only_the_fields_given( + client: MagicMock, runner: CliRunner, options: list[str], request_sent: ProjectUpdateRequest +) -> None: + client.update_project.return_value = FINANCE + + result = runner.invoke(app, ["projects", "update", "finance", *options]) + + assert result.exit_code == 0 + client.update_project.assert_called_once_with(FINANCE, request_sent) + + +def test_update_with_nothing_to_change_is_rejected_without_a_request(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["projects", "update", "finance"]) + + assert result.exit_code == ExitCode.INVALID_INPUT + assert result.stderr == "Error: Nothing to update.\nHint: Pass --name, --description or both.\n" + client.update_project.assert_not_called() + + +def test_delete_moves_the_resources_to_the_destination(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["projects", "delete", "finance", "--to", "default", "--yes"]) + + assert result.exit_code == 0 + client.delete_project.assert_called_once_with(FINANCE, DEFAULT) + client.get_project_delete_conflicts.assert_not_called() + client.list_projects.assert_called_once_with() + + +def test_delete_refused_by_a_conflict_lists_it(client: MagicMock, runner: CliRunner) -> None: + response = make_api_response({}, is_ok=False) + response.status_code = HTTPStatus.CONFLICT + client.delete_project.side_effect = ProjectDeleteConflictError( + "conflict", response=response, conflicts=[NAME_CLASH] + ) + + result = runner.invoke(app, ["projects", "delete", "finance", "--to", "default", "--yes"]) + + assert result.exit_code == ExitCode.CONFLICT + assert result.stderr == CONFLICT_ERROR + + +def test_delete_declined_at_the_prompt_deletes_nothing(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["projects", "delete", "finance", "--to", "default"], input="n\n") + + assert result.exit_code == ExitCode.CANCELLED + client.delete_project.assert_not_called() + + +@pytest.mark.parametrize( + ("conflicts", "exit_code", "stderr"), + [ + ([], 0, "Project 'Finance' can be deleted, moving its resources to 'Default'.\n"), + ([NAME_CLASH], ExitCode.CONFLICT, CONFLICT_ERROR), + ], + ids=["no-conflicts", "conflict"], +) +def test_delete_check_reports_the_conflicts_without_deleting( + client: MagicMock, + runner: CliRunner, + conflicts: list[ProjectDeleteConflict], + exit_code: int, + stderr: str, +) -> None: + client.get_project_delete_conflicts.return_value = conflicts + + result = runner.invoke(app, ["projects", "delete", "finance", "--to", "default", "--check"]) + + assert result.exit_code == exit_code + assert result.stderr == stderr + client.get_project_delete_conflicts.assert_called_once_with(FINANCE, DEFAULT) + client.delete_project.assert_not_called() From 80b0e039f380f967060ca029bdb5ea87db8eba32 Mon Sep 17 00:00:00 2001 From: jiatolentinoDM Date: Mon, 2 Nov 2026 12:13:34 +0800 Subject: [PATCH 06/11] feat: add dm resources move `dm resources move --to ` moves resources selected by `--project`, `--type`, `--search` or exact names. Resources that clash with the destination stay where they are; the command lists each one and exits with the `conflict` code. `--check` previews the move. --- README.md | 12 ++ .../skills/datamasque-cli/SKILL.md | 4 +- src/datamasque_cli/commands/resources.py | 138 ++++++++++++++++ src/datamasque_cli/main.py | 2 + tests/commands/test_resources.py | 151 ++++++++++++++++++ 5 files changed, 306 insertions(+), 1 deletion(-) create mode 100644 src/datamasque_cli/commands/resources.py create mode 100644 tests/commands/test_resources.py diff --git a/README.md b/README.md index 9da5748..7beef4c 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,18 @@ dm projects delete --to --check # Only list what woul Creating, renaming and deleting projects needs an admin user. Renaming makes rulesets and configurations that import one of the project's libraries by the old project name invalid. +### Moving resources + +```console +dm resources move --project Finance --to Archive # Every resource in Finance +dm resources move customers orders --type rulesets --to Archive # Rulesets with these exact names, from any project +dm resources move --search payroll --to HR --check # Only list the matches and what would stop them moving +``` + +Resources move with their files and runs. `--project`, `--type`, `--search` and names combine; pass at least one. +A resource that clashes with the destination (same name, or a file in the way) stays where it is, the others move, +and the command exits with the `conflict` code, listing each one that stayed. + ### In-flight masking The IFM service runs alongside the admin server, diff --git a/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md b/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md index 590d7a6..1088c14 100644 --- a/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md +++ b/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md @@ -69,7 +69,9 @@ Pass repeated `--options key=value` for server-side knobs `ambiguous` when there are several. A get or delete fails with `ambiguous` when the name exists in two projects; pass `--project` to pick one. `dm projects` creates, renames and deletes projects (delete needs `--to`, the - project that takes its resources). + project that takes its resources). `dm resources move --to ` moves + resources selected by `--project`, `--type`, `--search` or exact names; it + exits `conflict` when any stayed behind. Add `--check` to only preview. - **File masking needs a destination.** Database masking is in-place; file masking writes through to a destination connection and fails diff --git a/src/datamasque_cli/commands/resources.py b/src/datamasque_cli/commands/resources.py new file mode 100644 index 0000000..dfb9e7c --- /dev/null +++ b/src/datamasque_cli/commands/resources.py @@ -0,0 +1,138 @@ +"""Commands that act on resources of any type.""" + +from __future__ import annotations + +import typer +from datamasque.client import DataMasqueClient +from datamasque.client.exceptions import DataMasqueApiError +from datamasque.client.models.project import Project +from datamasque.client.models.resource import Resource +from datamasque.client.models.resource_type import ResourceTypeName + +from datamasque_cli.client import get_client +from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort +from datamasque_cli.output import print_success, render_output +from datamasque_cli.projects import PROJECT_OPTION_HELP, get_named_project, project_label + +app = typer.Typer(help="Work with resources of every type.", no_args_is_help=True) + +MOVE_CONFLICT_MESSAGE = "Some resources did not move" +MOVE_CHECK_CONFLICT_MESSAGE = "Some resources would not move" + + +def _describe_resource_count(count: int) -> str: + return f"{count} resource" if count == 1 else f"{count} resources" + + +def _get_resources_to_move( + client: DataMasqueClient, + *, + names: list[str], + sources: list[Project] | None, + type_names: list[ResourceTypeName] | None, + search: str | None, + destination: Project, +) -> dict[ResourceTypeName, list[Resource]]: + """ + Return the resources the filters select, by type, leaving out those already in the destination. + + Built-in seeds belong to no project and cannot move, so they are left out too. + """ + listed = client.list_resources(projects=sources, types=type_names, search=search) + selected = { + type_name: [ + resource + for resource in resources + if resource.project not in (None, destination.reference) and (not names or resource.name in names) + ] + for type_name, resources in listed.items() + } + return {type_name: resources for type_name, resources in selected.items() if resources} + + +@app.command("move") +def move_resources( + names: list[str] | None = typer.Argument( + None, help="Exact names of the resources to move, of any type unless --type is given; omit to move every match" + ), + destination: str = typer.Option(..., "--to", help="Project to move the resources to: name or id"), + sources: list[str] | None = typer.Option( + None, "--project", help=f"Move from this project only. {PROJECT_OPTION_HELP}; repeatable" + ), + type_names: list[ResourceTypeName] | None = typer.Option(None, "--type", help="Move this type only; repeatable"), + search: str | None = typer.Option(None, help="Move resources whose name contains every word of this, any case"), + is_check_only: bool = typer.Option( + False, "--check", help="Only list the resources and what would stop them moving" + ), + profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), + is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), + is_json: bool = typer.Option(False, "--json", help="Output as JSON"), +) -> None: + """ + Move resources to another project, with their files and runs. + + Select them by project, type, a name search or exact names; the filters combine. + A resource that clashes with the destination stays where it is, and the others move. + Rulesets and configurations whose library imports resolve differently after the move become invalid. + """ + if not (names or sources or type_names or search): + abort( + "Select the resources to move.", + code=ErrorCode.INVALID_INPUT, + hint="Pass resource names, --project, --type or --search.", + ) + + client = get_client(profile) + projects = client.list_projects() + target = get_named_project(projects, destination) + selected = _get_resources_to_move( + client, + names=names or [], + sources=[get_named_project(projects, source) for source in sources] if sources else None, + type_names=type_names, + search=search, + destination=target, + ) + if not selected: + abort(f"No resources to move to '{target.name}'.", code=ErrorCode.NOT_FOUND) + + # The selection leaves out resources in no project, and a deleted project has no resources left. + project_names_by_reference = {project.reference: project.name for project in projects} + rows = [ + { + "type": type_name.value, + "name": resource.name, + "project": project_label(project_names_by_reference, resource.project), + } + for type_name, resources in selected.items() + for resource in resources + ] + render_output( + rows, is_json=is_json, columns=["type", "name", "project"], title=f"Resources to move to {target.name}" + ) + + if is_check_only: + try: + conflicts = client.get_resource_move_conflicts(selected, target) + except DataMasqueApiError as exc: + abort_api_error("Failed to check the move", exc) + if conflicts: + abort(MOVE_CHECK_CONFLICT_MESSAGE, code=ErrorCode.CONFLICT, details=[c.detail for c in conflicts]) + print_success(f"All {_describe_resource_count(len(rows))} can move to '{target.name}'.") + return + + if not is_confirmed: + confirm_or_abort(f"Move {_describe_resource_count(len(rows))} to '{target.name}'?") + + try: + result = client.move_resources(selected, target) + except DataMasqueApiError as exc: + abort_api_error(f"Failed to move resources to '{target.name}'", exc) + + if result.conflicts: + abort( + f"{MOVE_CONFLICT_MESSAGE}; {result.moved} moved to '{target.name}'", + code=ErrorCode.CONFLICT, + details=[c.detail for c in result.conflicts], + ) + print_success(f"Moved {_describe_resource_count(result.moved)} to '{target.name}'.") diff --git a/src/datamasque_cli/main.py b/src/datamasque_cli/main.py index 8df520f..ea0ce77 100644 --- a/src/datamasque_cli/main.py +++ b/src/datamasque_cli/main.py @@ -28,6 +28,7 @@ files, ifm, projects, + resources, ruleset_libraries, rulesets, runs, @@ -67,6 +68,7 @@ app.add_typer(ifm.app, name="ifm") app.add_typer(table_references.app, name="table-references") app.add_typer(projects.app, name="projects") +app.add_typer(resources.app, name="resources") @app.command() diff --git a/tests/commands/test_resources.py b/tests/commands/test_resources.py new file mode 100644 index 0000000..429708a --- /dev/null +++ b/tests/commands/test_resources.py @@ -0,0 +1,151 @@ +from __future__ import annotations + +from collections.abc import Iterator +from unittest.mock import MagicMock, patch + +import pytest +from datamasque.client.models.resource import ( + Resource, + ResourceMoveConflict, + ResourceMoveConflictReason, + ResourceMoveResult, +) +from datamasque.client.models.resource_type import ResourceTypeName +from typer.testing import CliRunner + +from datamasque_cli.errors import ExitCode +from datamasque_cli.main import app +from tests.conftest import make_project, with_projects + +MODULE = "datamasque_cli.commands.resources" + +DEFAULT = make_project(1, "Default") +FINANCE = make_project(2, "Finance") + +CUSTOMERS = Resource(id="r1", name="customers", project=FINANCE.reference) +ORDERS = Resource(id="r2", name="orders", project=FINANCE.reference) +ALREADY_THERE = Resource(id="r3", name="customers", project=DEFAULT.reference) +BUILT_IN_SEED = Resource(id="s1", name="first_names.csv", project=None) + +CUSTOMERS_CLASH = ResourceMoveConflict( + reason=ResourceMoveConflictReason.name_in_use, + detail='Ruleset "customers" exists.', + type=ResourceTypeName.rulesets, + id="r1", + name="customers", +) + + +@pytest.fixture() +def client() -> Iterator[MagicMock]: + client = with_projects(MagicMock(), DEFAULT, FINANCE) + client.list_resources.return_value = { + ResourceTypeName.rulesets: [CUSTOMERS, ORDERS, ALREADY_THERE], + ResourceTypeName.seeds: [BUILT_IN_SEED], + } + client.move_resources.return_value = ResourceMoveResult(moved=2, conflicts=[]) + with patch(f"{MODULE}.get_client", return_value=client): + yield client + + +def test_move_project_sends_its_resources_and_filters(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke( + app, + [ + "resources", + "move", + "--project", + "finance", + "--type", + "rulesets", + "--search", + "cust", + "--to", + "default", + "-y", + ], + ) + + assert result.exit_code == 0 + client.list_projects.assert_called_once_with() + client.list_resources.assert_called_once_with(projects=[FINANCE], types=[ResourceTypeName.rulesets], search="cust") + client.move_resources.assert_called_once_with({ResourceTypeName.rulesets: [CUSTOMERS, ORDERS]}, DEFAULT) + + +def test_move_names_select_exact_names_only(client: MagicMock, runner: CliRunner) -> None: + client.list_resources.return_value = { + ResourceTypeName.rulesets: [CUSTOMERS, Resource(id="r4", name="customers_v2", project=FINANCE.reference)], + } + + result = runner.invoke(app, ["resources", "move", "customers", "--to", "default", "-y"]) + + assert result.exit_code == 0 + client.move_resources.assert_called_once_with({ResourceTypeName.rulesets: [CUSTOMERS]}, DEFAULT) + + +def test_move_without_any_selection_is_rejected_without_a_request(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["resources", "move", "--to", "default", "-y"]) + + assert result.exit_code == ExitCode.INVALID_INPUT + assert result.stderr == ( + "Error: Select the resources to move.\nHint: Pass resource names, --project, --type or --search.\n" + ) + client.list_resources.assert_not_called() + + +def test_move_with_nothing_outside_the_destination_is_not_found(client: MagicMock, runner: CliRunner) -> None: + client.list_resources.return_value = { + ResourceTypeName.rulesets: [ALREADY_THERE], + ResourceTypeName.seeds: [BUILT_IN_SEED], + } + + result = runner.invoke(app, ["resources", "move", "--search", "c", "--to", "default", "-y"]) + + assert result.exit_code == ExitCode.NOT_FOUND + assert result.stderr == "Error: No resources to move to 'Default'.\n" + client.move_resources.assert_not_called() + + +def test_move_that_leaves_resources_behind_names_them_and_fails(client: MagicMock, runner: CliRunner) -> None: + client.move_resources.return_value = ResourceMoveResult(moved=1, conflicts=[CUSTOMERS_CLASH]) + + result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default", "-y"]) + + assert result.exit_code == ExitCode.CONFLICT + assert result.stderr == ( + "Error: Some resources did not move; 1 moved to 'Default':\n Ruleset \"customers\" exists.\n" + ) + + +def test_move_declined_at_the_prompt_moves_nothing(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default"], input="n\n") + + assert result.exit_code == ExitCode.CANCELLED + client.move_resources.assert_not_called() + + +@pytest.mark.parametrize( + ("conflicts", "exit_code", "stderr"), + [ + ([], 0, "All 2 resources can move to 'Default'.\n"), + ( + [CUSTOMERS_CLASH], + ExitCode.CONFLICT, + 'Error: Some resources would not move:\n Ruleset "customers" exists.\n', + ), + ], + ids=["no-conflicts", "conflict"], +) +def test_move_check_reports_the_conflicts_without_moving( + client: MagicMock, runner: CliRunner, conflicts: list[ResourceMoveConflict], exit_code: int, stderr: str +) -> None: + client.get_resource_move_conflicts.return_value = conflicts + + result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default", "--check"]) + + assert result.exit_code == exit_code + assert result.stderr == stderr + client.get_resource_move_conflicts.assert_called_once_with( + {ResourceTypeName.rulesets: [CUSTOMERS, ORDERS]}, DEFAULT + ) + client.move_resources.assert_not_called() From 3ee75fbdea614d1cd7ec88bfa892c257b2869c3c Mon Sep 17 00:00:00 2001 From: jiatolentinoDM Date: Tue, 3 Nov 2026 15:28:07 +0800 Subject: [PATCH 07/11] fix: tighten dm resources move conflicts and let dm projects get show a deleted project - dm resources move lists a conflict detail once when several resources clash the same way, and says no resources moved when none did. - dm projects get finds a deleted project by its id, as projects list --include-deleted shows it, and its output says whether the project is deleted. A name still resolves among the active projects only. --- src/datamasque_cli/commands/projects.py | 29 ++++++++++++-- src/datamasque_cli/commands/resources.py | 18 ++++++--- src/datamasque_cli/projects.py | 10 ++++- tests/commands/test_projects.py | 48 +++++++++++++++++++++--- tests/commands/test_resources.py | 19 ++++++++++ 5 files changed, 107 insertions(+), 17 deletions(-) diff --git a/src/datamasque_cli/commands/projects.py b/src/datamasque_cli/commands/projects.py index 250d244..a20e59e 100644 --- a/src/datamasque_cli/commands/projects.py +++ b/src/datamasque_cli/commands/projects.py @@ -3,13 +3,14 @@ from __future__ import annotations import typer +from datamasque.client import DataMasqueClient from datamasque.client.exceptions import DataMasqueApiError, ProjectDeleteConflictError from datamasque.client.models.project import Project, ProjectCreateRequest, ProjectUpdateRequest from datamasque_cli.client import get_client from datamasque_cli.errors import ErrorCode, abort, abort_api_error, confirm_or_abort from datamasque_cli.output import print_success, render_output -from datamasque_cli.projects import PROJECT_OPTION_HELP, get_named_project, resolve_project +from datamasque_cli.projects import PROJECT_OPTION_HELP, find_named_project, get_named_project, resolve_project app = typer.Typer(help="Manage projects.", no_args_is_help=True) @@ -25,6 +26,26 @@ def _build_project_row(project: Project) -> dict[str, object]: } +def _find_project_for_get(client: DataMasqueClient, name_or_id: str) -> tuple[Project, bool]: + """ + Return the project `name_or_id` names, and whether it is deleted. + + A name resolves among the active projects only, because a deleted project can share an active project's name. + An id that no active project has also finds a deleted project, as `list --include-deleted` shows it. + """ + active = client.list_projects() + found = find_named_project(active, name_or_id) + if found is not None: + return found, False + + deleted = next( + (project for project in client.list_projects(include_archived=True) if str(project.id) == name_or_id), None + ) + if deleted is None: + abort(f"Project '{name_or_id}' not found.", code=ErrorCode.NOT_FOUND) + return deleted, True + + @app.command("list") def list_projects( is_deleted_included: bool = typer.Option(False, "--include-deleted", help="Also list deleted projects"), @@ -53,10 +74,10 @@ def get_project( profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: - """Show a project's details.""" + """Show a project's details, or a deleted project's by its id.""" client = get_client(profile) - found = resolve_project(client, project) - data = {**_build_project_row(found), "updated": found.updated} + found, is_deleted = _find_project_for_get(client, project) + data = {**_build_project_row(found), "updated": found.updated, "deleted": is_deleted} render_output(data, is_json=is_json, title=f"Project: {found.name}") diff --git a/src/datamasque_cli/commands/resources.py b/src/datamasque_cli/commands/resources.py index dfb9e7c..0f674c4 100644 --- a/src/datamasque_cli/commands/resources.py +++ b/src/datamasque_cli/commands/resources.py @@ -6,7 +6,7 @@ from datamasque.client import DataMasqueClient from datamasque.client.exceptions import DataMasqueApiError from datamasque.client.models.project import Project -from datamasque.client.models.resource import Resource +from datamasque.client.models.resource import Resource, ResourceMoveConflict from datamasque.client.models.resource_type import ResourceTypeName from datamasque_cli.client import get_client @@ -24,6 +24,11 @@ def _describe_resource_count(count: int) -> str: return f"{count} resource" if count == 1 else f"{count} resources" +def _get_conflict_details(conflicts: list[ResourceMoveConflict]) -> list[str]: + """Return each conflict's detail once, in order, since resources that clash the same way share a detail.""" + return list(dict.fromkeys(conflict.detail for conflict in conflicts)) + + def _get_resources_to_move( client: DataMasqueClient, *, @@ -117,7 +122,7 @@ def move_resources( except DataMasqueApiError as exc: abort_api_error("Failed to check the move", exc) if conflicts: - abort(MOVE_CHECK_CONFLICT_MESSAGE, code=ErrorCode.CONFLICT, details=[c.detail for c in conflicts]) + abort(MOVE_CHECK_CONFLICT_MESSAGE, code=ErrorCode.CONFLICT, details=_get_conflict_details(conflicts)) print_success(f"All {_describe_resource_count(len(rows))} can move to '{target.name}'.") return @@ -130,9 +135,10 @@ def move_resources( abort_api_error(f"Failed to move resources to '{target.name}'", exc) if result.conflicts: - abort( - f"{MOVE_CONFLICT_MESSAGE}; {result.moved} moved to '{target.name}'", - code=ErrorCode.CONFLICT, - details=[c.detail for c in result.conflicts], + message = ( + f"{MOVE_CONFLICT_MESSAGE}; {result.moved} moved to '{target.name}'" + if result.moved + else f"No resources moved to '{target.name}'" ) + abort(message, code=ErrorCode.CONFLICT, details=_get_conflict_details(result.conflicts)) print_success(f"Moved {_describe_resource_count(result.moved)} to '{target.name}'.") diff --git a/src/datamasque_cli/projects.py b/src/datamasque_cli/projects.py index 658e350..08d0705 100644 --- a/src/datamasque_cli/projects.py +++ b/src/datamasque_cli/projects.py @@ -23,11 +23,17 @@ def project(self) -> str | None: ... ScopedT = TypeVar("ScopedT", bound=ProjectScoped) -def get_named_project(projects: Sequence[Project], name_or_id: str) -> Project: - """Return the project in `projects` named `name_or_id`, ignoring case, or with that numeric id.""" +def find_named_project(projects: Sequence[Project], name_or_id: str) -> Project | None: + """Return the project in `projects` named `name_or_id`, ignoring case, or with that numeric id, else `None`.""" match = next((p for p in projects if p.name.casefold() == name_or_id.casefold()), None) if match is None and name_or_id.isdigit(): match = next((p for p in projects if p.id == int(name_or_id)), None) + return match + + +def get_named_project(projects: Sequence[Project], name_or_id: str) -> Project: + """Return the project in `projects` named `name_or_id`, ignoring case, or with that numeric id.""" + match = find_named_project(projects, name_or_id) if match is None: abort(f"Project '{name_or_id}' not found.", code=ErrorCode.NOT_FOUND) return match diff --git a/tests/commands/test_projects.py b/tests/commands/test_projects.py index c8fd523..eb95fcc 100644 --- a/tests/commands/test_projects.py +++ b/tests/commands/test_projects.py @@ -8,6 +8,7 @@ import pytest from datamasque.client.exceptions import DataMasqueApiError, ProjectDeleteConflictError from datamasque.client.models.project import ( + Project, ProjectCreateRequest, ProjectDeleteConflict, ProjectDeleteConflictReason, @@ -41,6 +42,13 @@ def _api_error(status: HTTPStatus, detail: str) -> DataMasqueApiError: return DataMasqueApiError(detail, response=response) +def with_deleted_projects(client: MagicMock, *deleted: Project) -> None: + """Make `list_projects` return `Default` and `Finance`, and the `deleted` projects first when they are included.""" + client.list_projects.side_effect = lambda include_archived=False: ( + [*deleted, DEFAULT, FINANCE] if include_archived else [DEFAULT, FINANCE] + ) + + @pytest.fixture() def client() -> Iterator[MagicMock]: client = with_projects(MagicMock(), DEFAULT, FINANCE) @@ -57,17 +65,15 @@ def test_list_shows_the_active_projects(client: MagicMock, runner: CliRunner) -> def test_list_include_deleted_marks_the_deleted_projects(client: MagicMock, runner: CliRunner) -> None: - client.list_projects.side_effect = lambda include_archived=False: ( - [DEFAULT, FINANCE, OLD] if include_archived else [DEFAULT, FINANCE] - ) + with_deleted_projects(client, OLD) result = runner.invoke(app, ["projects", "list", "--include-deleted", "--json"]) assert result.exit_code == 0 assert [(p["name"], p["deleted"]) for p in json.loads(result.stdout)] == [ + ("Old", True), ("Default", False), ("Finance", False), - ("Old", True), ] @@ -76,7 +82,39 @@ def test_get_finds_a_project_by_name_in_any_case_or_by_id(client: MagicMock, run result = runner.invoke(app, ["projects", "get", given, "--json"]) assert result.exit_code == 0 - assert json.loads(result.stdout)["name"] == "Finance" + found = json.loads(result.stdout) + assert (found["name"], found["deleted"]) == ("Finance", False) + + +def test_get_finds_a_deleted_project_by_id(client: MagicMock, runner: CliRunner) -> None: + with_deleted_projects(client, OLD) + + result = runner.invoke(app, ["projects", "get", "3", "--json"]) + + assert result.exit_code == 0 + found = json.loads(result.stdout) + assert (found["id"], found["name"], found["deleted"]) == (3, "Old", True) + + +def test_get_by_name_finds_the_active_project_not_a_deleted_one_of_that_name( + client: MagicMock, runner: CliRunner +) -> None: + with_deleted_projects(client, make_project(4, "Finance")) + + result = runner.invoke(app, ["projects", "get", "finance", "--json"]) + + assert result.exit_code == 0 + found = json.loads(result.stdout) + assert (found["id"], found["deleted"]) == (2, False) + + +def test_get_of_an_unknown_id_is_not_found(client: MagicMock, runner: CliRunner) -> None: + with_deleted_projects(client, OLD) + + result = runner.invoke(app, ["projects", "get", "99"]) + + assert result.exit_code == ExitCode.NOT_FOUND + assert result.stderr == "Error: Project '99' not found.\n" def test_get_of_an_unknown_project_is_not_found(client: MagicMock, runner: CliRunner) -> None: diff --git a/tests/commands/test_resources.py b/tests/commands/test_resources.py index 429708a..a0c31bd 100644 --- a/tests/commands/test_resources.py +++ b/tests/commands/test_resources.py @@ -117,6 +117,25 @@ def test_move_that_leaves_resources_behind_names_them_and_fails(client: MagicMoc ) +def test_move_that_moves_nothing_says_none_moved(client: MagicMock, runner: CliRunner) -> None: + client.move_resources.return_value = ResourceMoveResult(moved=0, conflicts=[CUSTOMERS_CLASH]) + + result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default", "-y"]) + + assert result.exit_code == ExitCode.CONFLICT + assert result.stderr == "Error: No resources moved to 'Default':\n Ruleset \"customers\" exists.\n" + + +def test_move_lists_a_detail_shared_by_several_conflicts_once(client: MagicMock, runner: CliRunner) -> None: + orders_clash = CUSTOMERS_CLASH.model_copy(update={"id": "r2", "name": "orders"}) + client.get_resource_move_conflicts.return_value = [CUSTOMERS_CLASH, orders_clash] + + result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default", "--check"]) + + assert result.exit_code == ExitCode.CONFLICT + assert result.stderr == 'Error: Some resources would not move:\n Ruleset "customers" exists.\n' + + def test_move_declined_at_the_prompt_moves_nothing(client: MagicMock, runner: CliRunner) -> None: result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default"], input="n\n") From 6c549e75dcbf5092ab58f1a4321dc326fdc61189 Mon Sep 17 00:00:00 2001 From: jiatolentinoDM Date: Wed, 4 Nov 2026 07:17:03 +0800 Subject: [PATCH 08/11] fix: report unmatched move names, bundle through the client, and pin exact test results - dm resources move aborts with not-found, naming each name that matches none of the resources the other filters select, instead of moving the rest and exiting 0. - dm rulesets export-bundle and import-bundle call the client's export_bundle and import_bundle. export-bundle gains --include-seed-files, so its seed files are bundled only on request. - import-bundle names the project that took the items the bundle files under no project, and leaves the older-bundle warning to the client, which already logs it. - Rename project_names to get_project_names_by_reference and in_project to filter_by_project, and make the test helper _with_deleted_projects private. - Tests compare the full JSON or message where the exact result is known. --- README.md | 3 +- src/datamasque_cli/client.py | 6 +- src/datamasque_cli/commands/connections.py | 10 +- src/datamasque_cli/commands/discovery.py | 4 +- .../commands/discovery_config_libraries.py | 14 +-- .../commands/discovery_configs.py | 18 ++-- src/datamasque_cli/commands/files.py | 8 +- src/datamasque_cli/commands/resources.py | 8 ++ .../commands/ruleset_libraries.py | 16 +-- src/datamasque_cli/commands/rulesets.py | 102 ++++++++---------- src/datamasque_cli/commands/runs.py | 18 ++-- src/datamasque_cli/commands/seeds.py | 8 +- src/datamasque_cli/commands/system.py | 2 +- .../commands/table_references.py | 12 +-- src/datamasque_cli/projects.py | 6 +- .../test_discovery_config_libraries.py | 13 +-- tests/commands/test_discovery_configs.py | 2 +- tests/commands/test_projects.py | 10 +- tests/commands/test_resources.py | 20 ++++ tests/commands/test_rulesets.py | 94 ++++++++-------- tests/test_projects.py | 14 +-- 21 files changed, 205 insertions(+), 183 deletions(-) diff --git a/README.md b/README.md index 7beef4c..bdb1867 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,8 @@ dm rulesets generate --file request.json # Generate from schema dm rulesets generate --file req.json -o out.yaml # Generate to file dm rulesets validate --file rules.yaml --type database|file # Validate against server (YAML under 60 KiB) dm rulesets status # Validation status; poll after creating YAML of 60 KiB+ -dm rulesets export-bundle -o bundle.zip # Export rulesets + libraries + seeds, by project +dm rulesets export-bundle -o bundle.zip # Export rulesets + libraries, by project +dm rulesets export-bundle -o bundle.zip --include-seed-files # Also bundle the custom seed files they use dm rulesets import-bundle --file bundle.zip # Import a previously exported bundle dm rulesets import-bundle -f bundle.zip --overwrite-rulesets --overwrite-libraries # Replace existing entries dm rulesets import-bundle -f bundle.zip --fallback-project # Project for items filed under none diff --git a/src/datamasque_cli/client.py b/src/datamasque_cli/client.py index ea60339..6aba6ba 100644 --- a/src/datamasque_cli/client.py +++ b/src/datamasque_cli/client.py @@ -16,7 +16,7 @@ from datamasque_cli.config import Config, Profile, load_config from datamasque_cli.errors import ErrorCode, abort -from datamasque_cli.projects import in_project, require_single_or_abort, resolve_optional_project +from datamasque_cli.projects import filter_by_project, require_single_or_abort, resolve_optional_project ENV_URL = "DATAMASQUE_URL" ENV_USERNAME = "DATAMASQUE_USERNAME" @@ -223,7 +223,9 @@ def resolve_connection(client: DataMasqueClient, name_or_id: str, project: str | Aborts when nothing matches, or when the name matches connections in more than one project. """ connections = client.list_connections() - by_name = in_project([c for c in connections if c.name == name_or_id], resolve_optional_project(client, project)) + by_name = filter_by_project( + [c for c in connections if c.name == name_or_id], resolve_optional_project(client, project) + ) if not by_name: by_id = next((c for c in connections if str(c.id) == name_or_id), None) if by_id is not None: diff --git a/src/datamasque_cli/commands/connections.py b/src/datamasque_cli/commands/connections.py index 0046f0b..23e2a18 100644 --- a/src/datamasque_cli/commands/connections.py +++ b/src/datamasque_cli/commands/connections.py @@ -28,9 +28,9 @@ from datamasque_cli.output import print_success, redact_sensitive_fields, render_output from datamasque_cli.projects import ( PROJECT_OPTION_HELP, - in_project, + filter_by_project, + get_project_names_by_reference, project_label, - project_names, resolve_create_project, resolve_optional_project, ) @@ -106,8 +106,8 @@ def list_connections( ) -> None: """List all configured connections, or those in one project.""" client = get_client(profile) - connections = in_project(client.list_connections(), resolve_optional_project(client, project)) - names = project_names(client) + connections = filter_by_project(client.list_connections(), resolve_optional_project(client, project)) + names = get_project_names_by_reference(client) data = [] for conn in connections: @@ -143,7 +143,7 @@ def get_connection( match = resolve_connection(client, name, project) data = redact_sensitive_fields(match.model_dump()) - data["project"] = project_label(project_names(client), match.project) + data["project"] = project_label(get_project_names_by_reference(client), match.project) render_output(data, is_json=is_json, title=f"Connection: {name}") diff --git a/src/datamasque_cli/commands/discovery.py b/src/datamasque_cli/commands/discovery.py index d3d9abb..84d7585 100644 --- a/src/datamasque_cli/commands/discovery.py +++ b/src/datamasque_cli/commands/discovery.py @@ -34,7 +34,7 @@ ) from datamasque_cli.fileio import write_bytes_or_abort, write_text_or_abort from datamasque_cli.output import print_info, print_json, print_success, render_output, should_emit_json -from datamasque_cli.projects import in_project, require_single_or_abort, resolve_optional_project +from datamasque_cli.projects import filter_by_project, require_single_or_abort, resolve_optional_project app = typer.Typer(help="Data discovery operations.", no_args_is_help=True) app.add_typer(discovery_configs.app, name="configs") @@ -87,7 +87,7 @@ def _resolve_discovery_config_id( Config names are unique per type within a project, so name, type and project identify at most one config. """ - named = in_project( + named = filter_by_project( [c for c in client.list_discovery_configs() if c.name == name], resolve_optional_project(client, project) ) of_type = [c for c in named if c.config_type is expected_type] diff --git a/src/datamasque_cli/commands/discovery_config_libraries.py b/src/datamasque_cli/commands/discovery_config_libraries.py index dad3129..9da3448 100644 --- a/src/datamasque_cli/commands/discovery_config_libraries.py +++ b/src/datamasque_cli/commands/discovery_config_libraries.py @@ -17,9 +17,9 @@ from datamasque_cli.output import print_success, print_warning, render_output from datamasque_cli.projects import ( PROJECT_OPTION_HELP, - in_project, + filter_by_project, + get_project_names_by_reference, project_label, - project_names, require_single_or_abort, resolve_create_project, resolve_optional_project, @@ -32,7 +32,7 @@ def _find_library(client: DataMasqueClient, name: str, project: str | None) -> DiscoveryConfigLibrary: """Return the library named `name`, with its YAML, in `project` or in the one project that has it.""" matches = [lib for lib in client.list_discovery_config_libraries() if lib.name == name] - matches = in_project(matches, resolve_optional_project(client, project)) + matches = filter_by_project(matches, resolve_optional_project(client, project)) found = require_single_or_abort(client, matches, f"Discovery config library '{name}'") return client.get_discovery_config_library(found.id) @@ -45,8 +45,8 @@ def list_libraries( ) -> None: """List all discovery config libraries, or those in one project.""" client = get_client(profile) - libraries = in_project(client.list_discovery_config_libraries(), resolve_optional_project(client, project)) - names = project_names(client) + libraries = filter_by_project(client.list_discovery_config_libraries(), resolve_optional_project(client, project)) + names = get_project_names_by_reference(client) data = [ { @@ -85,7 +85,7 @@ def get_library( data: dict[str, object] = { "id": lib.id, - "project": project_label(project_names(client), lib.project), + "project": project_label(get_project_names_by_reference(client), lib.project), "name": lib.name, "valid": lib.is_valid.value if lib.is_valid else "unknown", "used_by": lib.usage_count, @@ -199,7 +199,7 @@ def show_library_status( status = lib.is_valid.value if lib.is_valid else "unknown" data: dict[str, object] = { - "project": project_label(project_names(client), lib.project), + "project": project_label(get_project_names_by_reference(client), lib.project), "name": lib.name, "status": status, "validation_error": lib.validation_error, diff --git a/src/datamasque_cli/commands/discovery_configs.py b/src/datamasque_cli/commands/discovery_configs.py index da66775..047b5aa 100644 --- a/src/datamasque_cli/commands/discovery_configs.py +++ b/src/datamasque_cli/commands/discovery_configs.py @@ -28,9 +28,9 @@ from datamasque_cli.output import print_info, print_success, print_warning, render_output from datamasque_cli.projects import ( PROJECT_OPTION_HELP, - in_project, + filter_by_project, + get_project_names_by_reference, project_label, - project_names, resolve_create_project, resolve_optional_project, resolve_target_project, @@ -49,7 +49,7 @@ def _find_by_name( matches = [c for c in client.list_discovery_configs() if c.name == name] if config_type is not None: matches = [c for c in matches if c.config_type is config_type] - return in_project(matches, resolve_optional_project(client, project)) + return filter_by_project(matches, resolve_optional_project(client, project)) def _require_single_matched_config_or_abort( @@ -59,7 +59,7 @@ def _require_single_matched_config_or_abort( if not matched_configs: abort(f"Discovery config '{name}' not found.", code=ErrorCode.NOT_FOUND) if len(matched_configs) > 1: - names = project_names(client) + names = get_project_names_by_reference(client) options = "\n ".join( f"id={c.id} type={c.config_type.value} project={project_label(names, c.project)}" for c in matched_configs ) @@ -82,8 +82,8 @@ def list_configs( ) -> None: """List all discovery configs, or those in one project.""" client = get_client(profile) - configs = in_project(client.list_discovery_configs(), resolve_optional_project(client, project)) - names = project_names(client) + configs = filter_by_project(client.list_discovery_configs(), resolve_optional_project(client, project)) + names = get_project_names_by_reference(client) if config_type is not None: configs = [c for c in configs if c.config_type is config_type] @@ -128,7 +128,7 @@ def get_config( data: dict[str, object] = { "id": full.id, - "project": project_label(project_names(client), full.project), + "project": project_label(get_project_names_by_reference(client), full.project), "name": full.name, "type": full.config_type.value, "valid": full.is_valid.value if full.is_valid else "unknown", @@ -196,7 +196,7 @@ def create_config( hint="Pass --type database|file to create a new one.", ) else: - names = project_names(client) + names = get_project_names_by_reference(client) options = ", ".join(f"{c.config_type.value} in {project_label(names, c.project)}" for c in existing) abort( f"Multiple discovery configs named '{name}' ({options}).", @@ -308,7 +308,7 @@ def show_config_status( status = match.is_valid.value if match.is_valid else "unknown" data: dict[str, object] = { - "project": project_label(project_names(client), match.project), + "project": project_label(get_project_names_by_reference(client), match.project), "name": match.name, "type": match.config_type.value, "status": status, diff --git a/src/datamasque_cli/commands/files.py b/src/datamasque_cli/commands/files.py index 5d263be..0502e9c 100644 --- a/src/datamasque_cli/commands/files.py +++ b/src/datamasque_cli/commands/files.py @@ -12,9 +12,9 @@ from datamasque_cli.output import print_success, render_output from datamasque_cli.projects import ( PROJECT_OPTION_HELP, - in_project, + filter_by_project, + get_project_names_by_reference, project_label, - project_names, require_single_or_abort, resolve_optional_project, resolve_target_project, @@ -48,7 +48,7 @@ def list_files( client = get_client(profile) target = resolve_optional_project(client, project) files = client.list_files_of_type(klass, project=target.id if target else None) - names = project_names(client) + names = get_project_names_by_reference(client) data = [{"id": f.id, "project": project_label(names, f.project), "name": f.name} for f in files] render_output(data, is_json=is_json, columns=["id", "project", "name"], title=f"Files ({file_type})") @@ -70,7 +70,7 @@ def delete_file( named = [f for f in client.list_files_of_type(klass) if f.name == name] match = require_single_or_abort( - client, in_project(named, resolve_optional_project(client, project)), f"File '{name}' ({file_type})" + client, filter_by_project(named, resolve_optional_project(client, project)), f"File '{name}' ({file_type})" ) if not is_confirmed: diff --git a/src/datamasque_cli/commands/resources.py b/src/datamasque_cli/commands/resources.py index 0f674c4..7d1ab27 100644 --- a/src/datamasque_cli/commands/resources.py +++ b/src/datamasque_cli/commands/resources.py @@ -42,8 +42,16 @@ def _get_resources_to_move( Return the resources the filters select, by type, leaving out those already in the destination. Built-in seeds belong to no project and cannot move, so they are left out too. + Aborts with not-found when a name matches none of the resources the other filters select. """ listed = client.list_resources(projects=sources, types=type_names, search=search) + listed_names = {resource.name for resources in listed.values() for resource in resources} + if unmatched_names := [name for name in dict.fromkeys(names) if name not in listed_names]: + abort( + f"No resources named {', '.join(repr(name) for name in unmatched_names)}.", + code=ErrorCode.NOT_FOUND, + hint="Check the names, and that --project, --type and --search select them.", + ) selected = { type_name: [ resource diff --git a/src/datamasque_cli/commands/ruleset_libraries.py b/src/datamasque_cli/commands/ruleset_libraries.py index dfe5fa1..c6cebcc 100644 --- a/src/datamasque_cli/commands/ruleset_libraries.py +++ b/src/datamasque_cli/commands/ruleset_libraries.py @@ -16,9 +16,9 @@ from datamasque_cli.output import print_info, print_success, render_output, should_emit_json from datamasque_cli.projects import ( PROJECT_OPTION_HELP, - in_project, + filter_by_project, + get_project_names_by_reference, project_label, - project_names, require_single_or_abort, resolve_create_project, resolve_optional_project, @@ -30,7 +30,7 @@ def _find_library(client: DataMasqueClient, name: str, project: str | None) -> RulesetLibrary: """Return the library named `name`, with its YAML, in `project` or in the one project that has it.""" matches = [lib for lib in client.list_ruleset_libraries() if lib.name == name] - matches = in_project(matches, resolve_optional_project(client, project)) + matches = filter_by_project(matches, resolve_optional_project(client, project)) found = require_single_or_abort(client, matches, f"Library '{name}'") return client.get_ruleset_library(found.id) @@ -43,8 +43,8 @@ def list_libraries( ) -> None: """List all ruleset libraries, or those in one project.""" client = get_client(profile) - libraries = in_project(client.list_ruleset_libraries(), resolve_optional_project(client, project)) - names = project_names(client) + libraries = filter_by_project(client.list_ruleset_libraries(), resolve_optional_project(client, project)) + names = get_project_names_by_reference(client) data = [ { @@ -77,7 +77,7 @@ def get_library( data: dict[str, object] = { "id": lib.id, - "project": project_label(project_names(client), lib.project), + "project": project_label(get_project_names_by_reference(client), lib.project), "name": lib.name, "valid": lib.is_valid.value if lib.is_valid else "unknown", "created": lib.created, @@ -171,7 +171,7 @@ def show_library_status( status = lib.is_valid.value if lib.is_valid else "unknown" errors = lib.validation_errors or [] data: dict[str, object] = { - "project": project_label(project_names(client), lib.project), + "project": project_label(get_project_names_by_reference(client), lib.project), "name": lib.name, "status": status, } @@ -197,7 +197,7 @@ def library_usage( lib = _find_library(client, name, project) rulesets = client.list_rulesets_using_library(lib.id) - names = project_names(client) + names = get_project_names_by_reference(client) data = [ { diff --git a/src/datamasque_cli/commands/rulesets.py b/src/datamasque_cli/commands/rulesets.py index b291a29..b9805cd 100644 --- a/src/datamasque_cli/commands/rulesets.py +++ b/src/datamasque_cli/commands/rulesets.py @@ -7,7 +7,6 @@ import typer from datamasque.client import DataMasqueClient -from datamasque.client.base import UploadFile from datamasque.client.exceptions import DataMasqueApiError from datamasque.client.models.discovery import FileRulesetGenerationRequest, RulesetGenerationRequest from datamasque.client.models.ruleset import Ruleset, RulesetType @@ -33,9 +32,9 @@ from datamasque_cli.output import print_info, print_success, print_warning, render_output, should_emit_json from datamasque_cli.projects import ( PROJECT_OPTION_HELP, - in_project, + filter_by_project, + get_project_names_by_reference, project_label, - project_names, resolve_create_project, resolve_optional_project, resolve_project, @@ -55,7 +54,7 @@ def _find_by_name( matches = [rs for rs in client.list_rulesets() if rs.name == name] if mask_type is not None: matches = [rs for rs in matches if rs.ruleset_type == mask_type] - return in_project(matches, resolve_optional_project(client, project)) + return filter_by_project(matches, resolve_optional_project(client, project)) def _require_single_matched_ruleset_or_abort( @@ -65,7 +64,7 @@ def _require_single_matched_ruleset_or_abort( if not matched_rulesets: abort(f"Ruleset '{name}' not found.", code=ErrorCode.NOT_FOUND) if len(matched_rulesets) > 1: - names = project_names(client) + names = get_project_names_by_reference(client) options = "\n ".join( f"id={rs.id} type={rs.ruleset_type.value} project={project_label(names, rs.project)}" for rs in matched_rulesets @@ -87,12 +86,12 @@ def list_rulesets( ) -> None: """List all rulesets, or those in one project.""" client = get_client(profile) - rulesets = in_project(client.list_rulesets(), resolve_optional_project(client, project)) + rulesets = filter_by_project(client.list_rulesets(), resolve_optional_project(client, project)) if ruleset_type is not None: rulesets = [rs for rs in rulesets if rs.ruleset_type == ruleset_type] - names = project_names(client) + names = get_project_names_by_reference(client) data = [ { "id": rs.id, @@ -134,7 +133,7 @@ def get_ruleset( data: dict[str, object] = { "id": full.id, - "project": project_label(project_names(client), full.project), + "project": project_label(get_project_names_by_reference(client), full.project), "name": full.name, "type": full.ruleset_type.value, "yaml": full.yaml, @@ -179,7 +178,7 @@ def create_ruleset( hint="Pass --type database|file to create a new one.", ) else: - names = project_names(client) + names = get_project_names_by_reference(client) options = ", ".join(f"{r.ruleset_type.value} in {project_label(names, r.project)}" for r in existing) abort( f"Multiple rulesets named '{name}' ({options}).", @@ -279,17 +278,24 @@ def validate_ruleset( @app.command("export-bundle") def export_bundle( output_path: Path = typer.Option("datamasque-bundle.zip", "--output", "-o", help="Where to save the ZIP bundle"), + is_including_seed_files: bool = typer.Option( + False, "--include-seed-files", help="Also bundle the custom seed files the rulesets and libraries use" + ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: - """Export rulesets, ruleset libraries, and any referenced seed files as a ZIP bundle. + """ + Export every ruleset and ruleset library as a ZIP bundle, with their seed files on request. - Bundles only rulesets + libraries + optional seed files — not connections, - users, licences, or instance settings. Each item is filed under its project. + Bundles only rulesets, libraries and, with `--include-seed-files`, the custom seed files they use, + not connections, users, licences or instance settings. + Each item is filed under its project. """ client = get_client(profile) - # `export_configuration` is not yet wrapped in datamasque-python; hit the endpoint directly. - response = client.make_request("GET", "/api/export/v2/") - write_bytes_or_abort(output_path, response.content) + try: + bundle = client.export_bundle(include_seed_files=is_including_seed_files) + except DataMasqueApiError as exc: + abort_api_error("Failed to export the bundle", exc) + write_bytes_or_abort(output_path, bundle) print_success(f"Bundle exported to {output_path}") @@ -314,56 +320,38 @@ def import_bundle( profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: - """Import rulesets, ruleset libraries, and seed files from a ZIP bundle. + """ + Import rulesets, ruleset libraries, and seed files from a ZIP bundle. - Bundle must have been produced by `dm rulesets export-bundle` or the - server's export endpoint. Each item goes into the project the bundle files it - under; items under no project, such as those in an older bundle, go into - `--fallback-project`. By default, duplicates are skipped; pass `--overwrite-*` - flags to replace existing entries. + Bundle must have been produced by `dm rulesets export-bundle` or the server's export endpoint. + Each item goes into the project the bundle files it under; + items under no project, such as those in an older bundle, go into `--fallback-project`. + By default, duplicates are skipped; pass `--overwrite-*` flags to replace existing entries. """ if not is_confirmed: confirm_or_abort("This will modify rulesets, libraries, and seed files. Continue?") client = get_client(profile) - data = { - "overwrite_rulesets": str(overwrite_rulesets).lower(), - "overwrite_libraries": str(overwrite_libraries).lower(), - "overwrite_seed_files": str(overwrite_seeds).lower(), - } - if fallback_project is not None: - data["fallback_project"] = str(resolve_project(client, fallback_project).id) - - # `/api/import/v2/` expects a multipart `zip_archive` upload plus the overwrite - # flags and an optional `fallback_project`; `import_configuration` is not yet - # wrapped in datamasque-python, so we call `make_request` directly. - with file.open("rb") as zip_content: - response = client.make_request( - "POST", - "/api/import/v2/", - data=data, - files=[ - UploadFile( - field_name="zip_archive", - filename=file.name, - content=zip_content, - content_type="application/zip", - ), - ], + fallback = resolve_project(client, fallback_project) if fallback_project is not None else None + try: + result = client.import_bundle( + file, + overwrite_rulesets=overwrite_rulesets, + overwrite_libraries=overwrite_libraries, + overwrite_seed_files=overwrite_seeds, + fallback_project=fallback, ) + except DataMasqueApiError as exc: + abort_api_error("Failed to import the bundle", exc) print_success("Bundle imported successfully.") - if response.headers.get("Deprecation") == "true": - print_warning( - "This bundle is in the older format. Items it files under no project went into the fallback project." - ) - if response.content: - try: - summary = response.json() - except ValueError: - return - if isinstance(summary, dict): - render_output(summary, is_json=False, title="Import summary") + if result.fallback_project is not None: + print_info(f"Items the bundle files under no project went into project '{result.fallback_project}'.") + render_output( + result.model_dump(mode="json", exclude={"is_deprecated_bundle"}, exclude_none=True), + is_json=False, + title="Import summary", + ) @app.command("status") @@ -385,7 +373,7 @@ def show_ruleset_status( status = match.is_valid.value if match.is_valid else "unknown" errors = match.validation_errors or [] data: dict[str, object] = { - "project": project_label(project_names(client), match.project), + "project": project_label(get_project_names_by_reference(client), match.project), "name": match.name, "type": match.ruleset_type.value, "status": status, diff --git a/src/datamasque_cli/commands/runs.py b/src/datamasque_cli/commands/runs.py index 566303f..e78c128 100644 --- a/src/datamasque_cli/commands/runs.py +++ b/src/datamasque_cli/commands/runs.py @@ -28,9 +28,9 @@ ) from datamasque_cli.projects import ( PROJECT_OPTION_HELP, - in_project, + filter_by_project, + get_project_names_by_reference, project_label, - project_names, resolve_optional_project, ) @@ -111,7 +111,9 @@ def _resolve_ruleset_id( `project` narrows it to the project `--project` names. """ rulesets = client.list_rulesets() - by_name = in_project([r for r in rulesets if r.name == name_or_id], resolve_optional_project(client, project)) + by_name = filter_by_project( + [r for r in rulesets if r.name == name_or_id], resolve_optional_project(client, project) + ) if mask_type is not None: by_name_and_type = [r for r in by_name if r.ruleset_type.value == mask_type] @@ -128,7 +130,7 @@ def _resolve_ruleset_id( if len(by_name) == 1: return str(by_name[0].id) if len(by_name) > 1: - names = project_names(client) + names = get_project_names_by_reference(client) options = ", ".join(f"{r.ruleset_type.value}:{project_label(names, r.project)}:{r.id}" for r in by_name) abort( f"Multiple rulesets named '{name_or_id}' ({options}).", @@ -259,7 +261,9 @@ def run_status( # as literal "[status.finished]finished[/status.finished]" in the dump. is_styled = not should_emit_json(is_json) render_output( - _format_run_info(run, project_names(client), is_styled=is_styled), is_json=is_json, title=f"Run {run_id}" + _format_run_info(run, get_project_names_by_reference(client), is_styled=is_styled), + is_json=is_json, + title=f"Run {run_id}", ) @@ -303,7 +307,7 @@ def list_runs( else: runs = body is_styled = not should_emit_json(is_json) - names = project_names(client) + names = get_project_names_by_reference(client) data = [_format_run_dict(r, names, is_styled=is_styled) for r in runs] render_output( @@ -505,7 +509,7 @@ def _wait_for_run( duration = _format_duration(int(elapsed)) if should_emit_json(is_json): - print_json(_format_run_info(run, project_names(client))) + print_json(_format_run_info(run, get_project_names_by_reference(client))) status = run.status summary_parts = [f"Run {run_id} {status.value} in {duration}"] diff --git a/src/datamasque_cli/commands/seeds.py b/src/datamasque_cli/commands/seeds.py index e188795..a03122d 100644 --- a/src/datamasque_cli/commands/seeds.py +++ b/src/datamasque_cli/commands/seeds.py @@ -11,9 +11,9 @@ from datamasque_cli.errors import confirm_or_abort from datamasque_cli.output import print_success, render_output from datamasque_cli.projects import ( - in_project, + filter_by_project, + get_project_names_by_reference, project_label, - project_names, require_single_or_abort, resolve_optional_project, resolve_target_project, @@ -32,7 +32,7 @@ def list_seeds( client = get_client(profile) target = resolve_optional_project(client, project) seeds = client.list_files_of_type(SeedFile, project=target.id if target else None) - names = project_names(client) + names = get_project_names_by_reference(client) data = [{"id": s.id, "project": project_label(names, s.project), "name": s.name} for s in seeds] render_output(data, is_json=is_json, columns=["id", "project", "name"], title="Seed Files") @@ -66,7 +66,7 @@ def delete_seed( client = get_client(profile) named = [seed for seed in client.list_files_of_type(SeedFile) if seed.name == filename] match = require_single_or_abort( - client, in_project(named, resolve_optional_project(client, project)), f"Seed file '{filename}'" + client, filter_by_project(named, resolve_optional_project(client, project)), f"Seed file '{filename}'" ) if not is_confirmed: diff --git a/src/datamasque_cli/commands/system.py b/src/datamasque_cli/commands/system.py index 8b0b058..f0c7fc6 100644 --- a/src/datamasque_cli/commands/system.py +++ b/src/datamasque_cli/commands/system.py @@ -78,7 +78,7 @@ def export_config( ) -> None: """Deprecated alias for `dm rulesets export-bundle`.""" print_warning("`dm system export` is deprecated; use `dm rulesets export-bundle` instead.") - export_bundle(output_path=output_path, profile=profile) + export_bundle(output_path=output_path, is_including_seed_files=False, profile=profile) @app.command("import", hidden=True, deprecated=True) diff --git a/src/datamasque_cli/commands/table_references.py b/src/datamasque_cli/commands/table_references.py index 6b185d0..cc55037 100644 --- a/src/datamasque_cli/commands/table_references.py +++ b/src/datamasque_cli/commands/table_references.py @@ -17,9 +17,9 @@ from datamasque_cli.output import print_success, render_output from datamasque_cli.projects import ( PROJECT_OPTION_HELP, - in_project, + filter_by_project, + get_project_names_by_reference, project_label, - project_names, require_single_or_abort, resolve_create_project, resolve_optional_project, @@ -69,7 +69,7 @@ def _get_or_abort(client: DataMasqueClient, name: str, project: str | None) -> T """Return the table reference named `name`, in `project` or in the one project that has it, else abort.""" named = [ref for ref in _list_or_abort(client) if ref.name == name] return require_single_or_abort( - client, in_project(named, resolve_optional_project(client, project)), f"Table reference '{name}'" + client, filter_by_project(named, resolve_optional_project(client, project)), f"Table reference '{name}'" ) @@ -81,8 +81,8 @@ def list_references( ) -> None: """List all table references, or those in one project.""" client = get_client(profile) - references = in_project(_list_or_abort(client), resolve_optional_project(client, project)) - names = project_names(client) + references = filter_by_project(_list_or_abort(client), resolve_optional_project(client, project)) + names = get_project_names_by_reference(client) data = [ { @@ -116,7 +116,7 @@ def get_reference( options = reference.options data: dict[str, object] = { "id": reference.id, - "project": project_label(project_names(client), reference.project), + "project": project_label(get_project_names_by_reference(client), reference.project), "name": reference.name, "connection": reference.connection_id, "source": reference.source, diff --git a/src/datamasque_cli/projects.py b/src/datamasque_cli/projects.py index 08d0705..afe0d7b 100644 --- a/src/datamasque_cli/projects.py +++ b/src/datamasque_cli/projects.py @@ -84,7 +84,7 @@ def resolve_create_project(client: DataMasqueClient, name_or_id: str | None, exi return target -def project_names(client: DataMasqueClient) -> dict[str, str]: +def get_project_names_by_reference(client: DataMasqueClient) -> dict[str, str]: """Map each project's `-` reference to its name, archived projects included.""" return {p.reference: p.name for p in client.list_projects(include_archived=True)} @@ -96,7 +96,7 @@ def project_label(names: dict[str, str], reference: str | None) -> str: return names.get(reference, reference) -def in_project(items: Sequence[ScopedT], project: Project | None) -> list[ScopedT]: +def filter_by_project(items: Sequence[ScopedT], project: Project | None) -> list[ScopedT]: """Keep the items in `project`, or all of them when `project` is `None`.""" if project is None: return list(items) @@ -120,7 +120,7 @@ def require_single_or_abort( if not matches: abort(f"{label} not found.", code=ErrorCode.NOT_FOUND) if len(matches) > 1: - names = project_names(client) + names = get_project_names_by_reference(client) options = "\n ".join( f"project={project_label(names, item.project)}" + (f" {describe(item)}" if describe else "") for item in matches diff --git a/tests/commands/test_discovery_config_libraries.py b/tests/commands/test_discovery_config_libraries.py index a36bfec..3556246 100644 --- a/tests/commands/test_discovery_config_libraries.py +++ b/tests/commands/test_discovery_config_libraries.py @@ -63,9 +63,9 @@ def test_list_shows_project_and_usage(mock_get_client: MagicMock, runner: CliRun result = runner.invoke(app, ["discover", "libraries", "list", "--json"]) assert result.exit_code == 0 - assert '"finance"' in result.stdout - assert '"project": "Org"' in result.stdout - assert '"used_by": 3' in result.stdout + assert json.loads(result.stdout) == [ + {"id": "lib-uuid", "project": "Org", "name": "finance", "valid": "valid", "used_by": 3} + ] @patch(f"{MODULE}.get_client") @@ -81,8 +81,9 @@ def test_list_project_keeps_only_that_projects_libraries(mock_get_client: MagicM result = runner.invoke(app, ["discover", "libraries", "list", "--project", "org", "--json"]) assert result.exit_code == 0 - assert '"payroll"' in result.stdout - assert '"finance"' not in result.stdout + assert json.loads(result.stdout) == [ + {"id": "org-lib", "project": "Org", "name": "payroll", "valid": "valid", "used_by": 0} + ] @patch(f"{MODULE}.get_client") @@ -144,7 +145,7 @@ def test_get_unknown_project_is_not_found(mock_get_client: MagicMock, runner: Cl result = runner.invoke(app, ["discover", "libraries", "get", "finance", "--project", "nope"]) assert result.exit_code == ExitCode.NOT_FOUND - assert "Project 'nope' not found" in result.stderr + assert result.stderr == "Error: Project 'nope' not found.\n" @patch(f"{MODULE}.get_client") diff --git a/tests/commands/test_discovery_configs.py b/tests/commands/test_discovery_configs.py index d94f5c9..0e85b71 100644 --- a/tests/commands/test_discovery_configs.py +++ b/tests/commands/test_discovery_configs.py @@ -177,7 +177,7 @@ def test_create_of_a_new_type_ignores_the_other_types_project( ) assert result.exit_code == ExitCode.AMBIGUOUS - assert "The instance has 2 active projects." in result.output + assert result.stderr == "Error: The instance has 2 active projects.\nHint: Pass --project to choose one.\n" client.create_or_update_discovery_config.assert_not_called() diff --git a/tests/commands/test_projects.py b/tests/commands/test_projects.py index eb95fcc..50a66de 100644 --- a/tests/commands/test_projects.py +++ b/tests/commands/test_projects.py @@ -42,7 +42,7 @@ def _api_error(status: HTTPStatus, detail: str) -> DataMasqueApiError: return DataMasqueApiError(detail, response=response) -def with_deleted_projects(client: MagicMock, *deleted: Project) -> None: +def _with_deleted_projects(client: MagicMock, *deleted: Project) -> None: """Make `list_projects` return `Default` and `Finance`, and the `deleted` projects first when they are included.""" client.list_projects.side_effect = lambda include_archived=False: ( [*deleted, DEFAULT, FINANCE] if include_archived else [DEFAULT, FINANCE] @@ -65,7 +65,7 @@ def test_list_shows_the_active_projects(client: MagicMock, runner: CliRunner) -> def test_list_include_deleted_marks_the_deleted_projects(client: MagicMock, runner: CliRunner) -> None: - with_deleted_projects(client, OLD) + _with_deleted_projects(client, OLD) result = runner.invoke(app, ["projects", "list", "--include-deleted", "--json"]) @@ -87,7 +87,7 @@ def test_get_finds_a_project_by_name_in_any_case_or_by_id(client: MagicMock, run def test_get_finds_a_deleted_project_by_id(client: MagicMock, runner: CliRunner) -> None: - with_deleted_projects(client, OLD) + _with_deleted_projects(client, OLD) result = runner.invoke(app, ["projects", "get", "3", "--json"]) @@ -99,7 +99,7 @@ def test_get_finds_a_deleted_project_by_id(client: MagicMock, runner: CliRunner) def test_get_by_name_finds_the_active_project_not_a_deleted_one_of_that_name( client: MagicMock, runner: CliRunner ) -> None: - with_deleted_projects(client, make_project(4, "Finance")) + _with_deleted_projects(client, make_project(4, "Finance")) result = runner.invoke(app, ["projects", "get", "finance", "--json"]) @@ -109,7 +109,7 @@ def test_get_by_name_finds_the_active_project_not_a_deleted_one_of_that_name( def test_get_of_an_unknown_id_is_not_found(client: MagicMock, runner: CliRunner) -> None: - with_deleted_projects(client, OLD) + _with_deleted_projects(client, OLD) result = runner.invoke(app, ["projects", "get", "99"]) diff --git a/tests/commands/test_resources.py b/tests/commands/test_resources.py index a0c31bd..1693384 100644 --- a/tests/commands/test_resources.py +++ b/tests/commands/test_resources.py @@ -83,6 +83,26 @@ def test_move_names_select_exact_names_only(client: MagicMock, runner: CliRunner client.move_resources.assert_called_once_with({ResourceTypeName.rulesets: [CUSTOMERS]}, DEFAULT) +def test_move_with_a_name_that_matches_nothing_moves_nothing_and_is_not_found( + client: MagicMock, runner: CliRunner +) -> None: + result = runner.invoke(app, ["resources", "move", "customers", "typo", "other", "--to", "default", "-y"]) + + assert result.exit_code == ExitCode.NOT_FOUND + assert result.stderr == ( + "Error: No resources named 'typo', 'other'.\n" + "Hint: Check the names, and that --project, --type and --search select them.\n" + ) + client.move_resources.assert_not_called() + + +def test_move_name_of_a_resource_that_cannot_move_is_not_reported_missing(client: MagicMock, runner: CliRunner) -> None: + result = runner.invoke(app, ["resources", "move", "first_names.csv", "--to", "default", "-y"]) + + assert result.exit_code == ExitCode.NOT_FOUND + assert result.stderr == "Error: No resources to move to 'Default'.\n" + + def test_move_without_any_selection_is_rejected_without_a_request(client: MagicMock, runner: CliRunner) -> None: result = runner.invoke(app, ["resources", "move", "--to", "default", "-y"]) diff --git a/tests/commands/test_rulesets.py b/tests/commands/test_rulesets.py index 90d18d5..b4feab8 100644 --- a/tests/commands/test_rulesets.py +++ b/tests/commands/test_rulesets.py @@ -7,6 +7,7 @@ import pytest from datamasque.client.exceptions import DataMasqueApiError +from datamasque.client.models.bundle import BundleImportResult from datamasque.client.models.ruleset import RulesetType from datamasque.client.models.status import ValidationErrorDetails, ValidationStatus from typer.testing import CliRunner @@ -164,7 +165,7 @@ def test_create_of_a_new_type_ignores_the_other_types_project( ) assert result.exit_code == ExitCode.AMBIGUOUS - assert "The instance has 2 active projects." in result.output + assert result.stderr == "Error: The instance has 2 active projects.\nHint: Pass --project to choose one.\n" client.create_or_update_ruleset.assert_not_called() @@ -412,20 +413,35 @@ def test_validate_nonterminal_status_reports_valid( # -- export-bundle / import-bundle ---------------------------------------- +def _make_bundle_import_result(*, fallback_project: str | None = None) -> BundleImportResult: + """Return an import result for a bundle with no items, whose items under no project went into `fallback_project`.""" + return BundleImportResult.model_validate( + { + "rulesets": {"metadata": {"processed": 0, "created": 0, "restored": 0, "error": 0}, "data": []}, + "fallback_project": fallback_project, + } + ) + + +@pytest.mark.parametrize(("seed_flags", "is_including_seed_files"), [([], False), (["--include-seed-files"], True)]) @patch(f"{MODULE}.get_client") -def test_export_bundle_writes_binary_zip(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: +def test_export_bundle_writes_the_zip_with_seed_files_only_on_request( + mock_get_client: MagicMock, + runner: CliRunner, + tmp_path: Path, + seed_flags: list[str], + is_including_seed_files: bool, +) -> None: client = with_projects(MagicMock()) mock_get_client.return_value = client - mock_response = MagicMock() - mock_response.content = b"PK\x03\x04fake-zip-bytes" - client.make_request.return_value = mock_response + client.export_bundle.return_value = b"PK\x03\x04fake-zip-bytes" output = tmp_path / "bundle.zip" - result = runner.invoke(app, ["rulesets", "export-bundle", "--output", str(output)]) + result = runner.invoke(app, ["rulesets", "export-bundle", "--output", str(output), *seed_flags]) assert result.exit_code == 0 assert output.read_bytes() == b"PK\x03\x04fake-zip-bytes" - client.make_request.assert_called_once_with("GET", "/api/export/v2/") + client.export_bundle.assert_called_once_with(include_seed_files=is_including_seed_files) @patch(f"{MODULE}.get_client") @@ -439,55 +455,40 @@ def test_import_bundle_requires_confirmation(mock_get_client: MagicMock, runner: result = runner.invoke(app, ["rulesets", "import-bundle", "--file", str(bundle)], input="n\n") assert result.exit_code == ExitCode.CANCELLED - client.make_request.assert_not_called() + client.import_bundle.assert_not_called() @patch(f"{MODULE}.get_client") -def test_import_bundle_uploads_zip_archive_as_multipart( +def test_import_bundle_passes_the_file_and_overwrite_options( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: client = with_projects(MagicMock()) mock_get_client.return_value = client - mock_response = MagicMock() - mock_response.content = b"" - client.make_request.return_value = mock_response + client.import_bundle.return_value = _make_bundle_import_result() bundle = tmp_path / "my-bundle.zip" bundle.write_bytes(b"PK\x03\x04zip-bytes") - result = runner.invoke( - app, - [ - "rulesets", - "import-bundle", - "--file", - str(bundle), - "--overwrite-rulesets", - "--yes", - ], - ) + result = runner.invoke(app, ["rulesets", "import-bundle", "--file", str(bundle), "--overwrite-rulesets", "--yes"]) assert result.exit_code == 0 - (call,) = client.make_request.call_args_list - assert call.args == ("POST", "/api/import/v2/") - assert call.kwargs["data"] == { - "overwrite_rulesets": "true", - "overwrite_libraries": "false", - "overwrite_seed_files": "false", - } - (upload,) = call.kwargs["files"] - assert upload.field_name == "zip_archive" - assert upload.filename == "my-bundle.zip" - assert upload.content_type == "application/zip" + client.import_bundle.assert_called_once_with( + bundle, + overwrite_rulesets=True, + overwrite_libraries=False, + overwrite_seed_files=False, + fallback_project=None, + ) @patch(f"{MODULE}.get_client") -def test_import_bundle_sends_the_fallback_project_id( +def test_import_bundle_sends_the_fallback_project( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: - client = with_projects(MagicMock(), make_project(), make_project(project_id=7, name="Bank")) + bank = make_project(project_id=7, name="Bank") + client = with_projects(MagicMock(), make_project(), bank) mock_get_client.return_value = client - client.make_request.return_value = MagicMock(content=b"", headers={}) + client.import_bundle.return_value = _make_bundle_import_result() bundle = tmp_path / "bundle.zip" bundle.write_bytes(b"PK\x03\x04") @@ -497,8 +498,7 @@ def test_import_bundle_sends_the_fallback_project_id( ) assert result.exit_code == 0 - (call,) = client.make_request.call_args_list - assert call.kwargs["data"]["fallback_project"] == "7" + assert client.import_bundle.call_args.kwargs["fallback_project"] == bank @patch(f"{MODULE}.get_client") @@ -516,16 +516,16 @@ def test_import_bundle_rejects_an_unknown_fallback_project( ) assert result.exit_code == ExitCode.NOT_FOUND - client.make_request.assert_not_called() + client.import_bundle.assert_not_called() @patch(f"{MODULE}.get_client") -def test_import_bundle_warns_about_an_older_bundle( +def test_import_bundle_names_the_project_that_took_items_under_no_project( mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path ) -> None: client = with_projects(MagicMock()) mock_get_client.return_value = client - client.make_request.return_value = MagicMock(content=b"", headers={"Deprecation": "true"}) + client.import_bundle.return_value = _make_bundle_import_result(fallback_project="Bank") bundle = tmp_path / "bundle.zip" bundle.write_bytes(b"PK\x03\x04") @@ -533,18 +533,16 @@ def test_import_bundle_warns_about_an_older_bundle( result = runner.invoke(app, ["rulesets", "import-bundle", "--file", str(bundle), "--yes"]) assert result.exit_code == 0 - assert "older format" in result.output - (call,) = client.make_request.call_args_list - assert "fallback_project" not in call.kwargs["data"] + assert " ".join(result.stderr.split()) == ( + "Bundle imported successfully. Items the bundle files under no project went into project 'Bank'." + ) @patch(f"{MODULE}.get_client") def test_system_export_alias_warns_and_delegates(mock_get_client: MagicMock, runner: CliRunner, tmp_path: Path) -> None: client = with_projects(MagicMock()) mock_get_client.return_value = client - mock_response = MagicMock() - mock_response.content = b"zip-body" - client.make_request.return_value = mock_response + client.export_bundle.return_value = b"zip-body" output = tmp_path / "export.zip" result = runner.invoke(app, ["system", "export", "--output", str(output)]) diff --git a/tests/test_projects.py b/tests/test_projects.py index 499a53e..a6d6d11 100644 --- a/tests/test_projects.py +++ b/tests/test_projects.py @@ -8,9 +8,9 @@ from datamasque_cli.errors import ExitCode from datamasque_cli.projects import ( - in_project, + filter_by_project, + get_project_names_by_reference, project_label, - project_names, require_single_or_abort, resolve_create_project, resolve_project, @@ -56,10 +56,10 @@ def test_resolve_target_project_needs_a_project_once_there_are_two() -> None: assert raised.value.code == ExitCode.AMBIGUOUS -def test_project_names_include_archived_projects() -> None: +def test_get_project_names_by_reference_includes_archived_projects() -> None: client = _client(DEFAULT, FINANCE) - assert project_names(client) == {"1-default": "Default", "2-finance": "Finance"} + assert get_project_names_by_reference(client) == {"1-default": "Default", "2-finance": "Finance"} client.list_projects.assert_called_once_with(include_archived=True) @@ -70,11 +70,11 @@ def test_project_label_names_the_project_and_leaves_a_built_in_blank() -> None: assert project_label(names, None) == "" -def test_in_project_keeps_only_that_projects_items() -> None: +def test_filter_by_project_keeps_only_that_projects_items() -> None: items = [SimpleNamespace(project="1-default"), SimpleNamespace(project="2-finance")] - assert in_project(items, FINANCE) == [items[1]] - assert in_project(items, None) == items + assert filter_by_project(items, FINANCE) == [items[1]] + assert filter_by_project(items, None) == items def test_require_single_returns_the_only_match() -> None: From 419fad157cff5cb986894e4ec3bfb94a11e9de82 Mon Sep 17 00:00:00 2001 From: jiatolentinoDM Date: Fri, 6 Nov 2026 10:41:26 +0800 Subject: [PATCH 09/11] fix: report a move with a conflict as nothing moved `move_resources` moves everything or nothing and raises `ResourceMoveConflictError`. `dm resources move` reports that nothing moved, and `--check` reports that no resources would move. Requires datamasque-python 1.7.0.dev12. --- README.md | 5 +++-- src/datamasque_cli/commands/resources.py | 21 ++++++++++----------- tests/commands/test_resources.py | 23 ++++++++--------------- 3 files changed, 21 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index bdb1867..aa67b4a 100644 --- a/README.md +++ b/README.md @@ -228,8 +228,9 @@ dm resources move --search payroll --to HR --check # Only list the ``` Resources move with their files and runs. `--project`, `--type`, `--search` and names combine; pass at least one. -A resource that clashes with the destination (same name, or a file in the way) stays where it is, the others move, -and the command exits with the `conflict` code, listing each one that stayed. +All of the resources move, or none do. A resource that clashes with the destination (same name, or a file in the way) +stops the move, and the command exits with the `conflict` code, listing each one. A resource already in the +destination stays there, and the others move. ### In-flight masking diff --git a/src/datamasque_cli/commands/resources.py b/src/datamasque_cli/commands/resources.py index 7d1ab27..ef0c818 100644 --- a/src/datamasque_cli/commands/resources.py +++ b/src/datamasque_cli/commands/resources.py @@ -4,7 +4,7 @@ import typer from datamasque.client import DataMasqueClient -from datamasque.client.exceptions import DataMasqueApiError +from datamasque.client.exceptions import DataMasqueApiError, ResourceMoveConflictError from datamasque.client.models.project import Project from datamasque.client.models.resource import Resource, ResourceMoveConflict from datamasque.client.models.resource_type import ResourceTypeName @@ -16,8 +16,7 @@ app = typer.Typer(help="Work with resources of every type.", no_args_is_help=True) -MOVE_CONFLICT_MESSAGE = "Some resources did not move" -MOVE_CHECK_CONFLICT_MESSAGE = "Some resources would not move" +MOVE_CHECK_CONFLICT_MESSAGE = "No resources would move" def _describe_resource_count(count: int) -> str: @@ -85,7 +84,8 @@ def move_resources( Move resources to another project, with their files and runs. Select them by project, type, a name search or exact names; the filters combine. - A resource that clashes with the destination stays where it is, and the others move. + All of them move, or none do: a resource that clashes with the destination stops the move. + A resource already in the destination stays there, and the others move. Rulesets and configurations whose library imports resolve differently after the move become invalid. """ if not (names or sources or type_names or search): @@ -139,14 +139,13 @@ def move_resources( try: result = client.move_resources(selected, target) + except ResourceMoveConflictError as exc: + abort( + f"No resources moved to '{target.name}'", + code=ErrorCode.CONFLICT, + details=_get_conflict_details(exc.conflicts), + ) except DataMasqueApiError as exc: abort_api_error(f"Failed to move resources to '{target.name}'", exc) - if result.conflicts: - message = ( - f"{MOVE_CONFLICT_MESSAGE}; {result.moved} moved to '{target.name}'" - if result.moved - else f"No resources moved to '{target.name}'" - ) - abort(message, code=ErrorCode.CONFLICT, details=_get_conflict_details(result.conflicts)) print_success(f"Moved {_describe_resource_count(result.moved)} to '{target.name}'.") diff --git a/tests/commands/test_resources.py b/tests/commands/test_resources.py index 1693384..e4e9e61 100644 --- a/tests/commands/test_resources.py +++ b/tests/commands/test_resources.py @@ -4,6 +4,7 @@ from unittest.mock import MagicMock, patch import pytest +from datamasque.client.exceptions import ResourceMoveConflictError from datamasque.client.models.resource import ( Resource, ResourceMoveConflict, @@ -43,7 +44,7 @@ def client() -> Iterator[MagicMock]: ResourceTypeName.rulesets: [CUSTOMERS, ORDERS, ALREADY_THERE], ResourceTypeName.seeds: [BUILT_IN_SEED], } - client.move_resources.return_value = ResourceMoveResult(moved=2, conflicts=[]) + client.move_resources.return_value = ResourceMoveResult(moved=2) with patch(f"{MODULE}.get_client", return_value=client): yield client @@ -126,20 +127,12 @@ def test_move_with_nothing_outside_the_destination_is_not_found(client: MagicMoc client.move_resources.assert_not_called() -def test_move_that_leaves_resources_behind_names_them_and_fails(client: MagicMock, runner: CliRunner) -> None: - client.move_resources.return_value = ResourceMoveResult(moved=1, conflicts=[CUSTOMERS_CLASH]) - - result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default", "-y"]) - - assert result.exit_code == ExitCode.CONFLICT - assert result.stderr == ( - "Error: Some resources did not move; 1 moved to 'Default':\n Ruleset \"customers\" exists.\n" +def test_move_with_a_conflict_says_none_moved_and_names_it(client: MagicMock, runner: CliRunner) -> None: + response = MagicMock(status_code=409) + client.move_resources.side_effect = ResourceMoveConflictError( + "No resources moved.", response=response, conflicts=[CUSTOMERS_CLASH] ) - -def test_move_that_moves_nothing_says_none_moved(client: MagicMock, runner: CliRunner) -> None: - client.move_resources.return_value = ResourceMoveResult(moved=0, conflicts=[CUSTOMERS_CLASH]) - result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default", "-y"]) assert result.exit_code == ExitCode.CONFLICT @@ -153,7 +146,7 @@ def test_move_lists_a_detail_shared_by_several_conflicts_once(client: MagicMock, result = runner.invoke(app, ["resources", "move", "--project", "finance", "--to", "default", "--check"]) assert result.exit_code == ExitCode.CONFLICT - assert result.stderr == 'Error: Some resources would not move:\n Ruleset "customers" exists.\n' + assert result.stderr == 'Error: No resources would move:\n Ruleset "customers" exists.\n' def test_move_declined_at_the_prompt_moves_nothing(client: MagicMock, runner: CliRunner) -> None: @@ -170,7 +163,7 @@ def test_move_declined_at_the_prompt_moves_nothing(client: MagicMock, runner: Cl ( [CUSTOMERS_CLASH], ExitCode.CONFLICT, - 'Error: Some resources would not move:\n Ruleset "customers" exists.\n', + 'Error: No resources would move:\n Ruleset "customers" exists.\n', ), ], ids=["no-conflicts", "conflict"], From d90bf877e3cc2fa5a2ecb8e62f10065edcd68b70 Mon Sep 17 00:00:00 2001 From: jiatolentinoDM Date: Wed, 4 Nov 2026 11:50:03 +0800 Subject: [PATCH 10/11] refactor: build the --project help strings from PROJECT_OPTION_HELP The commands that find a resource by a name that two projects can share take their --project help from get_same_name_project_help, and the seed list and bundle import help start from the constant too. The help text is unchanged. --- src/datamasque_cli/commands/connections.py | 17 +++++------------ .../commands/discovery_configs.py | 13 ++++--------- src/datamasque_cli/commands/files.py | 5 ++--- src/datamasque_cli/commands/rulesets.py | 15 +++++---------- src/datamasque_cli/commands/seeds.py | 8 ++++---- src/datamasque_cli/commands/table_references.py | 13 ++++--------- src/datamasque_cli/projects.py | 5 +++++ 7 files changed, 29 insertions(+), 47 deletions(-) diff --git a/src/datamasque_cli/commands/connections.py b/src/datamasque_cli/commands/connections.py index 23e2a18..4291035 100644 --- a/src/datamasque_cli/commands/connections.py +++ b/src/datamasque_cli/commands/connections.py @@ -30,6 +30,7 @@ PROJECT_OPTION_HELP, filter_by_project, get_project_names_by_reference, + get_same_name_project_help, project_label, resolve_create_project, resolve_optional_project, @@ -132,9 +133,7 @@ def list_connections( @app.command("get") def get_connection( name: str = typer.Argument(help="Connection name or ID"), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when connections in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("connections")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: @@ -308,9 +307,7 @@ def _build_connection_config( @app.command("test") def test_connection( name: str = typer.Argument(help="Connection name or ID to test"), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when connections in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("connections")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Verify a connection can reach its target. @@ -338,9 +335,7 @@ def test_connection( @app.command("update") def update_connection( name: str = typer.Argument(help="Connection name or ID to update"), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when connections in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("connections")), host: str | None = typer.Option(None, help="New database host"), port: str | None = typer.Option(None, help="New database port"), database: str | None = typer.Option(None, help="New database name"), @@ -386,9 +381,7 @@ def update_connection( @app.command("delete") def delete_connection( name: str = typer.Argument(help="Connection name or ID to delete"), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when connections in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("connections")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: diff --git a/src/datamasque_cli/commands/discovery_configs.py b/src/datamasque_cli/commands/discovery_configs.py index 047b5aa..aca2d59 100644 --- a/src/datamasque_cli/commands/discovery_configs.py +++ b/src/datamasque_cli/commands/discovery_configs.py @@ -30,6 +30,7 @@ PROJECT_OPTION_HELP, filter_by_project, get_project_names_by_reference, + get_same_name_project_help, project_label, resolve_create_project, resolve_optional_project, @@ -108,9 +109,7 @@ def get_config( config_type: DiscoveryConfigType | None = typer.Option( None, "--type", "-t", help="Required when two configs share a name" ), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when configs in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("configs")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_yaml: bool = typer.Option(False, "--yaml", help="Output raw YAML content only"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), @@ -222,9 +221,7 @@ def delete_config( config_type: DiscoveryConfigType | None = typer.Option( None, "--type", "-t", help="Required when two configs share a name" ), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when configs in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("configs")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: @@ -296,9 +293,7 @@ def show_config_status( config_type: DiscoveryConfigType | None = typer.Option( None, "--type", "-t", help="Required when two configs share a name" ), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when configs in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("configs")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: diff --git a/src/datamasque_cli/commands/files.py b/src/datamasque_cli/commands/files.py index 0502e9c..7928d30 100644 --- a/src/datamasque_cli/commands/files.py +++ b/src/datamasque_cli/commands/files.py @@ -14,6 +14,7 @@ PROJECT_OPTION_HELP, filter_by_project, get_project_names_by_reference, + get_same_name_project_help, project_label, require_single_or_abort, resolve_optional_project, @@ -58,9 +59,7 @@ def list_files( def delete_file( file_type: str = typer.Argument(help="File type: snowflake-key"), name: str = typer.Argument(help="File name"), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when files in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("files")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: diff --git a/src/datamasque_cli/commands/rulesets.py b/src/datamasque_cli/commands/rulesets.py index b9805cd..2a19637 100644 --- a/src/datamasque_cli/commands/rulesets.py +++ b/src/datamasque_cli/commands/rulesets.py @@ -34,6 +34,7 @@ PROJECT_OPTION_HELP, filter_by_project, get_project_names_by_reference, + get_same_name_project_help, project_label, resolve_create_project, resolve_optional_project, @@ -111,9 +112,7 @@ def get_ruleset( ruleset_type: RulesetType | None = typer.Option( None, "--type", "-t", help="Required when two rulesets share a name" ), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when rulesets in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("rulesets")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_yaml: bool = typer.Option(False, "--yaml", help="Output raw YAML content only"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), @@ -203,9 +202,7 @@ def delete_ruleset( ruleset_type: RulesetType | None = typer.Option( None, "--type", "-t", help="Required when two rulesets share a name" ), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when rulesets in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("rulesets")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: @@ -314,7 +311,7 @@ def import_bundle( fallback_project: str | None = typer.Option( None, "--fallback-project", - help="Project name or id for the items the bundle files under no project. " + help=f"{PROJECT_OPTION_HELP} for the items the bundle files under no project. " "Defaults to the server's default project.", ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), @@ -360,9 +357,7 @@ def show_ruleset_status( ruleset_type: RulesetType | None = typer.Option( None, "--type", "-t", help="Required when two rulesets share a name" ), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when rulesets in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("rulesets")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: diff --git a/src/datamasque_cli/commands/seeds.py b/src/datamasque_cli/commands/seeds.py index a03122d..22862e5 100644 --- a/src/datamasque_cli/commands/seeds.py +++ b/src/datamasque_cli/commands/seeds.py @@ -11,8 +11,10 @@ from datamasque_cli.errors import confirm_or_abort from datamasque_cli.output import print_success, render_output from datamasque_cli.projects import ( + PROJECT_OPTION_HELP, filter_by_project, get_project_names_by_reference, + get_same_name_project_help, project_label, require_single_or_abort, resolve_optional_project, @@ -24,7 +26,7 @@ @app.command("list") def list_seeds( - project: str | None = typer.Option(None, "--project", help="Project name or id; also lists the built-in seeds"), + project: str | None = typer.Option(None, "--project", help=f"{PROJECT_OPTION_HELP}; also lists the built-in seeds"), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: @@ -56,9 +58,7 @@ def upload_seed( @app.command("delete") def delete_seed( filename: str = typer.Argument(help="Seed filename to delete"), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when seeds in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("seeds")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: diff --git a/src/datamasque_cli/commands/table_references.py b/src/datamasque_cli/commands/table_references.py index cc55037..d558bfc 100644 --- a/src/datamasque_cli/commands/table_references.py +++ b/src/datamasque_cli/commands/table_references.py @@ -19,6 +19,7 @@ PROJECT_OPTION_HELP, filter_by_project, get_project_names_by_reference, + get_same_name_project_help, project_label, require_single_or_abort, resolve_create_project, @@ -103,9 +104,7 @@ def list_references( @app.command("get") def get_reference( name: str = typer.Argument(help="Table reference name"), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when references in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("references")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), ) -> None: @@ -261,9 +260,7 @@ def update_reference( encoding: str | None = typer.Option(None, help=f"New CSV encoding {_CSV_OPTION_HELP}"), quotechar: str | None = typer.Option(None, help=f"New CSV quote character {_CSV_OPTION_HELP}"), null_string: str | None = typer.Option(None, help=f"New null-string value {_CSV_OPTION_HELP}"), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when references in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("references")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Update selected fields on an existing table reference, preserving its ID.""" @@ -295,9 +292,7 @@ def update_reference( @app.command("delete") def delete_reference( name: str = typer.Argument(help="Table reference name to delete"), - project: str | None = typer.Option( - None, "--project", help="Project name or id; required when references in two projects share a name" - ), + project: str | None = typer.Option(None, "--project", help=get_same_name_project_help("references")), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: diff --git a/src/datamasque_cli/projects.py b/src/datamasque_cli/projects.py index afe0d7b..4707164 100644 --- a/src/datamasque_cli/projects.py +++ b/src/datamasque_cli/projects.py @@ -13,6 +13,11 @@ PROJECT_OPTION_HELP = "Project name or id" +def get_same_name_project_help(resources: str) -> str: + """Return the `--project` help for a command that finds `resources` by a name more than one project can hold.""" + return f"{PROJECT_OPTION_HELP}; required when {resources} in two projects share a name" + + class ProjectScoped(Protocol): """A resource that records its project as an `-` reference.""" From 6b6fca5800dc9dac6d276783f316b81f25d199e8 Mon Sep 17 00:00:00 2001 From: Elliot Simpson Date: Fri, 20 Nov 2026 14:16:21 +1300 Subject: [PATCH 11/11] fix: address review: v3.26.22.0, move wording, shared help strings and clearer names --- README.md | 2 +- .../skills/datamasque-cli/SKILL.md | 3 ++- src/datamasque_cli/commands/discovery.py | 23 +++++++++++-------- .../commands/discovery_config_libraries.py | 12 ++++------ .../commands/discovery_configs.py | 5 ++-- src/datamasque_cli/commands/files.py | 11 +++++---- src/datamasque_cli/commands/resources.py | 20 ++++++++-------- .../commands/ruleset_libraries.py | 14 +++++------ src/datamasque_cli/commands/rulesets.py | 5 ++-- src/datamasque_cli/commands/runs.py | 3 ++- src/datamasque_cli/commands/seeds.py | 9 ++++---- .../commands/table_references.py | 14 +++++++---- src/datamasque_cli/projects.py | 14 +++++++++++ tests/commands/test_project_options.py | 3 +-- 14 files changed, 78 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index aa67b4a..f28ccf1 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ or set `DATAMASQUE_VERIFY_SSL=false` to skip verification per call. ## Projects Every connection, ruleset, library, discovery config, seed, file and table reference belongs to one project. -This CLI needs a DataMasque version with projects (v3.26.21.0 or later); use an earlier CLI release with older versions. +This CLI needs a DataMasque version with projects (v3.26.22.0 or later); use an earlier CLI release with older versions. - `--project` takes a project name (any case) or its numeric ID. - List commands show each resource's project, and `--project` lists only that project's resources diff --git a/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md b/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md index 1088c14..6495103 100644 --- a/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md +++ b/claude-skills/datamasque-cli/skills/datamasque-cli/SKILL.md @@ -71,7 +71,8 @@ Pass repeated `--options key=value` for server-side knobs `dm projects` creates, renames and deletes projects (delete needs `--to`, the project that takes its resources). `dm resources move --to ` moves resources selected by `--project`, `--type`, `--search` or exact names; it - exits `conflict` when any stayed behind. Add `--check` to only preview. + moves nothing and exits `conflict` when any of them clashes with the + destination. Add `--check` to only preview. - **File masking needs a destination.** Database masking is in-place; file masking writes through to a destination connection and fails diff --git a/src/datamasque_cli/commands/discovery.py b/src/datamasque_cli/commands/discovery.py index 84d7585..61beb36 100644 --- a/src/datamasque_cli/commands/discovery.py +++ b/src/datamasque_cli/commands/discovery.py @@ -34,7 +34,12 @@ ) from datamasque_cli.fileio import write_bytes_or_abort, write_text_or_abort from datamasque_cli.output import print_info, print_json, print_success, render_output, should_emit_json -from datamasque_cli.projects import filter_by_project, require_single_or_abort, resolve_optional_project +from datamasque_cli.projects import ( + filter_by_project, + get_named_resources_project_help, + require_single_or_abort, + resolve_optional_project, +) app = typer.Typer(help="Data discovery operations.", no_args_is_help=True) app.add_typer(discovery_configs.app, name="configs") @@ -87,16 +92,16 @@ def _resolve_discovery_config_id( Config names are unique per type within a project, so name, type and project identify at most one config. """ - named = filter_by_project( + named_configs = filter_by_project( [c for c in client.list_discovery_configs() if c.name == name], resolve_optional_project(client, project) ) - of_type = [c for c in named if c.config_type is expected_type] - if of_type: - match = require_single_or_abort(client, of_type, f"Discovery config '{name}'") + configs_of_type = [c for c in named_configs if c.config_type is expected_type] + if configs_of_type: + match = require_single_or_abort(client, configs_of_type, f"Discovery config '{name}'") return require_id_or_abort(match.id, f"discovery config '{name}'") - if named: - other_type = named[0].config_type + if named_configs: + other_type = named_configs[0].config_type abort( f"Discovery config '{name}' exists as {other_type.value}, " f"but {expected_type.value} discovery needs a {expected_type.value} config.", @@ -112,7 +117,7 @@ def schema_discovery( None, "--config", "-c", help="Run with a saved database discovery config (configurable discovery)" ), project: str | None = typer.Option( - None, "--project", help="Project of the connection and config, when their names exist in more than one" + None, "--project", help=get_named_resources_project_help("connection and config") ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), @@ -158,7 +163,7 @@ def start_file_discovery( None, "--config", "-c", help="Run with a saved file discovery config (configurable discovery)" ), project: str | None = typer.Option( - None, "--project", help="Project of the connection and config, when their names exist in more than one" + None, "--project", help=get_named_resources_project_help("connection and config") ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), diff --git a/src/datamasque_cli/commands/discovery_config_libraries.py b/src/datamasque_cli/commands/discovery_config_libraries.py index 9da3448..4c6b8de 100644 --- a/src/datamasque_cli/commands/discovery_config_libraries.py +++ b/src/datamasque_cli/commands/discovery_config_libraries.py @@ -17,6 +17,7 @@ from datamasque_cli.output import print_success, print_warning, render_output from datamasque_cli.projects import ( PROJECT_OPTION_HELP, + PROJECT_VALIDATE_HELP, filter_by_project, get_project_names_by_reference, project_label, @@ -127,32 +128,29 @@ def delete_library( If the library is imported by any discovery configs, the server rejects the delete unless --force is passed. """ - label = name client = get_client(profile) lib = _find_library(client, name, project) if not is_confirmed: - confirm_or_abort(f"Delete discovery config library '{label}'?") + confirm_or_abort(f"Delete discovery config library '{name}'?") try: client.delete_discovery_config_library_by_id_if_exists(lib.id, force=force) except DataMasqueApiError as exc: abort_api_error( - f"Failed to delete discovery config library '{label}'", + f"Failed to delete discovery config library '{name}'", exc, conflict_hint="Re-run with --force to delete it and mark the dependent configs invalid.", ) - print_success(f"Discovery config library '{label}' deleted.") + print_success(f"Discovery config library '{name}' deleted.") @app.command("validate") def validate_library( file: Path = typer.Option(..., "--file", "-f", help="Path to YAML library file", exists=True, readable=True), - project: str | None = typer.Option( - None, "--project", help="Project to validate in; required when the instance has more than one" - ), + project: str | None = typer.Option(None, "--project", help=PROJECT_VALIDATE_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Validate a discovery config library YAML file against the DataMasque server. diff --git a/src/datamasque_cli/commands/discovery_configs.py b/src/datamasque_cli/commands/discovery_configs.py index aca2d59..55d0c4b 100644 --- a/src/datamasque_cli/commands/discovery_configs.py +++ b/src/datamasque_cli/commands/discovery_configs.py @@ -28,6 +28,7 @@ from datamasque_cli.output import print_info, print_success, print_warning, render_output from datamasque_cli.projects import ( PROJECT_OPTION_HELP, + PROJECT_VALIDATE_HELP, filter_by_project, get_project_names_by_reference, get_same_name_project_help, @@ -241,9 +242,7 @@ def delete_config( def validate_config( file: Path = typer.Option(..., "--file", "-f", help="Path to YAML config file", exists=True, readable=True), config_type: DiscoveryConfigType = typer.Option(..., "--type", "-t", help="Config type: database or file"), - project: str | None = typer.Option( - None, "--project", help="Project to validate in; required when the instance has more than one" - ), + project: str | None = typer.Option(None, "--project", help=PROJECT_VALIDATE_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Validate a discovery config YAML file against the DataMasque server. diff --git a/src/datamasque_cli/commands/files.py b/src/datamasque_cli/commands/files.py index 7928d30..6d29485 100644 --- a/src/datamasque_cli/commands/files.py +++ b/src/datamasque_cli/commands/files.py @@ -12,6 +12,7 @@ from datamasque_cli.output import print_success, render_output from datamasque_cli.projects import ( PROJECT_OPTION_HELP, + PROJECT_UPLOAD_HELP, filter_by_project, get_project_names_by_reference, get_same_name_project_help, @@ -67,9 +68,11 @@ def delete_file( klass = _resolve_file_type(file_type) client = get_client(profile) - named = [f for f in client.list_files_of_type(klass) if f.name == name] + named_files = [f for f in client.list_files_of_type(klass) if f.name == name] match = require_single_or_abort( - client, filter_by_project(named, resolve_optional_project(client, project)), f"File '{name}' ({file_type})" + client, + filter_by_project(named_files, resolve_optional_project(client, project)), + f"File '{name}' ({file_type})", ) if not is_confirmed: @@ -84,9 +87,7 @@ def upload_file( file_type: str = typer.Argument(help="File type: snowflake-key"), file: Path = typer.Option(..., "--file", "-f", help="Path to file", exists=True, readable=True), name: str = typer.Option(..., help="Name for the uploaded file"), - project: str | None = typer.Option( - None, "--project", help="Project to upload to; required when the instance has more than one" - ), + project: str | None = typer.Option(None, "--project", help=PROJECT_UPLOAD_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Upload a file.""" diff --git a/src/datamasque_cli/commands/resources.py b/src/datamasque_cli/commands/resources.py index ef0c818..7c5f225 100644 --- a/src/datamasque_cli/commands/resources.py +++ b/src/datamasque_cli/commands/resources.py @@ -43,23 +43,23 @@ def _get_resources_to_move( Built-in seeds belong to no project and cannot move, so they are left out too. Aborts with not-found when a name matches none of the resources the other filters select. """ - listed = client.list_resources(projects=sources, types=type_names, search=search) - listed_names = {resource.name for resources in listed.values() for resource in resources} + listed_resources = client.list_resources(projects=sources, types=type_names, search=search) + listed_names = {resource.name for resources in listed_resources.values() for resource in resources} if unmatched_names := [name for name in dict.fromkeys(names) if name not in listed_names]: abort( f"No resources named {', '.join(repr(name) for name in unmatched_names)}.", code=ErrorCode.NOT_FOUND, hint="Check the names, and that --project, --type and --search select them.", ) - selected = { + selected_resources = { type_name: [ resource for resource in resources if resource.project not in (None, destination.reference) and (not names or resource.name in names) ] - for type_name, resources in listed.items() + for type_name, resources in listed_resources.items() } - return {type_name: resources for type_name, resources in selected.items() if resources} + return {type_name: resources for type_name, resources in selected_resources.items() if resources} @app.command("move") @@ -98,7 +98,7 @@ def move_resources( client = get_client(profile) projects = client.list_projects() target = get_named_project(projects, destination) - selected = _get_resources_to_move( + resources_to_move = _get_resources_to_move( client, names=names or [], sources=[get_named_project(projects, source) for source in sources] if sources else None, @@ -106,7 +106,7 @@ def move_resources( search=search, destination=target, ) - if not selected: + if not resources_to_move: abort(f"No resources to move to '{target.name}'.", code=ErrorCode.NOT_FOUND) # The selection leaves out resources in no project, and a deleted project has no resources left. @@ -117,7 +117,7 @@ def move_resources( "name": resource.name, "project": project_label(project_names_by_reference, resource.project), } - for type_name, resources in selected.items() + for type_name, resources in resources_to_move.items() for resource in resources ] render_output( @@ -126,7 +126,7 @@ def move_resources( if is_check_only: try: - conflicts = client.get_resource_move_conflicts(selected, target) + conflicts = client.get_resource_move_conflicts(resources_to_move, target) except DataMasqueApiError as exc: abort_api_error("Failed to check the move", exc) if conflicts: @@ -138,7 +138,7 @@ def move_resources( confirm_or_abort(f"Move {_describe_resource_count(len(rows))} to '{target.name}'?") try: - result = client.move_resources(selected, target) + result = client.move_resources(resources_to_move, target) except ResourceMoveConflictError as exc: abort( f"No resources moved to '{target.name}'", diff --git a/src/datamasque_cli/commands/ruleset_libraries.py b/src/datamasque_cli/commands/ruleset_libraries.py index c6cebcc..a8ff74d 100644 --- a/src/datamasque_cli/commands/ruleset_libraries.py +++ b/src/datamasque_cli/commands/ruleset_libraries.py @@ -112,24 +112,23 @@ def delete_library( is_confirmed: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation"), ) -> None: """Delete a ruleset library by name.""" - label = name client = get_client(profile) lib = _find_library(client, name, project) if not is_confirmed: - confirm_or_abort(f"Delete library '{label}'?") + confirm_or_abort(f"Delete library '{name}'?") try: client.delete_ruleset_library_by_id_if_exists(lib.id, force=force) except DataMasqueApiError as exc: abort_api_error( - f"Failed to delete library '{label}'", + f"Failed to delete library '{name}'", exc, conflict_hint="Re-run with --force to delete it and flag the dependent rulesets for revalidation.", ) - print_success(f"Library '{label}' deleted.") + print_success(f"Library '{name}' deleted.") @app.command("validate") @@ -142,7 +141,6 @@ def validate_library( Triggers a server-side validation pass on an existing library and reports the result. """ - label = name client = get_client(profile) lib = _find_library(client, name, project) @@ -150,11 +148,11 @@ def validate_library( try: validated = client.validate_ruleset_library(lib.id) except DataMasqueApiError as exc: - abort_api_error(f"Failed to validate library '{label}'", exc) - abort_if_invalid(f"Library '{label}'", validated.is_valid, validated.validation_errors) + abort_api_error(f"Failed to validate library '{name}'", exc) + abort_if_invalid(f"Library '{name}'", validated.is_valid, validated.validation_errors) status = validated.is_valid.value if validated.is_valid else "unknown" - print_success(f"Library '{label}' validation status: {status}") + print_success(f"Library '{name}' validation status: {status}") @app.command("status") diff --git a/src/datamasque_cli/commands/rulesets.py b/src/datamasque_cli/commands/rulesets.py index 2a19637..5e87e67 100644 --- a/src/datamasque_cli/commands/rulesets.py +++ b/src/datamasque_cli/commands/rulesets.py @@ -32,6 +32,7 @@ from datamasque_cli.output import print_info, print_success, print_warning, render_output, should_emit_json from datamasque_cli.projects import ( PROJECT_OPTION_HELP, + PROJECT_VALIDATE_HELP, filter_by_project, get_project_names_by_reference, get_same_name_project_help, @@ -227,9 +228,7 @@ def validate_ruleset( "-t", help="Ruleset type: database or file", ), - project: str | None = typer.Option( - None, "--project", help="Project to validate in; required when the instance has more than one" - ), + project: str | None = typer.Option(None, "--project", help=PROJECT_VALIDATE_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Validate a ruleset YAML file against the DataMasque server. diff --git a/src/datamasque_cli/commands/runs.py b/src/datamasque_cli/commands/runs.py index e78c128..098cf87 100644 --- a/src/datamasque_cli/commands/runs.py +++ b/src/datamasque_cli/commands/runs.py @@ -29,6 +29,7 @@ from datamasque_cli.projects import ( PROJECT_OPTION_HELP, filter_by_project, + get_named_resources_project_help, get_project_names_by_reference, project_label, resolve_optional_project, @@ -194,7 +195,7 @@ def start_run( False, "--background", "-b", help="Return immediately without waiting for completion" ), project: str | None = typer.Option( - None, "--project", help="Project of the ruleset and connections, when their names exist in more than one" + None, "--project", help=get_named_resources_project_help("ruleset and connections") ), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), is_json: bool = typer.Option(False, "--json", help="Output as JSON"), diff --git a/src/datamasque_cli/commands/seeds.py b/src/datamasque_cli/commands/seeds.py index 22862e5..5f0a639 100644 --- a/src/datamasque_cli/commands/seeds.py +++ b/src/datamasque_cli/commands/seeds.py @@ -12,6 +12,7 @@ from datamasque_cli.output import print_success, render_output from datamasque_cli.projects import ( PROJECT_OPTION_HELP, + PROJECT_UPLOAD_HELP, filter_by_project, get_project_names_by_reference, get_same_name_project_help, @@ -43,9 +44,7 @@ def list_seeds( @app.command("upload") def upload_seed( file: Path = typer.Argument(help="Path to seed file", exists=True, readable=True), - project: str | None = typer.Option( - None, "--project", help="Project to upload to; required when the instance has more than one" - ), + project: str | None = typer.Option(None, "--project", help=PROJECT_UPLOAD_HELP), profile: str | None = typer.Option(None, "--profile", "-p", help="Profile to use"), ) -> None: """Upload a seed file.""" @@ -64,9 +63,9 @@ def delete_seed( ) -> None: """Delete a seed file by filename.""" client = get_client(profile) - named = [seed for seed in client.list_files_of_type(SeedFile) if seed.name == filename] + named_seeds = [seed for seed in client.list_files_of_type(SeedFile) if seed.name == filename] match = require_single_or_abort( - client, filter_by_project(named, resolve_optional_project(client, project)), f"Seed file '{filename}'" + client, filter_by_project(named_seeds, resolve_optional_project(client, project)), f"Seed file '{filename}'" ) if not is_confirmed: diff --git a/src/datamasque_cli/commands/table_references.py b/src/datamasque_cli/commands/table_references.py index d558bfc..05061af 100644 --- a/src/datamasque_cli/commands/table_references.py +++ b/src/datamasque_cli/commands/table_references.py @@ -68,9 +68,11 @@ def _list_or_abort(client: DataMasqueClient) -> list[TableReference]: def _get_or_abort(client: DataMasqueClient, name: str, project: str | None) -> TableReference: """Return the table reference named `name`, in `project` or in the one project that has it, else abort.""" - named = [ref for ref in _list_or_abort(client) if ref.name == name] + named_references = [ref for ref in _list_or_abort(client) if ref.name == name] return require_single_or_abort( - client, filter_by_project(named, resolve_optional_project(client, project)), f"Table reference '{name}'" + client, + filter_by_project(named_references, resolve_optional_project(client, project)), + f"Table reference '{name}'", ) @@ -140,9 +142,11 @@ def _resolve_connection_id( so a name that other projects share needs no `--project`. Otherwise every project is searched. """ if project is None: - own = [c for c in client.list_connections() if c.name == name_or_id and c.project == reference_project] - if own: - return own[0].id + own_project_connections = [ + c for c in client.list_connections() if c.name == name_or_id and c.project == reference_project + ] + if own_project_connections: + return own_project_connections[0].id return resolve_connection(client, name_or_id, project).id diff --git a/src/datamasque_cli/projects.py b/src/datamasque_cli/projects.py index 4707164..9132cd0 100644 --- a/src/datamasque_cli/projects.py +++ b/src/datamasque_cli/projects.py @@ -18,6 +18,20 @@ def get_same_name_project_help(resources: str) -> str: return f"{PROJECT_OPTION_HELP}; required when {resources} in two projects share a name" +def get_only_project_help(action: str) -> str: + """Return the `--project` help for a command that `action`s into one project, the only one when omitted.""" + return f"Project to {action}; required when the instance has more than one" + + +def get_named_resources_project_help(resources: str) -> str: + """Return the `--project` help for a command that finds several `resources` by names more than one project can hold.""" + return f"Project of the {resources}, when their names exist in more than one" + + +PROJECT_UPLOAD_HELP = get_only_project_help("upload to") +PROJECT_VALIDATE_HELP = get_only_project_help("validate in") + + class ProjectScoped(Protocol): """A resource that records its project as an `-` reference.""" diff --git a/tests/commands/test_project_options.py b/tests/commands/test_project_options.py index 1da3d06..704c4eb 100644 --- a/tests/commands/test_project_options.py +++ b/tests/commands/test_project_options.py @@ -257,8 +257,7 @@ def test_runs_list_project_is_filtered_on_the_server(mock_get_client: MagicMock, result = runner.invoke(app, ["run", "list", "--project", "Finance", "--json"]) assert result.exit_code == 0 - query = client.make_request.call_args.args[1] - assert "project=2" in query + client.make_request.assert_called_once_with("GET", "/api/runs/?project=2&limit=20") assert json.loads(result.stdout)[0]["project"] == "Finance"