From ad6235985c153d0f0dc5376dac7b2652fc0267bb Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 10:34:00 +0000 Subject: [PATCH 1/8] feat(cli): add uipath resources and derive bindings.json from uipath_resources.py (PC-5725) Coded agents and Python functions declare the platform resources they use in one file, uipath_resources.py, and bindings.json is derived from it instead of written by hand. - uipath.resources (uipath-platform): `resource.(...)` returns a frozen data handle (kind, name, folder_path, type; a connection's id and connector; a skill bundle's version). One method per kind the SDK can override, taken from the overwrite models in _bindings.py; a test keeps them in step. - `uipath resources add | list | remove | bindings`: edits the file as text with `ast`, literal values only, offline. `add` creates the file with the import and the ProjectResources class when missing, re-adding the same kind and key leaves the file unchanged, a different type fails and names the line. `bindings` writes bindings.json over the hand-written entries (same kind and key replaced, entries stamped Source "code" regenerated). - `uipath pack` and `uipath push` regenerate bindings.json first when the project has a uipath_resources.py; a project without one packs as before. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_014t9fy7CGYG2vBLEfHwu12m --- README.md | 26 +- packages/uipath-platform/CLAUDE.md | 1 + packages/uipath-platform/pyproject.toml | 2 +- .../src/uipath/resources/__init__.py | 67 ++ .../src/uipath/resources/_handles.py | 324 ++++++++ .../src/uipath/resources/py.typed | 0 .../tests/resources/test_handles.py | 143 ++++ packages/uipath/README.md | 26 +- packages/uipath/pyproject.toml | 4 +- packages/uipath/src/uipath/_cli/__init__.py | 1 + .../src/uipath/_cli/_declarations/__init__.py | 14 + .../uipath/_cli/_declarations/_bindings.py | 226 ++++++ .../src/uipath/_cli/_declarations/_editor.py | 251 +++++++ .../src/uipath/_cli/_declarations/_model.py | 113 +++ .../src/uipath/_cli/_declarations/_parser.py | 316 ++++++++ .../src/uipath/_cli/_declarations/_project.py | 95 +++ packages/uipath/src/uipath/_cli/cli_pack.py | 5 + packages/uipath/src/uipath/_cli/cli_push.py | 5 + .../uipath/src/uipath/_cli/cli_resources.py | 584 +++++++++++++++ .../tests/cli/test_resource_declarations.py | 597 +++++++++++++++ packages/uipath/tests/cli/test_resources.py | 709 ++++++++++++++++++ 21 files changed, 3504 insertions(+), 5 deletions(-) create mode 100644 packages/uipath-platform/src/uipath/resources/__init__.py create mode 100644 packages/uipath-platform/src/uipath/resources/_handles.py create mode 100644 packages/uipath-platform/src/uipath/resources/py.typed create mode 100644 packages/uipath-platform/tests/resources/test_handles.py create mode 100644 packages/uipath/src/uipath/_cli/_declarations/__init__.py create mode 100644 packages/uipath/src/uipath/_cli/_declarations/_bindings.py create mode 100644 packages/uipath/src/uipath/_cli/_declarations/_editor.py create mode 100644 packages/uipath/src/uipath/_cli/_declarations/_model.py create mode 100644 packages/uipath/src/uipath/_cli/_declarations/_parser.py create mode 100644 packages/uipath/src/uipath/_cli/_declarations/_project.py create mode 100644 packages/uipath/src/uipath/_cli/cli_resources.py create mode 100644 packages/uipath/tests/cli/test_resource_declarations.py create mode 100644 packages/uipath/tests/cli/test_resources.py diff --git a/README.md b/README.md index d90c937fc..843ca8567 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,29 @@ uipath publish Publishes the most recently created package to your UiPath Orchestrator. +### Declare Resources + +```bash +uipath resources add InvoiceThreshold --kind asset --folder-path Finance/Shared --type integer +uipath resources add InvoiceReview --kind queue +uipath resources list +uipath resources remove InvoiceReview --kind queue +uipath resources bindings +``` + +Declares the platform resources the project uses in one place, `uipath_resources.py`: + +```python +from uipath.resources import resource + + +class ProjectResources: + invoice_threshold = resource.asset(name="InvoiceThreshold", folder_path="Finance/Shared", type="integer") + invoice_review = resource.queue(name="InvoiceReview") # no folder: the project's own +``` + +The code passes a handle's fields to the SDK (`sdk.assets.retrieve(name=ProjectResources.invoice_threshold.name, folder_path=ProjectResources.invoice_threshold.folder_path)`). `uipath resources bindings`, `uipath pack` and `uipath push` derive `bindings.json` from the file, keeping any hand-written entries, so the package carries exactly the bindings the code declares. The commands work offline; looking a resource up in the tenant and adding it to a solution is done by the `uip` CLI (`uip codedagent resources`, `uip function resources`), which forwards to these commands. + ## Project Structure To properly use the CLI for packaging and publishing, your project should include: @@ -190,7 +213,8 @@ To properly use the CLI for packaging and publishing, your project should includ - A `pyproject.toml` file with project metadata - A `uipath.json` file with your function definitions (e.g., `"functions": {"main": "main.py:main"}`) - A `entry-points.json` file (generated by `uipath init`) -- A `bindings.json` file (generated by `uipath init`) to configure resource overrides +- A `bindings.json` file (generated by `uipath init`) to configure resource overrides; when the project has a `uipath_resources.py`, `uipath pack` and `uipath push` regenerate it from the declarations there +- Optionally a `uipath_resources.py` file declaring the platform resources the code uses (see `uipath resources`) - Any Python files needed for your automation diff --git a/packages/uipath-platform/CLAUDE.md b/packages/uipath-platform/CLAUDE.md index 4bb5d4fad..5ad1320fb 100644 --- a/packages/uipath-platform/CLAUDE.md +++ b/packages/uipath-platform/CLAUDE.md @@ -108,6 +108,7 @@ Services provide both sync and async variants (e.g., `.invoke()` and `.invoke_as | `ontology/` | Ontology service: an ontology by id, its artifact files, its graph, SQL over its objects | | `guardrails/` | LLM output guardrails | | `resource_catalog/` | Resource discovery and metadata | +| `resources/` (`uipath.resources`, outside `uipath.platform`) | Typed handles for the resources a coded project declares in `uipath_resources.py` (`resource.asset(...)`, `resource.queue(...)`, one method per overridable kind); plain data the code passes to the SDK's methods. The `uipath` CLI reads that file as text and derives `bindings.json` from it | | `resume_triggers/` | HITL trigger creation/reading protocols | | `common/` | Shared base classes, config, auth, retry, paging, validation | | `errors/` | Custom exceptions (`EnrichedException`, `FolderNotFoundException`, `BaseUrlMissingError`, etc.) | diff --git a/packages/uipath-platform/pyproject.toml b/packages/uipath-platform/pyproject.toml index 611fea927..cb22f5c61 100644 --- a/packages/uipath-platform/pyproject.toml +++ b/packages/uipath-platform/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath-platform" -version = "0.3.22" +version = "0.3.23" description = "HTTP client library for programmatic access to UiPath Platform" readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/packages/uipath-platform/src/uipath/resources/__init__.py b/packages/uipath-platform/src/uipath/resources/__init__.py new file mode 100644 index 000000000..2914b5998 --- /dev/null +++ b/packages/uipath-platform/src/uipath/resources/__init__.py @@ -0,0 +1,67 @@ +"""Typed handles for the resources a coded project declares in ``uipath_resources.py``. + +Example: + ```python + from uipath.resources import resource + + class ProjectResources: + invoice_threshold = resource.asset( + name="InvoiceThreshold", folder_path="Finance/Shared", type="integer" + ) + review = resource.queue(name="Review") + ``` + + Then, in the project's code:: + + sdk.assets.retrieve( + name=ProjectResources.invoice_threshold.name, + folder_path=ProjectResources.invoice_threshold.folder_path, + ) + +The ``uipath`` CLI (``uipath resources``) edits the file and derives the +project's ``bindings.json`` from it. +""" + +from ._handles import ( + ASSET_TYPES, + BUCKET_TYPES, + CONNECTION_KIND, + ENTITY_KIND, + GENERIC_KINDS, + KIND_METHODS, + METHOD_BY_KIND, + RESOURCE_KINDS, + SKILL_BUNDLE_KIND, + TYPED_KINDS, + ConnectionHandle, + EntityHandle, + Handle, + ResourceFactory, + ResourceHandle, + SkillBundleHandle, + binding_key, + normalize_folder_path, + resource, +) + +__all__ = [ + "ASSET_TYPES", + "BUCKET_TYPES", + "CONNECTION_KIND", + "ENTITY_KIND", + "GENERIC_KINDS", + "KIND_METHODS", + "METHOD_BY_KIND", + "RESOURCE_KINDS", + "SKILL_BUNDLE_KIND", + "TYPED_KINDS", + "ConnectionHandle", + "EntityHandle", + "Handle", + "ResourceFactory", + "ResourceHandle", + "SkillBundleHandle", + "binding_key", + "normalize_folder_path", + "resource", +] diff --git a/packages/uipath-platform/src/uipath/resources/_handles.py b/packages/uipath-platform/src/uipath/resources/_handles.py new file mode 100644 index 000000000..14c218aae --- /dev/null +++ b/packages/uipath-platform/src/uipath/resources/_handles.py @@ -0,0 +1,324 @@ +"""Typed handles for the resources a coded project declares. + +A coded project names the platform resources it uses in one file, +``uipath_resources.py``, as attributes of a ``ProjectResources`` class:: + + from uipath.resources import resource + + class ProjectResources: + invoice_threshold = resource.asset( + name="InvoiceThreshold", folder_path="Finance/Shared", type="integer" + ) + review = resource.queue(name="Review") # no folder: the project's own + +Each ``resource.(...)`` call returns a frozen handle: plain data (the +kind, the name, the folder and the kind's own identifiers) that the code passes +to the SDK's existing methods, for example +``sdk.assets.retrieve(name=h.name, folder_path=h.folder_path)``. The handles +hold no SDK methods and make no requests. + +The ``uipath`` CLI reads the file as text, never imports it, and derives the +project's ``bindings.json`` from the literal declarations, so every value in a +declaration must be a string literal. The kinds are those the SDK can override +at deploy time: the ``resource_type`` values of the overwrite models in +``uipath.platform.common._bindings``, so a kind is added in one place. +""" + +from typing import Literal, get_args + +from pydantic import BaseModel, ConfigDict, model_validator + +from uipath.platform.common._bindings import ( + ConnectionResourceOverwrite, + EntityResourceOverwrite, + GenericResourceOverwrite, + SkillBundleResourceOverwrite, + VersionMode, + version_for_mode, +) + + +def _kinds_of(model: type[BaseModel]) -> tuple[str, ...]: + return tuple(get_args(model.model_fields["resource_type"].annotation)) + + +GENERIC_KINDS: tuple[str, ...] = _kinds_of(GenericResourceOverwrite) +"""Kinds found by name within a folder, with no identifier of their own.""" + +ENTITY_KIND: str = _kinds_of(EntityResourceOverwrite)[0] +CONNECTION_KIND: str = _kinds_of(ConnectionResourceOverwrite)[0] +SKILL_BUNDLE_KIND: str = _kinds_of(SkillBundleResourceOverwrite)[0] + +RESOURCE_KINDS: tuple[str, ...] = ( + *GENERIC_KINDS, + ENTITY_KIND, + CONNECTION_KIND, + SKILL_BUNDLE_KIND, +) +"""Every kind a declaration can have, as a binding names it (``mcpServer``).""" + +TYPED_KINDS: frozenset[str] = frozenset({"asset", "bucket", "process"}) +"""Kinds whose declaration may carry a ``type``: an asset's value type, a bucket's provider, a process's kind.""" + +ASSET_TYPES: tuple[str, ...] = ( + "text", + "integer", + "bool", + "credential", + "secret", + "json", +) +BUCKET_TYPES: tuple[str, ...] = ("orchestrator", "amazon", "azure") + +# The folder a solution writes for its own root; a declaration naming it has no folder. +_SOLUTION_ROOT_FOLDER = "solution_folder" + + +def normalize_folder_path(folder_path: str | None) -> str | None: + """The folder a declaration names, or ``None`` for the project's own folder. + + Blank, ``"."`` and the solution's own root folder all mean the folder the + project runs in, which a binding writes as ``"."``. + + Args: + folder_path: The folder as declared. + + Returns: + The folder, or ``None`` when the declaration names none. + """ + if folder_path is None: + return None + trimmed = folder_path.strip() + if not trimmed or trimmed == "." or trimmed == _SOLUTION_ROOT_FOLDER: + return None + return folder_path + + +def binding_key(name: str, folder_path: str | None) -> str: + """``name.folderPath``, or the bare name without a folder: the key a binding and its override share.""" + return f"{name}.{folder_path}" if folder_path else name + + +class ResourceHandle(BaseModel): + """A resource found by name within a folder. + + Attributes: + kind: The resource kind, as a binding names it (``asset``, ``mcpServer``). + name: The resource's name in Orchestrator or the service that owns it. + folder_path: The folder the resource sits in; ``None`` for the folder the + project runs in (a resource its solution creates). + type: For an asset, its value type (text, integer, bool, credential, + secret, json); for a bucket, its provider (orchestrator, amazon, + azure); for a process, its kind. ``None`` otherwise. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + kind: str + name: str + folder_path: str | None = None + type: str | None = None + + @model_validator(mode="after") + def _check(self) -> "ResourceHandle": + if not self.name.strip(): + raise ValueError(f"a {self.kind} handle needs a non-blank name") + if self.type is not None and self.kind not in TYPED_KINDS: + raise ValueError( + f"a {self.kind} takes no type: only {', '.join(sorted(TYPED_KINDS))} do" + ) + return self + + @property + def binding_key(self) -> str: + """The key of the handle's binding, which a deploy-time override matches.""" + return binding_key(self.name, self.folder_path) + + +class EntityHandle(ResourceHandle): + """A Data Fabric entity, found by name; the folder is optional.""" + + kind: Literal["entity"] = "entity" + + +class ConnectionHandle(BaseModel): + """An Integration Service connection, found by its id. + + Attributes: + kind: Always ``connection``. + id: The connection's id (a GUID), the key its binding and override share. + connector: The connector key (``uipath-slack``), which types the connection. + name: An optional label; it never identifies the connection. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + kind: Literal["connection"] = "connection" + id: str + connector: str + name: str | None = None + + @model_validator(mode="after") + def _check(self) -> "ConnectionHandle": + if not self.id.strip(): + raise ValueError("a connection handle needs its id") + if not self.connector.strip(): + raise ValueError("a connection handle needs its connector key") + return self + + @property + def binding_key(self) -> str: + """The key of the handle's binding: the connection's id.""" + return self.id + + +class SkillBundleHandle(ResourceHandle): + """A skill bundle, found by name within a folder, at a pinned or the latest version. + + Attributes: + version_mode: ``pinned`` when ``version`` names the version to use, + ``latest`` to take the newest one at run start. + version: The pinned version (a version number, a tag or a ``sha256:`` + digest); ``None`` for ``latest``. + """ + + kind: Literal["skillBundle"] = "skillBundle" + version_mode: VersionMode = VersionMode.LATEST + version: str | None = None + + @model_validator(mode="after") + def _check_version(self) -> "SkillBundleHandle": + # Raises for a pinned bundle without a version. + object.__setattr__( + self, "version", version_for_mode(self.version_mode, self.version) + ) + return self + + +Handle = ResourceHandle | ConnectionHandle +"""Any handle a declaration can produce.""" + + +class ResourceFactory: + """Builds the handles a project's ``uipath_resources.py`` declares. + + One method per kind the SDK can override. Every argument is a keyword, and + the CLI reads only string literals, so a declaration is + ``resource.queue(name="Review")`` and never ``resource.queue(QUEUE_NAME)``. + """ + + @staticmethod + def _generic( + kind: str, name: str, folder_path: str | None, type: str | None = None + ) -> ResourceHandle: + return ResourceHandle( + kind=kind, + name=name, + folder_path=normalize_folder_path(folder_path), + type=type, + ) + + def asset( + self, *, name: str, folder_path: str | None = None, type: str | None = None + ) -> ResourceHandle: + """An Orchestrator asset; ``type`` is its value type (text, integer, bool, credential, secret, json).""" + return self._generic("asset", name, folder_path, type) + + def bucket( + self, *, name: str, folder_path: str | None = None, type: str | None = None + ) -> ResourceHandle: + """An Orchestrator storage bucket; ``type`` is its provider (orchestrator, amazon, azure).""" + return self._generic("bucket", name, folder_path, type) + + def queue(self, *, name: str, folder_path: str | None = None) -> ResourceHandle: + """An Orchestrator queue.""" + return self._generic("queue", name, folder_path) + + def process( + self, *, name: str, folder_path: str | None = None, type: str | None = None + ) -> ResourceHandle: + """An Orchestrator process (a release); ``type`` is its kind, written as given.""" + return self._generic("process", name, folder_path, type) + + def index(self, *, name: str, folder_path: str | None = None) -> ResourceHandle: + """A Context Grounding index.""" + return self._generic("index", name, folder_path) + + def app(self, *, name: str, folder_path: str | None = None) -> ResourceHandle: + """An app (an Action Center app, a web app).""" + return self._generic("app", name, folder_path) + + def mcp_server( + self, *, name: str, folder_path: str | None = None + ) -> ResourceHandle: + """An MCP server registered in Orchestrator.""" + return self._generic("mcpServer", name, folder_path) + + def remote_a2a_agent( + self, *, name: str, folder_path: str | None = None + ) -> ResourceHandle: + """A remote A2A agent registered in Agent Hub.""" + return self._generic("remoteA2aAgent", name, folder_path) + + def memory_space( + self, *, name: str, folder_path: str | None = None + ) -> ResourceHandle: + """A memory space.""" + return self._generic("memorySpace", name, folder_path) + + def business_rule( + self, *, name: str, folder_path: str | None = None + ) -> ResourceHandle: + """A business rule deployed to Orchestrator.""" + return self._generic("businessRule", name, folder_path) + + def ontology(self, *, name: str, folder_path: str | None = None) -> ResourceHandle: + """An ontology.""" + return self._generic("ontology", name, folder_path) + + def entity(self, *, name: str, folder_path: str | None = None) -> EntityHandle: + """A Data Fabric entity; the folder is optional.""" + return EntityHandle(name=name, folder_path=normalize_folder_path(folder_path)) + + def connection( + self, *, id: str, connector: str, name: str | None = None + ) -> ConnectionHandle: + """An Integration Service connection, by its id and connector key.""" + return ConnectionHandle(id=id, connector=connector, name=name) + + def skill_bundle( + self, *, name: str, folder_path: str | None = None, version: str | None = None + ) -> SkillBundleHandle: + """A skill bundle; ``version`` pins one, ``None`` or ``"latest"`` takes the newest at run start.""" + latest = version is None or version.strip().lower() == VersionMode.LATEST + return SkillBundleHandle( + name=name, + folder_path=normalize_folder_path(folder_path), + version_mode=VersionMode.LATEST if latest else VersionMode.PINNED, + version=None if latest else version, + ) + + +resource = ResourceFactory() +"""The factory a ``uipath_resources.py`` imports: ``from uipath.resources import resource``.""" + +KIND_METHODS: dict[str, str] = { + "asset": "asset", + "bucket": "bucket", + "queue": "queue", + "process": "process", + "index": "index", + "app": "app", + "mcp_server": "mcpServer", + "remote_a2a_agent": "remoteA2aAgent", + "memory_space": "memorySpace", + "business_rule": "businessRule", + "ontology": "ontology", + "entity": "entity", + "connection": "connection", + "skill_bundle": "skillBundle", +} +"""The ``resource.`` a declaration calls, by method name, to the kind it declares.""" + +METHOD_BY_KIND: dict[str, str] = {kind: method for method, kind in KIND_METHODS.items()} +"""The factory method that declares each kind.""" diff --git a/packages/uipath-platform/src/uipath/resources/py.typed b/packages/uipath-platform/src/uipath/resources/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/packages/uipath-platform/tests/resources/test_handles.py b/packages/uipath-platform/tests/resources/test_handles.py new file mode 100644 index 000000000..9bee79e16 --- /dev/null +++ b/packages/uipath-platform/tests/resources/test_handles.py @@ -0,0 +1,143 @@ +"""Tests for the typed resource handles a ``uipath_resources.py`` declares.""" + +import inspect + +import pytest +from pydantic import ValidationError + +from uipath.platform.common._bindings import _KNOWN_RESOURCE_TYPES, VersionMode +from uipath.resources import ( + KIND_METHODS, + METHOD_BY_KIND, + RESOURCE_KINDS, + ConnectionHandle, + EntityHandle, + ResourceFactory, + ResourceHandle, + SkillBundleHandle, + normalize_folder_path, + resource, +) + + +def test_kinds_are_the_overwrite_kinds_the_sdk_knows() -> None: + assert set(RESOURCE_KINDS) == _KNOWN_RESOURCE_TYPES + assert len(RESOURCE_KINDS) == len(set(RESOURCE_KINDS)) + + +def test_every_kind_has_one_factory_method_and_the_maps_agree() -> None: + methods = { + name + for name, member in inspect.getmembers(ResourceFactory, inspect.isfunction) + if not name.startswith("_") + } + assert methods == set(KIND_METHODS) + assert set(KIND_METHODS.values()) == set(RESOURCE_KINDS) + assert {kind: method for method, kind in KIND_METHODS.items()} == METHOD_BY_KIND + + +def test_factory_methods_take_keywords_only() -> None: + for name in KIND_METHODS: + signature = inspect.signature(getattr(ResourceFactory, name)) + for parameter in list(signature.parameters.values())[1:]: + assert parameter.kind is inspect.Parameter.KEYWORD_ONLY, name + + +def test_generic_handle_carries_kind_name_folder_and_type() -> None: + handle = resource.asset( + name="InvoiceThreshold", folder_path="Finance/Shared", type="integer" + ) + assert handle == ResourceHandle( + kind="asset", + name="InvoiceThreshold", + folder_path="Finance/Shared", + type="integer", + ) + assert handle.binding_key == "InvoiceThreshold.Finance/Shared" + + +@pytest.mark.parametrize("folder", [None, "", " ", ".", "solution_folder"]) +def test_the_projects_own_folder_is_none(folder: str | None) -> None: + handle = resource.queue(name="Review", folder_path=folder) + assert handle.folder_path is None + assert handle.binding_key == "Review" + assert normalize_folder_path(folder) is None + + +def test_handles_are_frozen() -> None: + handle = resource.queue(name="Review") + with pytest.raises(ValidationError): + handle.name = "Other" # type: ignore[misc] + + +def test_a_blank_name_is_rejected() -> None: + with pytest.raises(ValidationError, match="non-blank name"): + resource.bucket(name=" ") + + +def test_a_type_on_a_kind_without_one_is_rejected() -> None: + with pytest.raises(ValidationError, match="takes no type"): + ResourceHandle(kind="queue", name="Review", type="text") + + +@pytest.mark.parametrize( + ("method", "kind"), + [ + ("mcp_server", "mcpServer"), + ("remote_a2a_agent", "remoteA2aAgent"), + ("memory_space", "memorySpace"), + ("business_rule", "businessRule"), + ("index", "index"), + ("app", "app"), + ("ontology", "ontology"), + ("process", "process"), + ], +) +def test_snake_case_methods_declare_camel_case_kinds(method: str, kind: str) -> None: + handle = getattr(resource, method)(name="X", folder_path="Shared") + assert (handle.kind, handle.name, handle.folder_path) == (kind, "X", "Shared") + + +def test_entity_keeps_an_optional_folder() -> None: + assert resource.entity(name="Invoices").folder_path is None + with_folder = resource.entity(name="Invoices", folder_path="Finance") + assert isinstance(with_folder, EntityHandle) + assert with_folder.kind == "entity" + assert with_folder.binding_key == "Invoices.Finance" + + +def test_connection_is_identified_by_its_id() -> None: + handle = resource.connection( + id="3121165f-ce9b-4503-8c10-289ae6b21bd8", + connector="uipath-slack", + name="Finance Slack", + ) + assert handle == ConnectionHandle( + id="3121165f-ce9b-4503-8c10-289ae6b21bd8", + connector="uipath-slack", + name="Finance Slack", + ) + assert handle.kind == "connection" + assert handle.binding_key == "3121165f-ce9b-4503-8c10-289ae6b21bd8" + with pytest.raises(ValidationError, match="connector"): + resource.connection(id="3121165f-ce9b-4503-8c10-289ae6b21bd8", connector=" ") + + +@pytest.mark.parametrize("version", [None, "latest", "LATEST", " latest "]) +def test_skill_bundle_without_a_version_takes_the_latest(version: str | None) -> None: + handle = resource.skill_bundle( + name="finance", folder_path="Shared/Skills", version=version + ) + assert isinstance(handle, SkillBundleHandle) + assert (handle.version_mode, handle.version) == (VersionMode.LATEST, None) + + +@pytest.mark.parametrize("version", ["7", "v1.2", "sha256:abc"]) +def test_skill_bundle_with_a_version_is_pinned(version: str) -> None: + handle = resource.skill_bundle(name="finance", version=version) + assert (handle.version_mode, handle.version) == (VersionMode.PINNED, version) + + +def test_a_pinned_skill_bundle_needs_a_version() -> None: + with pytest.raises(ValidationError, match="needs a version"): + SkillBundleHandle(name="finance", version_mode=VersionMode.PINNED) diff --git a/packages/uipath/README.md b/packages/uipath/README.md index d90c937fc..843ca8567 100644 --- a/packages/uipath/README.md +++ b/packages/uipath/README.md @@ -183,6 +183,29 @@ uipath publish Publishes the most recently created package to your UiPath Orchestrator. +### Declare Resources + +```bash +uipath resources add InvoiceThreshold --kind asset --folder-path Finance/Shared --type integer +uipath resources add InvoiceReview --kind queue +uipath resources list +uipath resources remove InvoiceReview --kind queue +uipath resources bindings +``` + +Declares the platform resources the project uses in one place, `uipath_resources.py`: + +```python +from uipath.resources import resource + + +class ProjectResources: + invoice_threshold = resource.asset(name="InvoiceThreshold", folder_path="Finance/Shared", type="integer") + invoice_review = resource.queue(name="InvoiceReview") # no folder: the project's own +``` + +The code passes a handle's fields to the SDK (`sdk.assets.retrieve(name=ProjectResources.invoice_threshold.name, folder_path=ProjectResources.invoice_threshold.folder_path)`). `uipath resources bindings`, `uipath pack` and `uipath push` derive `bindings.json` from the file, keeping any hand-written entries, so the package carries exactly the bindings the code declares. The commands work offline; looking a resource up in the tenant and adding it to a solution is done by the `uip` CLI (`uip codedagent resources`, `uip function resources`), which forwards to these commands. + ## Project Structure To properly use the CLI for packaging and publishing, your project should include: @@ -190,7 +213,8 @@ To properly use the CLI for packaging and publishing, your project should includ - A `pyproject.toml` file with project metadata - A `uipath.json` file with your function definitions (e.g., `"functions": {"main": "main.py:main"}`) - A `entry-points.json` file (generated by `uipath init`) -- A `bindings.json` file (generated by `uipath init`) to configure resource overrides +- A `bindings.json` file (generated by `uipath init`) to configure resource overrides; when the project has a `uipath_resources.py`, `uipath pack` and `uipath push` regenerate it from the declarations there +- Optionally a `uipath_resources.py` file declaring the platform resources the code uses (see `uipath resources`) - Any Python files needed for your automation diff --git a/packages/uipath/pyproject.toml b/packages/uipath/pyproject.toml index dae9eebae..446cb57f6 100644 --- a/packages/uipath/pyproject.toml +++ b/packages/uipath/pyproject.toml @@ -1,13 +1,13 @@ [project] name = "uipath" -version = "2.15.15" +version = "2.15.16" description = "Python SDK and CLI for UiPath Platform, enabling programmatic interaction with automation services, process management, and deployment tools." readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" dependencies = [ "uipath-core>=0.5.35, <0.6.0", "uipath-runtime>=0.13.7, <0.14.0", - "uipath-platform>=0.3.20, <0.4.0", + "uipath-platform>=0.3.23, <0.4.0", "uipath-ipc>=2.5.1, <2.6.0", "click>=8.3.3, <9.0.0", "httpx>=0.28.1", diff --git a/packages/uipath/src/uipath/_cli/__init__.py b/packages/uipath/src/uipath/_cli/__init__.py index afeacfb29..a09bb4d2c 100644 --- a/packages/uipath/src/uipath/_cli/__init__.py +++ b/packages/uipath/src/uipath/_cli/__init__.py @@ -47,6 +47,7 @@ "register": "cli_register", "debug": "cli_debug", "list-models": "cli_list_models", + "resources": "cli_resources", "assets": "services.cli_assets", "buckets": "services.cli_buckets", "context-grounding": "services.cli_context_grounding", diff --git a/packages/uipath/src/uipath/_cli/_declarations/__init__.py b/packages/uipath/src/uipath/_cli/_declarations/__init__.py new file mode 100644 index 000000000..eaa336cb1 --- /dev/null +++ b/packages/uipath/src/uipath/_cli/_declarations/__init__.py @@ -0,0 +1,14 @@ +"""The project's resource declarations file, ``uipath_resources.py``, and what derives from it. + +A coded project declares the platform resources it uses as attributes of a +``ProjectResources`` class in ``uipath_resources.py`` (see +``uipath.resources``). The ``uipath resources`` commands read and edit that +file as text, never importing it, and ``uipath resources bindings``, ``pack`` +and ``push`` derive the project's ``bindings.json`` from it. + +- ``_model``: a declaration as the commands see it, and its binding key. +- ``_parser``: the literal-only ``ast`` reader, with a diagnostic per call it skips. +- ``_editor``: adds and removes declarations in the file's text. +- ``_bindings``: derives ``bindings.json`` over the hand-written entries. +- ``_project``: where the files live. +""" diff --git a/packages/uipath/src/uipath/_cli/_declarations/_bindings.py b/packages/uipath/src/uipath/_cli/_declarations/_bindings.py new file mode 100644 index 000000000..bd36d7b64 --- /dev/null +++ b/packages/uipath/src/uipath/_cli/_declarations/_bindings.py @@ -0,0 +1,226 @@ +"""``bindings.json`` derived from the project's resource declarations. + +The declarations are the source and the bindings a build output: ``uipath +resources bindings``, ``pack`` and ``push`` write them before they read them. +A hand-written ``bindings.json`` is the base: its entries are kept, except an +entry a declaration replaces (same kind and key) and entries an earlier +derivation wrote (``metadata.Source`` is ``code``), so bindings for kinds +declared by hand (an MCP server a low-code agent uses, a guardrail) keep working. + +Entry shapes match what Studio Web and the ``uip`` CLI write for the same kind, +so Solutions and Orchestrator read them as they read theirs. +""" + +import json +import os +from dataclasses import dataclass, field +from typing import Any + +from ._model import CONNECTION_KIND, SKILL_BUNDLE_KIND, Declaration, binding_identity +from ._parser import parse_declarations +from ._project import bindings_path, read_declarations_file + +BINDINGS_FILE_VERSION = "2.0" +# ``metadata.BindingsVersion`` of a derived entry; Solutions needs at least 2.2 to offer an override. +_BINDINGS_ENTRY_VERSION = "2.2" +DERIVED_BINDING_SOURCE = "code" +"""``metadata.Source`` stamped on every derived entry.""" +# ``folderPath`` of a binding whose declaration names no folder: the folder the project runs in. +_PROJECT_FOLDER = "." + + +class BindingsFileError(Exception): + """The existing ``bindings.json`` cannot be read, so nothing is derived over it.""" + + +@dataclass(frozen=True) +class DerivedBindings: + """The bindings document derived from a set of declarations. + + Attributes: + document: The ``bindings.json`` content. + derived: Entries written from declarations. + kept: Entries kept from the base document. + diagnostics: Declarations that collide with an earlier one of the same kind and key. + """ + + document: dict[str, Any] + derived: int + kept: int + diagnostics: list[str] = field(default_factory=list) + + +@dataclass(frozen=True) +class BindingsSync: + """What regenerating a project's ``bindings.json`` did. + + Attributes: + path: The bindings file. + declarations_file: The declarations file, relative to the project root. + declared: Declarations read. + derived: Entries written from them. + kept: Hand-written entries kept. + changed: Whether the file's content changed. + diagnostics: Declarations skipped (unreadable) or colliding, one line each. + """ + + path: str + declarations_file: str + declared: int + derived: int + kept: int + changed: bool + diagnostics: list[str] = field(default_factory=list) + + +def _value(default: str, display_name: str) -> dict[str, Any]: + return {"defaultValue": default, "isExpression": False, "displayName": display_name} + + +def _connection_entry(declaration: Declaration) -> dict[str, Any]: + # Studio Web's shape for a connection binding. + connection_id = declaration.id or "" + return { + "resource": declaration.kind, + "key": connection_id, + "value": {"ConnectionId": _value(connection_id, "Connection")}, + "metadata": { + "BindingsVersion": _BINDINGS_ENTRY_VERSION, + "Connector": declaration.type, + "UseConnectionService": "true", + "SolutionsSupport": "true", + "Source": DERIVED_BINDING_SOURCE, + }, + } + + +def binding_entry(declaration: Declaration) -> dict[str, Any]: + """The ``bindings.json`` entry one declaration derives.""" + if declaration.kind == CONNECTION_KIND: + return _connection_entry(declaration) + value: dict[str, Any] = { + "name": _value(declaration.name, "Name"), + "folderPath": _value(declaration.folder_path or _PROJECT_FOLDER, "Folder Path"), + } + if declaration.kind == SKILL_BUNDLE_KIND: + value["version"] = _value(declaration.version or "latest", "Version") + metadata: dict[str, Any] = {"BindingsVersion": _BINDINGS_ENTRY_VERSION} + if declaration.type: + metadata["SubType"] = declaration.type + metadata["Source"] = DERIVED_BINDING_SOURCE + return { + "resource": declaration.kind, + "key": declaration.key, + "value": value, + "metadata": metadata, + } + + +def is_derived_binding(entry: dict[str, Any]) -> bool: + """Whether an entry was written from a declaration by an earlier derivation.""" + metadata = entry.get("metadata") + return ( + isinstance(metadata, dict) and metadata.get("Source") == DERIVED_BINDING_SOURCE + ) + + +def derive_bindings( + declarations: list[Declaration], base: dict[str, Any] | None +) -> DerivedBindings: + """One entry per declared kind and key, after the base entries the declarations leave in place.""" + derived: dict[str, dict[str, Any]] = {} + declared_types: dict[str, str | None] = {} + diagnostics: list[str] = [] + for declaration in declarations: + identity = declaration.identity + if identity in derived: + if declared_types[identity] != declaration.type: + diagnostics.append( + f'{declaration.kind} "{declaration.key}" is declared more than once ' + f"with different types; the first declaration is used." + ) + continue + derived[identity] = binding_entry(declaration) + declared_types[identity] = declaration.type + + kept = [ + entry + for entry in (base or {}).get("resources", []) + if isinstance(entry, dict) + and not is_derived_binding(entry) + and binding_identity(str(entry.get("resource", "")), str(entry.get("key", ""))) + not in derived + ] + version = (base or {}).get("version") + return DerivedBindings( + document={ + "version": version if isinstance(version, str) else BINDINGS_FILE_VERSION, + "resources": [*kept, *derived.values()], + }, + derived=len(derived), + kept=len(kept), + diagnostics=diagnostics, + ) + + +def read_bindings_document(path: str) -> dict[str, Any] | None: + """The bindings file at ``path``, or ``None`` when it is absent or empty. + + Raises: + BindingsFileError: The file is not a JSON object with a ``resources`` list. + """ + if not os.path.isfile(path): + return None + with open(path, encoding="utf-8") as f: + content = f.read() + if not content.strip(): + return None + try: + document = json.loads(content) + except json.JSONDecodeError as error: + raise BindingsFileError(f"{path} is not valid JSON ({error}).") from error + if not isinstance(document, dict): + raise BindingsFileError(f"{path} must be a JSON object.") + if not isinstance(document.get("resources"), list): + raise BindingsFileError(f'{path} is missing a "resources" list.') + return document + + +def serialize_bindings(document: dict[str, Any]) -> str: + """Four-space JSON, as ``uipath init`` writes the file.""" + return json.dumps(document, indent=4) + + +def sync_bindings(root: str) -> BindingsSync | None: + """Regenerates ``bindings.json`` from the project's declarations file. + + Returns ``None`` when the project has no declarations file, in which case + the bindings file is left as it is. + + Raises: + DeclarationsSyntaxError: The declarations file is not valid Python. + BindingsFileError: The existing bindings file cannot be read. + """ + declarations = read_declarations_file(root) + if not declarations.exists: + return None + parsed = parse_declarations(declarations.content, declarations.relative_path) + path = bindings_path(root) + derived = derive_bindings(parsed.resources, read_bindings_document(path)) + content = serialize_bindings(derived.document) + changed = True + if os.path.isfile(path): + with open(path, encoding="utf-8") as f: + changed = f.read() != content + if changed: + with open(path, "w", encoding="utf-8") as f: + f.write(content) + return BindingsSync( + path=path, + declarations_file=declarations.relative_path, + declared=len(parsed.resources), + derived=derived.derived, + kept=derived.kept, + changed=changed, + diagnostics=[*parsed.diagnostics, *derived.diagnostics], + ) diff --git a/packages/uipath/src/uipath/_cli/_declarations/_editor.py b/packages/uipath/src/uipath/_cli/_declarations/_editor.py new file mode 100644 index 000000000..da49d7e58 --- /dev/null +++ b/packages/uipath/src/uipath/_cli/_declarations/_editor.py @@ -0,0 +1,251 @@ +"""Adds and removes declarations in the text of ``uipath_resources.py``. + +The file is edited as text so that everything else in it (comments, other +members, formatting) stays as the user wrote it: a declaration is one line +added after the last member of ``ProjectResources``, or one statement removed. +""" + +import ast +import keyword +import re +from dataclasses import dataclass + +from ._model import ( + CLASS_NAME, + CONNECTION_KIND, + SDK_HELPER_NAME, + SDK_IMPORT_LINE, + Declaration, +) +from ._parser import ParsedDeclarations, parse_declarations + +_DEFAULT_INDENT = " " +_FALLBACK_IDENTIFIER = "resource" +_ENCODING_COOKIE = re.compile(r"^[ \t]*#.*coding[:=]") + + +class DeclarationsFileError(Exception): + """The file cannot be edited as it is; the message says what to do.""" + + +@dataclass(frozen=True) +class InsertResult: + """What adding a declaration did. + + Attributes: + source: The file's new text; the input unchanged when nothing was added. + added: ``False`` when the same kind and key was already declared. + attribute: The ``ProjectResources`` attribute the declaration was written to. + """ + + source: str + added: bool + attribute: str | None + + +@dataclass(frozen=True) +class RemoveResult: + """What removing a declaration did. + + Attributes: + source: The file's new text; the input unchanged when nothing matched. + removed: Whether a declaration was removed. + attribute: The attribute the removed declaration was bound to, if any. + """ + + source: str + removed: bool + attribute: str | None + + +def to_python_identifier(name: str, taken: frozenset[str] | set[str]) -> str: + """A snake_case attribute name for ``name``, unique among ``taken`` and never a keyword. + + ``InvoiceThreshold`` becomes ``invoice_threshold``; a second ``Review`` + becomes ``review_2``; ``class`` becomes ``class_``; ``2FA`` becomes ``_2fa``. + """ + spaced = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", name) + words = [word for word in re.split(r"[^A-Za-z0-9]+", spaced) if word] + base = "_".join(word.lower() for word in words) or _FALLBACK_IDENTIFIER + if base[0].isdigit(): + base = f"_{base}" + if keyword.iskeyword(base): + base = f"{base}_" + candidate = base + suffix = 2 + while candidate in taken or candidate == SDK_HELPER_NAME: + candidate = f"{base}_{suffix}" + suffix += 1 + return candidate + + +def _quote(value: str) -> str: + escaped = ( + value.replace("\\", "\\\\") + .replace('"', '\\"') + .replace("\n", "\\n") + .replace("\r", "\\r") + ) + return f'"{escaped}"' + + +def render_declaration( + attribute: str, declaration: Declaration, indent: str = _DEFAULT_INDENT +) -> str: + """The line that declares ``declaration`` as ``attribute`` of ``ProjectResources``.""" + if declaration.kind == CONNECTION_KIND: + arguments = [ + f"id={_quote(declaration.id or '')}", + f"connector={_quote(declaration.type or '')}", + ] + if declaration.name: + arguments.append(f"name={_quote(declaration.name)}") + else: + arguments = [f"name={_quote(declaration.name)}"] + if declaration.folder_path: + arguments.append(f"folder_path={_quote(declaration.folder_path)}") + if declaration.type: + arguments.append(f"type={_quote(declaration.type)}") + if declaration.version: + arguments.append(f"version={_quote(declaration.version)}") + return f"{indent}{attribute} = {SDK_HELPER_NAME}.{declaration.method}({', '.join(arguments)})" + + +def _identifier_source(declaration: Declaration) -> str: + """What the attribute name is built from: the name, or a connection's connector when it has no label.""" + return declaration.name or declaration.type or declaration.kind + + +def _new_file(declaration: Declaration) -> InsertResult: + attribute = to_python_identifier(_identifier_source(declaration), set()) + source = "\n".join( + [ + SDK_IMPORT_LINE, + "", + "", + f"class {CLASS_NAME}:", + render_declaration(attribute, declaration), + "", + ] + ) + return InsertResult(source=source, added=True, attribute=attribute) + + +def _import_insertion_index(source: str, lines: list[str]) -> int: + """The line index the SDK import goes at: after the docstring and ``from __future__`` imports.""" + tree = ast.parse(source) + at = 0 + for index, statement in enumerate(tree.body): + is_docstring = ( + index == 0 + and isinstance(statement, ast.Expr) + and isinstance(statement.value, ast.Constant) + and isinstance(statement.value.value, str) + ) + is_future = ( + isinstance(statement, ast.ImportFrom) and statement.module == "__future__" + ) + if not (is_docstring or is_future): + break + at = statement.end_lineno or statement.lineno + if at == 0: + if lines and lines[0].startswith("#!"): + at = 1 + for index in range(at, min(2, len(lines))): + if _ENCODING_COOKIE.match(lines[index]): + at = index + 1 + return at + + +def _line_end(lines: list[str], index: int) -> str: + return "\r" if 0 <= index < len(lines) and lines[index].endswith("\r") else "" + + +def insert_declaration( + source: str, declaration: Declaration, file_name: str +) -> InsertResult: + """Adds ``declaration`` as an attribute of ``ProjectResources``, after its last member. + + A blank ``source`` becomes a new file. The SDK import is added when the + file lacks it. A declaration of the same kind and key is left as it is. + + Raises: + DeclarationsSyntaxError: The file is not valid Python. + DeclarationsFileError: The file has content but no module-level + ``class ProjectResources``. + """ + if not source.strip(): + return _new_file(declaration) + + parsed = parse_declarations(source, file_name) + if parsed.find(declaration.kind, declaration.key) is not None: + return InsertResult(source=source, added=False, attribute=None) + + info = parsed.project_resources + if info is None: + raise DeclarationsFileError( + f"{file_name} exists but has no `class {CLASS_NAME}:` at module level. " + f"Add the declaration by hand, or move your declarations into that class." + ) + + attribute = to_python_identifier(_identifier_source(declaration), info.taken) + lines = source.split("\n") + body_start, body_end = info.body_lines + line = render_declaration(attribute, declaration, info.indent) + _line_end( + lines, body_end - 1 + ) + if info.only_placeholder: + lines[body_start - 1 : body_end] = [line] + else: + lines.insert(body_end, line) + + if not parsed.imports_helper: + updated = "\n".join(lines) + at = _import_insertion_index(updated, lines) + lines.insert(at, SDK_IMPORT_LINE + _line_end(lines, at - 1)) + return InsertResult(source="\n".join(lines), added=True, attribute=attribute) + + +def remove_declaration( + source: str, kind: str, key: str, file_name: str +) -> RemoveResult: + """Removes the declaration of ``kind`` with binding key ``key``: the whole statement that holds it. + + Raises: + DeclarationsSyntaxError: The file is not valid Python. + DeclarationsFileError: The declaration is not a plain + ``attribute = resource.(...)`` statement, so it is left for + the user to remove. + """ + parsed = parse_declarations(source, file_name) + found = parsed.find(kind, key) + if found is None: + return RemoveResult(source=source, removed=False, attribute=None) + if found.statement_lines is None: + raise DeclarationsFileError( + f"{file_name}:{found.lineno}: the {found.declaration.label} declaration is " + f"part of a larger expression; remove it by hand." + ) + start, end = found.statement_lines + lines = source.split("\n") + del lines[start - 1 : end] + + info = parsed.project_resources + if info is not None and info.body_lines == found.statement_lines: + # The class body would be empty, which is not valid Python. + lines.insert(start - 1, f"{info.indent}pass" + _line_end(lines, start - 2)) + return RemoveResult( + source="\n".join(lines), removed=True, attribute=found.attribute + ) + + +__all__ = [ + "DeclarationsFileError", + "InsertResult", + "ParsedDeclarations", + "RemoveResult", + "insert_declaration", + "remove_declaration", + "render_declaration", + "to_python_identifier", +] diff --git a/packages/uipath/src/uipath/_cli/_declarations/_model.py b/packages/uipath/src/uipath/_cli/_declarations/_model.py new file mode 100644 index 000000000..166bd49a0 --- /dev/null +++ b/packages/uipath/src/uipath/_cli/_declarations/_model.py @@ -0,0 +1,113 @@ +"""A resource declaration as the ``uipath resources`` commands see it.""" + +import re +from dataclasses import dataclass + +from uipath.resources import ( + CONNECTION_KIND, + ENTITY_KIND, + KIND_METHODS, + METHOD_BY_KIND, + RESOURCE_KINDS, + SKILL_BUNDLE_KIND, + TYPED_KINDS, + binding_key, + normalize_folder_path, +) + +DECLARATIONS_FILE_NAME = "uipath_resources.py" +CLASS_NAME = "ProjectResources" +SDK_MODULE = "uipath.resources" +SDK_HELPER_NAME = "resource" +SDK_IMPORT_LINE = f"from {SDK_MODULE} import {SDK_HELPER_NAME}" +CONNECTION_ID_PATTERN = re.compile( + r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.IGNORECASE +) +"""A connection's id is a GUID.""" + +__all__ = [ + "CLASS_NAME", + "CONNECTION_ID_PATTERN", + "CONNECTION_KIND", + "DECLARATIONS_FILE_NAME", + "ENTITY_KIND", + "KIND_METHODS", + "METHOD_BY_KIND", + "RESOURCE_KINDS", + "SDK_HELPER_NAME", + "SDK_IMPORT_LINE", + "SDK_MODULE", + "SKILL_BUNDLE_KIND", + "TYPED_KINDS", + "Declaration", + "binding_identity", + "binding_key", + "normalize_folder_path", + "resolve_kind", +] + + +@dataclass(frozen=True) +class Declaration: + """One ``resource.(...)`` declaration, with literal values only. + + Attributes: + kind: The kind as a binding names it (``asset``, ``mcpServer``). + name: The resource name; ``""`` for a connection without a label. + folder_path: The folder, or ``""`` for the project's own folder. Always + ``""`` for a connection. + type: An asset's value type, a bucket's provider, a process's kind, or + a connection's connector key. + id: A connection's id. + version: A skill bundle's pinned version; ``None`` for ``latest``. + """ + + kind: str + name: str + folder_path: str = "" + type: str | None = None + id: str | None = None + version: str | None = None + + @property + def key(self) -> str: + """The key the declaration's binding and its override share: a connection's id, else ``name.folder`` or the bare name.""" + if self.kind == CONNECTION_KIND: + return self.id or "" + return binding_key(self.name, self.folder_path or None) + + @property + def identity(self) -> str: + """``kind:key``, kinds compared without case: what makes two declarations the same resource.""" + return binding_identity(self.kind, self.key) + + @property + def method(self) -> str: + """The ``resource.`` that declares this kind.""" + return METHOD_BY_KIND[self.kind] + + @property + def label(self) -> str: + """The declaration named for a message: ``asset "InvoiceThreshold"``.""" + return f'{self.kind} "{self.name or self.key}"' + + +def binding_identity(kind: str, key: str) -> str: + """``kind:key`` with the kind lowered: Studio Web writes some kinds as ``Asset`` or ``Connection``.""" + return f"{kind.lower()}:{key}" + + +def resolve_kind(value: str) -> str | None: + """The kind ``value`` names, in any of its spellings, or ``None``. + + Accepts the binding kind (``mcpServer``), the factory method + (``mcp_server``) and any casing of either. + """ + folded = value.replace("_", "").replace("-", "").lower() + for kind in RESOURCE_KINDS: + if kind.lower() == folded: + return kind + for method, kind in KIND_METHODS.items(): + if method.replace("_", "") == folded: + return kind + return None diff --git a/packages/uipath/src/uipath/_cli/_declarations/_parser.py b/packages/uipath/src/uipath/_cli/_declarations/_parser.py new file mode 100644 index 000000000..e7d49c96b --- /dev/null +++ b/packages/uipath/src/uipath/_cli/_declarations/_parser.py @@ -0,0 +1,316 @@ +"""Reads ``uipath_resources.py`` with ``ast``, literal values only, never importing it. + +Grammar, shared with the ``uip`` CLI's reader of the same file: every +``resource.(...)`` call whose arguments are all keywords with string +literal values declares a resource. ``name`` is required; ``folder_path``, +``type`` and ``version`` are optional where the kind takes them; a connection +takes ``id`` and ``connector`` instead, with an optional ``name``. A call that +breaks the rules (a positional argument, a variable, an f-string, an unknown +keyword) is reported with its line and skipped, so a declaration the CLI cannot +read never silently drops out of the bindings. +""" + +import ast +from dataclasses import dataclass + +from ._model import ( + CLASS_NAME, + CONNECTION_ID_PATTERN, + CONNECTION_KIND, + KIND_METHODS, + SDK_HELPER_NAME, + SKILL_BUNDLE_KIND, + TYPED_KINDS, + Declaration, + normalize_folder_path, +) + +_COMMON_KEYWORDS = frozenset({"name", "folder_path"}) +_CONNECTION_KEYWORDS = frozenset({"id", "connector", "name"}) + + +class DeclarationsSyntaxError(Exception): + """The declarations file is not valid Python.""" + + def __init__(self, file_name: str, error: SyntaxError) -> None: + line = f":{error.lineno}" if error.lineno else "" + super().__init__(f"{file_name}{line}: {error.msg}") + + +@dataclass(frozen=True) +class ParsedDeclaration: + """A declaration and where it sits in the file. + + Attributes: + declaration: The resource declared. + attribute: The ``ProjectResources`` attribute (or module variable) it + is assigned to; ``None`` for a call that is not a plain assignment. + lineno: The line of the ``resource.(`` call. + statement_lines: The first and last line of the statement that holds + the call, when the call is the whole value of an assignment or an + expression statement; ``None`` when it is nested in something else. + """ + + declaration: Declaration + attribute: str | None + lineno: int + statement_lines: tuple[int, int] | None + + +@dataclass(frozen=True) +class ClassInfo: + """The module-level ``class ProjectResources`` in the file. + + Attributes: + lineno: The line of the ``class`` statement. + end_lineno: The last line of the class. + body_lines: The first and last line of its body statements. + indent: The indentation of its body. + taken: Attribute, method and nested class names already bound in the body. + only_placeholder: Whether the body is a lone ``pass`` or ``...``. + """ + + lineno: int + end_lineno: int + body_lines: tuple[int, int] + indent: str + taken: frozenset[str] + only_placeholder: bool + + +@dataclass(frozen=True) +class ParsedDeclarations: + """What a read of the file found. + + Attributes: + declarations: The declarations read, in file order. + diagnostics: One line per call that was skipped, with its line and why. + project_resources: The ``ProjectResources`` class, when the file has one. + imports_helper: Whether the file binds the SDK helper as ``resource``. + """ + + declarations: list[ParsedDeclaration] + diagnostics: list[str] + project_resources: ClassInfo | None + imports_helper: bool + + @property + def resources(self) -> list[Declaration]: + """The declarations without their positions.""" + return [parsed.declaration for parsed in self.declarations] + + def find(self, kind: str, key: str) -> ParsedDeclaration | None: + """The declaration of ``kind`` with binding key ``key``, if the file has one.""" + wanted = f"{kind.lower()}:{key}" + for parsed in self.declarations: + if parsed.declaration.identity == wanted: + return parsed + return None + + +def _declared_method(call: ast.Call) -> str | None: + """The ``resource.`` a call names, when it is one the factory has.""" + func = call.func + if ( + isinstance(func, ast.Attribute) + and isinstance(func.value, ast.Name) + and func.value.id == SDK_HELPER_NAME + and func.attr in KIND_METHODS + ): + return func.attr + return None + + +def _literal_keywords(call: ast.Call) -> dict[str, str] | str: + """The call's keyword arguments as strings, or why they cannot be read.""" + if call.args: + return "has a positional argument" + values: dict[str, str] = {} + for keyword in call.keywords: + if keyword.arg is None: + return "unpacks its arguments" + value = keyword.value + if not isinstance(value, ast.Constant) or not isinstance(value.value, str): + return f"has a non-literal {keyword.arg}" + values[keyword.arg] = value.value + return values + + +def _to_declaration(method: str, values: dict[str, str]) -> Declaration | str: + """The declaration a call makes, or why it is not one.""" + kind = KIND_METHODS[method] + if kind == CONNECTION_KIND: + unknown = set(values) - _CONNECTION_KEYWORDS + if unknown: + return f"has an argument a connection does not take: {', '.join(sorted(unknown))}" + connection_id = values.get("id") + if connection_id is None: + return "is missing an id" + if not CONNECTION_ID_PATTERN.match(connection_id): + return "has an id that is not a connection id (a GUID)" + connector = values.get("connector") + if connector is None: + return "is missing a connector" + if not connector.strip(): + return "has an empty connector" + return Declaration( + kind=kind, + name=values.get("name", ""), + folder_path="", + type=connector, + id=connection_id, + ) + + allowed = set(_COMMON_KEYWORDS) + if kind in TYPED_KINDS: + allowed.add("type") + if kind == SKILL_BUNDLE_KIND: + allowed.add("version") + unknown = set(values) - allowed + if unknown: + return f"has an argument a {kind} does not take: {', '.join(sorted(unknown))}" + name = values.get("name") + if name is None: + return "is missing a name" + if not name.strip(): + return "has an empty name" + type_ = values.get("type") + if type_ is not None and not type_.strip(): + return "has an empty type" + version = values.get("version") + if version is not None and version.strip().lower() in ("", "latest"): + version = None + return Declaration( + kind=kind, + name=name, + folder_path=normalize_folder_path(values.get("folder_path")) or "", + type=type_, + version=version, + ) + + +def _bound_name(statement: ast.stmt) -> str | None: + """The single name an assignment binds, when it binds exactly one.""" + if isinstance(statement, ast.Assign) and len(statement.targets) == 1: + target = statement.targets[0] + return target.id if isinstance(target, ast.Name) else None + if isinstance(statement, ast.AnnAssign) and isinstance(statement.target, ast.Name): + return statement.target.id + return None + + +def _statement_value(statement: ast.stmt) -> ast.expr | None: + if isinstance(statement, (ast.Assign, ast.AnnAssign, ast.Expr)): + return statement.value + return None + + +def _imports_helper(tree: ast.Module) -> bool: + """Whether the module binds the SDK helper as ``resource``; ``resource as r`` does not.""" + from ._model import SDK_MODULE + + for statement in tree.body: + if not isinstance(statement, ast.ImportFrom) or statement.level != 0: + continue + if statement.module != SDK_MODULE: + continue + for alias in statement.names: + if alias.name == "*": + return True + if alias.name == SDK_HELPER_NAME and alias.asname in ( + None, + SDK_HELPER_NAME, + ): + return True + return False + + +def _class_info(tree: ast.Module, lines: list[str]) -> ClassInfo | None: + for statement in tree.body: + if isinstance(statement, ast.ClassDef) and statement.name == CLASS_NAME: + first, last = statement.body[0], statement.body[-1] + indent = lines[first.lineno - 1][: first.col_offset] + taken: set[str] = set() + for member in statement.body: + bound = _bound_name(member) + if bound: + taken.add(bound) + elif isinstance( + member, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef) + ): + taken.add(member.name) + only_placeholder = len(statement.body) == 1 and ( + isinstance(first, ast.Pass) + or ( + isinstance(first, ast.Expr) + and isinstance(first.value, ast.Constant) + and first.value.value is Ellipsis + ) + ) + return ClassInfo( + lineno=statement.lineno, + end_lineno=statement.end_lineno or statement.lineno, + body_lines=(first.lineno, last.end_lineno or last.lineno), + indent=indent, + taken=frozenset(taken), + only_placeholder=only_placeholder, + ) + return None + + +def parse_declarations(source: str, file_name: str) -> ParsedDeclarations: + """Reads the declarations in ``source``, the text of ``file_name``. + + Raises: + DeclarationsSyntaxError: The file is not valid Python. + """ + try: + tree = ast.parse(source, filename=file_name) + except SyntaxError as error: + raise DeclarationsSyntaxError(file_name, error) from error + + lines = source.split("\n") + declarations: list[ParsedDeclaration] = [] + diagnostics: list[str] = [] + # A call that is the whole value of a statement, keyed by its node, so the + # walk below knows which calls can be removed as one statement. + statements: dict[int, tuple[str | None, tuple[int, int]]] = {} + for node in ast.walk(tree): + if isinstance(node, ast.stmt): + value = _statement_value(node) + if isinstance(value, ast.Call) and _declared_method(value): + statements[id(value)] = ( + _bound_name(node), + (node.lineno, node.end_lineno or node.lineno), + ) + + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + method = _declared_method(node) + if method is None: + continue + values = _literal_keywords(node) + result = values if isinstance(values, str) else _to_declaration(method, values) + if isinstance(result, str): + diagnostics.append( + f"{file_name}:{node.lineno}: resource.{method}() {result}; skipped" + ) + continue + attribute, statement_lines = statements.get(id(node), (None, None)) + declarations.append( + ParsedDeclaration( + declaration=result, + attribute=attribute, + lineno=node.lineno, + statement_lines=statement_lines, + ) + ) + + declarations.sort(key=lambda parsed: parsed.lineno) + return ParsedDeclarations( + declarations=declarations, + diagnostics=diagnostics, + project_resources=_class_info(tree, lines) if tree.body else None, + imports_helper=_imports_helper(tree), + ) diff --git a/packages/uipath/src/uipath/_cli/_declarations/_project.py b/packages/uipath/src/uipath/_cli/_declarations/_project.py new file mode 100644 index 000000000..6dce7ab17 --- /dev/null +++ b/packages/uipath/src/uipath/_cli/_declarations/_project.py @@ -0,0 +1,95 @@ +"""Where a project keeps its declarations and bindings files.""" + +import os +from dataclasses import dataclass + +from uipath.platform.constants import PYTHON_CONFIGURATION_FILE, UIPATH_BINDINGS_FILE + +from ._model import DECLARATIONS_FILE_NAME + +# Where the declarations may live, relative to the project root, in lookup order. +DECLARATIONS_PATHS = ( + DECLARATIONS_FILE_NAME, + os.path.join("src", DECLARATIONS_FILE_NAME), +) + + +class NotAProjectError(Exception): + """The folder holds no Python project the declarations could belong to.""" + + +@dataclass(frozen=True) +class DeclarationsFile: + """The project's declarations file, or the one to create when there is none. + + Attributes: + path: The file's absolute path. + relative_path: The path relative to the project root, for messages. + content: The file's text; ``""`` when it does not exist yet. + exists: Whether the file exists. + """ + + path: str + relative_path: str + content: str + exists: bool + + +def resolve_project_root(project_path: str | None) -> str: + """The project folder: ``project_path`` or the working directory, as an absolute path. + + Raises: + NotAProjectError: The folder has neither a ``pyproject.toml`` nor a + declarations file, so there is no project to declare resources for. + """ + root = os.path.abspath(project_path or os.getcwd()) + if not os.path.isdir(root): + raise NotAProjectError(f"{root} is not a folder.") + if find_declarations_path(root) is None and not os.path.isfile( + os.path.join(root, PYTHON_CONFIGURATION_FILE) + ): + raise NotAProjectError( + f"No {PYTHON_CONFIGURATION_FILE} in {root}. Run the command from the " + f"project folder, or pass --project-path." + ) + return root + + +def find_declarations_path(root: str) -> str | None: + """The absolute path of the project's ``uipath_resources.py``, or ``None`` when it has none.""" + for relative in DECLARATIONS_PATHS: + path = os.path.join(root, relative) + if os.path.isfile(path): + return path + return None + + +def read_declarations_file(root: str) -> DeclarationsFile: + """The project's declarations file, read, or the one ``uipath resources add`` would create.""" + path = find_declarations_path(root) + if path is None: + return DeclarationsFile( + path=os.path.join(root, DECLARATIONS_FILE_NAME), + relative_path=DECLARATIONS_FILE_NAME, + content="", + exists=False, + ) + with open(path, encoding="utf-8", newline="") as f: + content = f.read() + return DeclarationsFile( + path=path, + relative_path=os.path.relpath(path, root), + content=content, + exists=True, + ) + + +def write_declarations_file(file: DeclarationsFile, content: str) -> None: + """Writes ``content`` to the declarations file, creating it when needed.""" + with open(file.path, "w", encoding="utf-8", newline="") as f: + f.write(content) + + +def bindings_path(root: str) -> str: + """The project's ``bindings.json``, at its root.""" + return os.path.join(root, UIPATH_BINDINGS_FILE) diff --git a/packages/uipath/src/uipath/_cli/cli_pack.py b/packages/uipath/src/uipath/_cli/cli_pack.py index 510eeadff..00be2c7bc 100644 --- a/packages/uipath/src/uipath/_cli/cli_pack.py +++ b/packages/uipath/src/uipath/_cli/cli_pack.py @@ -392,6 +392,11 @@ def pack(root, nolock): config = get_project_config(root) validate_config(config) + # The bindings a package carries are derived from uipath_resources.py. + from .cli_resources import regenerate_bindings + + regenerate_bindings(root) + with console.spinner("Packaging project ..."): try: # Handle uv operations before packaging, unless nolock is specified diff --git a/packages/uipath/src/uipath/_cli/cli_push.py b/packages/uipath/src/uipath/_cli/cli_push.py index b9cbeb4ee..3f8c92130 100644 --- a/packages/uipath/src/uipath/_cli/cli_push.py +++ b/packages/uipath/src/uipath/_cli/cli_push.py @@ -235,6 +235,11 @@ def push(root: str, ignore_resources: bool, nolock: bool, overwrite: bool) -> No ensure_config_file(root) config = get_project_config(root) validate_config(config) + + # The bindings pushed (and the resources imported) are derived from uipath_resources.py. + from .cli_resources import regenerate_bindings + + regenerate_bindings(root) validate_project_files(root) project_id = UiPathConfig.project_id diff --git a/packages/uipath/src/uipath/_cli/cli_resources.py b/packages/uipath/src/uipath/_cli/cli_resources.py new file mode 100644 index 000000000..5c12ca89f --- /dev/null +++ b/packages/uipath/src/uipath/_cli/cli_resources.py @@ -0,0 +1,584 @@ +"""``uipath resources``: the resources a coded project declares in ``uipath_resources.py``. + +The file is the one place a project names the platform resources it uses +(see ``uipath.resources``), and ``bindings.json`` is derived from it, so the +bindings a package carries are exactly what the code declares. These commands +edit the file as text and never import it; they make no requests, so they work +offline. Looking a resource up in the tenant and adding it to a solution is the +``uip`` CLI's part (``uip codedagent resources``, ``uip function resources``), +which forwards to these commands. +""" + +import json +from typing import Any + +import click + +from uipath.resources import ASSET_TYPES, BUCKET_TYPES, RESOURCE_KINDS + +from ._telemetry import track_command +from ._utils._console import ConsoleLogger +from ._utils._context import CliContext + +console = ConsoleLogger() + +_KIND_CHOICES = list(RESOURCE_KINDS) +_PROJECT_PATH_HELP = ( + "Project folder, the one with pyproject.toml (default: current directory)" +) + + +def _project_path_option(f: Any) -> Any: + return click.option("--project-path", help=_PROJECT_PATH_HELP)(f) + + +def _format_option(f: Any) -> Any: + return click.option( + "--format", + "format", + type=click.Choice(["json", "table"]), + default=None, + help="Output format (overrides the global --format)", + )(f) + + +def _kind_option(help_text: str) -> Any: + return click.option( + "--kind", + metavar="", + help=f"{help_text}: one of {', '.join(_KIND_CHOICES)} (mcp_server and the other snake_case spellings work too)", + ) + + +def _wants_json() -> bool: + """Whether the command runs with ``--format json``, on the command or on ``uipath`` itself.""" + ctx = click.get_current_context(silent=True) + if ctx is None: + return False + if ctx.params.get("format") is not None: + return ctx.params["format"] == "json" + if isinstance(ctx.obj, CliContext): + return ctx.obj.output_format == "json" + return False + + +def _emit(data: Any) -> None: + """Prints ``data`` as JSON when the CLI runs with ``--format json``.""" + click.echo(json.dumps(data, indent=2)) + + +def _warn(message: str) -> None: + """A warning, kept off stdout when stdout carries JSON.""" + if _wants_json(): + click.echo(f"Warning: {message}", err=True) + else: + console.warning(message) + + +def _row(declaration: Any) -> dict[str, Any]: + row: dict[str, Any] = {"kind": declaration.kind, "name": declaration.name} + if declaration.id: + row["id"] = declaration.id + if declaration.folder_path: + row["folderPath"] = declaration.folder_path + if declaration.type: + row["type"] = declaration.type + if declaration.version: + row["version"] = declaration.version + return row + + +def _describe(declaration: Any) -> str: + parts = [ + f"{declaration.kind} {click.style(declaration.name or declaration.id, fg='cyan')}" + ] + if declaration.id and declaration.name: + parts.append(f"id {declaration.id}") + if declaration.folder_path: + parts.append(f"folder {declaration.folder_path}") + if declaration.type: + parts.append(f"type {declaration.type}") + if declaration.version: + parts.append(f"version {declaration.version}") + return ", ".join(parts) + + +def _fail(message: str) -> None: + if _wants_json(): + _emit({"error": message}) + click.get_current_context().exit(1) + console.error(message) + + +def _resolve_root(project_path: str | None) -> str: + from ._declarations._project import NotAProjectError, resolve_project_root + + try: + return resolve_project_root(project_path) + except NotAProjectError as error: + _fail(str(error)) + raise AssertionError("unreachable") from error + + +def _checked_type(kind: str, type_: str | None) -> str | None: + """``--type`` checked against the values the kind takes.""" + from ._declarations._model import TYPED_KINDS + + if type_ is None: + return None + if kind not in TYPED_KINDS: + _fail( + f"--type does not apply to a {kind}: only assets, buckets and processes " + f"carry one (a connection takes --connector)." + ) + if kind == "asset" and type_.lower() not in ASSET_TYPES: + _fail(f'"{type_}" is not an asset type. Use one of: {", ".join(ASSET_TYPES)}.') + if kind == "bucket" and type_.lower() not in BUCKET_TYPES: + _fail(f'"{type_}" is not a bucket type. Use one of: {", ".join(BUCKET_TYPES)}.') + return type_.lower() if kind in ("asset", "bucket") else type_ + + +def _declaration_from_options( + name: str | None, + kind: str, + folder_path: str | None, + type_: str | None, + connection_id: str | None, + connector: str | None, + version: str | None, +) -> Any: + from ._declarations._model import ( + CONNECTION_ID_PATTERN, + CONNECTION_KIND, + SKILL_BUNDLE_KIND, + Declaration, + normalize_folder_path, + ) + + if kind == CONNECTION_KIND: + if not connection_id or not connector: + _fail( + "A connection is declared by its id and connector key: pass --id and " + "--connector (uip codedagent resources add looks them up by name)." + ) + assert connection_id is not None + if not CONNECTION_ID_PATTERN.match(connection_id): + _fail(f'"{connection_id}" is not a connection id (a GUID).') + if folder_path is not None or type_ is not None or version is not None: + _fail("--folder-path, --type and --version do not apply to a connection.") + return Declaration( + kind=kind, name=name or "", folder_path="", type=connector, id=connection_id + ) + if not name or not name.strip(): + _fail("Pass the resource name, as Orchestrator shows it.") + if connection_id is not None or connector is not None: + _fail("--id and --connector apply to a connection only.") + if version is not None and kind != SKILL_BUNDLE_KIND: + _fail("--version applies to a skill bundle only.") + assert name is not None + if version is not None and version.strip().lower() in ("", "latest"): + version = None + return Declaration( + kind=kind, + name=name, + folder_path=normalize_folder_path(folder_path) or "", + type=_checked_type(kind, type_), + version=version, + ) + + +def _check_saved_declaration(file: Any, declaration: Any) -> None: + """Fails when the same resource is already declared with another type or version: the file is the source of truth, so the line is edited, not overwritten.""" + from ._declarations._parser import parse_declarations + + if not file.exists: + return + saved = parse_declarations(file.content, file.relative_path).find( + declaration.kind, declaration.key + ) + if saved is None: + return + for field_name in ("type", "version"): + wanted = getattr(declaration, field_name) + current = getattr(saved.declaration, field_name) + if wanted is not None and current != wanted: + has = ( + f"with {field_name} {current}" if current else f"without a {field_name}" + ) + _fail( + f"{declaration.label} is already declared in {file.relative_path}:" + f"{saved.lineno} {has}. Edit or remove that line to change the " + f"{field_name}, then run the command again." + ) + + +def _resolved_kind(kind: str | None) -> str: + from ._declarations._model import resolve_kind + + if kind is None: + _fail(f"Pass --kind with one of: {', '.join(_KIND_CHOICES)}.") + assert kind is not None + resolved = resolve_kind(kind) + if resolved is None: + _fail( + f'"{kind}" is not a resource kind. Use one of: {", ".join(_KIND_CHOICES)}.' + ) + assert resolved is not None + return resolved + + +def _report_sync(sync: Any, quiet: bool = False) -> None: + for diagnostic in sync.diagnostics: + _warn(diagnostic) + if quiet: + return + state = "Updated" if sync.changed else "Unchanged" + console.success( + f"{state} {click.style(sync.path, fg='cyan')} from {sync.declarations_file}: " + f"{sync.derived} declared, {sync.kept} hand-written kept." + ) + + +@click.group() +def resources() -> None: + """Declare the resources the project uses, in uipath_resources.py. + + \b + The file is the one place a coded project names the platform resources it + uses; bindings.json is derived from it by `uipath resources bindings`, + `uipath pack` and `uipath push`. These commands work offline and never + import the file. + + \b + Examples: + uipath resources add InvoiceThreshold --kind asset --folder-path Finance/Shared --type integer + uipath resources add InvoiceReview --kind queue + uipath resources add "Finance Slack" --kind connection --id 3121165f-ce9b-4503-8c10-289ae6b21bd8 --connector uipath-slack + uipath resources list + uipath resources remove InvoiceReview --kind queue + uipath resources bindings + """ # noqa: D301 + + +@resources.command(name="add") +@click.argument("name", required=False) +@_kind_option("Resource kind") +@click.option( + "--folder-path", + help="Folder the resource sits in. Omit it for a resource the solution creates.", +) +@click.option( + "--type", + "type_", + help=( + "Asset value type (text, integer, bool, credential, secret, json), bucket " + "provider (orchestrator, amazon, azure) or process kind." + ), +) +@click.option("--id", "connection_id", help="A connection's id (a GUID)") +@click.option("--connector", help="A connection's connector key, e.g. uipath-slack") +@click.option( + "--version", + help="A skill bundle's pinned version; omit it or pass 'latest' to take the newest at run start.", +) +@click.option( + "--skip-verify", + is_flag=True, + hidden=True, + help="Accepted for parity with `uip resources add`; declarations here are never looked up.", +) +@_format_option +@_project_path_option +@track_command("resources add") +def add( + name: str | None, + kind: str | None, + folder_path: str | None, + type_: str | None, + connection_id: str | None, + connector: str | None, + version: str | None, + skip_verify: bool, + format: str | None, + project_path: str | None, +) -> None: + """Declare a resource in uipath_resources.py. + + Creates the file, with the import and the ProjectResources class, when + the project has none, and appends the declaration as a new attribute. + A resource of the same kind and key that is already declared leaves the + file unchanged. Nothing is looked up: the declaration is written as given. + + \b + Examples: + uipath resources add InvoiceThreshold --kind asset --folder-path Finance/Shared --type integer + uipath resources add InvoiceReview --kind queue + uipath resources add Invoices --kind bucket --type orchestrator + uipath resources add "Finance Slack" --kind connection --id 3121165f-ce9b-4503-8c10-289ae6b21bd8 --connector uipath-slack + uipath resources add finance --kind skillBundle --folder-path Shared/Skills --version 7 + """ # noqa: D301 + from ._declarations._editor import DeclarationsFileError, insert_declaration + from ._declarations._parser import DeclarationsSyntaxError + from ._declarations._project import read_declarations_file, write_declarations_file + + root = _resolve_root(project_path) + resolved_kind = _resolved_kind(kind) + declaration = _declaration_from_options( + name, resolved_kind, folder_path, type_, connection_id, connector, version + ) + + file = read_declarations_file(root) + try: + _check_saved_declaration(file, declaration) + result = insert_declaration(file.content, declaration, file.relative_path) + except (DeclarationsSyntaxError, DeclarationsFileError) as error: + _fail(str(error)) + return + if result.added: + write_declarations_file(file, result.source) + + if _wants_json(): + _emit( + { + "added": result.added, + **_row(declaration), + **({"attribute": result.attribute} if result.attribute else {}), + "file": file.relative_path, + } + ) + return + if result.added: + verb = "Created" if not file.exists else "Updated" + console.success( + f"{verb} {click.style(file.relative_path, fg='cyan')}: " + f"{click.style(result.attribute or '', fg='cyan')} = {_describe(declaration)}" + ) + console.hint( + f"Run {click.style('uipath resources bindings', fg='cyan')} to regenerate " + f"bindings.json now; pack and push do it for you." + ) + else: + console.info( + f"{_describe(declaration)} is already declared in {file.relative_path}." + ) + + +@resources.command(name="list") +@_kind_option("Only declarations of this kind") +@_format_option +@_project_path_option +@track_command("resources list") +def list_declarations( + kind: str | None, format: str | None, project_path: str | None +) -> None: + """List the resources declared in uipath_resources.py. + + A declaration the CLI cannot read (a value that is not a string literal) + is reported as a warning with its line and left out. + + \b + Examples: + uipath resources list + uipath resources list --kind asset + uipath --format json resources list + """ # noqa: D301 + from ._declarations._parser import DeclarationsSyntaxError, parse_declarations + from ._declarations._project import read_declarations_file + + root = _resolve_root(project_path) + wanted = _resolved_kind(kind) if kind else None + file = read_declarations_file(root) + rows: list[Any] = [] + if file.exists: + try: + parsed = parse_declarations(file.content, file.relative_path) + except DeclarationsSyntaxError as error: + _fail(str(error)) + return + for diagnostic in parsed.diagnostics: + _warn(diagnostic) + rows = [ + parsed_declaration + for parsed_declaration in parsed.declarations + if wanted is None or parsed_declaration.declaration.kind == wanted + ] + + if _wants_json(): + _emit( + [ + { + **_row(row.declaration), + **({"attribute": row.attribute} if row.attribute else {}), + } + for row in rows + ] + ) + return + if not file.exists: + console.info( + f"No {file.relative_path} in the project; " + f"run {click.style('uipath resources add', fg='cyan')} to declare a resource." + ) + return + if not rows: + console.info( + f"No {wanted + ' ' if wanted else ''}declarations in {file.relative_path}." + ) + return + for row in rows: + attribute = f"{row.attribute} = " if row.attribute else "" + console.info(f" {attribute}{_describe(row.declaration)}") + + +@resources.command(name="remove") +@click.argument("name", required=False) +@_kind_option("Resource kind") +@click.option( + "--folder-path", + help="The folder the declaration names; omit it for a declaration without one.", +) +@click.option("--id", "connection_id", help="A connection's id (a GUID)") +@_format_option +@_project_path_option +@track_command("resources remove") +def remove( + name: str | None, + kind: str | None, + folder_path: str | None, + connection_id: str | None, + format: str | None, + project_path: str | None, +) -> None: + """Remove a declaration from uipath_resources.py. + + Removes the statement that declares the resource of that kind, name and + folder (a connection by its id). Code that still uses the attribute is + left to you. bindings.json drops the binding at the next + `uipath resources bindings`, pack or push. + + \b + Examples: + uipath resources remove InvoiceReview --kind queue + uipath resources remove InvoiceThreshold --kind asset --folder-path Finance/Shared + uipath resources remove --kind connection --id 3121165f-ce9b-4503-8c10-289ae6b21bd8 + """ # noqa: D301 + from ._declarations._editor import DeclarationsFileError, remove_declaration + from ._declarations._model import ( + CONNECTION_KIND, + binding_key, + normalize_folder_path, + ) + from ._declarations._parser import DeclarationsSyntaxError + from ._declarations._project import read_declarations_file, write_declarations_file + + root = _resolve_root(project_path) + resolved_kind = _resolved_kind(kind) + if resolved_kind == CONNECTION_KIND: + if not connection_id: + _fail("A connection is identified by its id: pass --id.") + assert connection_id is not None + key = connection_id + label = f"connection {connection_id}" + else: + if not name or not name.strip(): + _fail("Pass the resource name, as declared.") + assert name is not None + key = binding_key(name, normalize_folder_path(folder_path)) + label = f"{resolved_kind} {name}" + + file = read_declarations_file(root) + if not file.exists: + _fail(f"No {file.relative_path} in the project; nothing to remove.") + try: + result = remove_declaration( + file.content, resolved_kind, key, file.relative_path + ) + except (DeclarationsSyntaxError, DeclarationsFileError) as error: + _fail(str(error)) + return + if result.removed: + write_declarations_file(file, result.source) + + if _wants_json(): + _emit( + { + "removed": result.removed, + "kind": resolved_kind, + "key": key, + **({"attribute": result.attribute} if result.attribute else {}), + "file": file.relative_path, + } + ) + return + if result.removed: + attribute = f" ({result.attribute})" if result.attribute else "" + console.success(f"Removed {label}{attribute} from {file.relative_path}.") + else: + console.info(f"{label} is not declared in {file.relative_path}.") + + +@resources.command(name="bindings") +@_format_option +@_project_path_option +@track_command("resources bindings") +def bindings(format: str | None, project_path: str | None) -> None: + """Write bindings.json from the declarations in uipath_resources.py. + + One binding per declared resource, after the hand-written entries the + declarations leave in place (an entry of the same kind and key is + replaced). `uipath pack` and `uipath push` run this first, so the + package carries exactly what the code declares. + + \b + Examples: + uipath resources bindings + """ # noqa: D301 + from ._declarations._bindings import BindingsFileError, sync_bindings + from ._declarations._parser import DeclarationsSyntaxError + from ._declarations._project import read_declarations_file + + root = _resolve_root(project_path) + try: + sync = sync_bindings(root) + except (DeclarationsSyntaxError, BindingsFileError) as error: + _fail(str(error)) + return + if sync is None: + file = read_declarations_file(root) + _fail( + f"No {file.relative_path} in the project; " + f"run `uipath resources add` to declare a resource first." + ) + return + if _wants_json(): + _emit( + { + "file": sync.path, + "declarationsFile": sync.declarations_file, + "declared": sync.declared, + "derived": sync.derived, + "kept": sync.kept, + "changed": sync.changed, + "diagnostics": sync.diagnostics, + } + ) + return + _report_sync(sync) + + +def regenerate_bindings(root: str) -> None: + """Regenerates ``bindings.json`` before a pack or a push, when the project declares resources. + + A project without ``uipath_resources.py`` keeps its ``bindings.json`` as it + is. Errors in either file stop the command: a package built on stale + bindings would deploy wrong. + """ + from ._declarations._bindings import BindingsFileError, sync_bindings + from ._declarations._parser import DeclarationsSyntaxError + + try: + sync = sync_bindings(root) + except (DeclarationsSyntaxError, BindingsFileError) as error: + console.error(str(error)) + if sync is not None: + _report_sync(sync, quiet=not sync.changed) diff --git a/packages/uipath/tests/cli/test_resource_declarations.py b/packages/uipath/tests/cli/test_resource_declarations.py new file mode 100644 index 000000000..9141155bc --- /dev/null +++ b/packages/uipath/tests/cli/test_resource_declarations.py @@ -0,0 +1,597 @@ +"""Tests for reading, editing and deriving bindings from ``uipath_resources.py``.""" + +import json +import os +import textwrap + +import pytest + +from uipath._cli._declarations._bindings import ( + BindingsFileError, + binding_entry, + derive_bindings, + sync_bindings, +) +from uipath._cli._declarations._editor import ( + DeclarationsFileError, + insert_declaration, + remove_declaration, + render_declaration, + to_python_identifier, +) +from uipath._cli._declarations._model import Declaration, resolve_kind +from uipath._cli._declarations._parser import ( + DeclarationsSyntaxError, + parse_declarations, +) + +FILE = "uipath_resources.py" +CONNECTION_ID = "3121165f-ce9b-4503-8c10-289ae6b21bd8" + + +def src(body: str) -> str: + return textwrap.dedent(body).lstrip("\n") + + +class TestParse: + def test_reads_every_kind_with_its_arguments(self) -> None: + source = src( + f''' + """The project's resources.""" + from uipath.resources import resource + + + class ProjectResources: + threshold = resource.asset(name="InvoiceThreshold", folder_path="Finance/Shared", type="integer") + review = resource.queue(name="Review") # the project's own folder + files = resource.bucket(name='Invoices', folder_path='.', type='orchestrator') + runner = resource.process(name="Runner", folder_path="solution_folder", type="agent") + docs = resource.mcp_server(name="Docs", folder_path="Shared") + invoices = resource.entity(name="Invoices") + slack = resource.connection(id="{CONNECTION_ID}", connector="uipath-slack", name="Finance Slack") + skills = resource.skill_bundle(name="finance", folder_path="Shared/Skills", version="7") + latest = resource.skill_bundle(name="ops", version="latest") + ''' + ) + parsed = parse_declarations(source, FILE) + assert parsed.diagnostics == [] + assert parsed.imports_helper + assert [p.attribute for p in parsed.declarations] == [ + "threshold", + "review", + "files", + "runner", + "docs", + "invoices", + "slack", + "skills", + "latest", + ] + assert parsed.resources == [ + Declaration( + kind="asset", + name="InvoiceThreshold", + folder_path="Finance/Shared", + type="integer", + ), + Declaration(kind="queue", name="Review"), + Declaration(kind="bucket", name="Invoices", type="orchestrator"), + Declaration(kind="process", name="Runner", type="agent"), + Declaration(kind="mcpServer", name="Docs", folder_path="Shared"), + Declaration(kind="entity", name="Invoices"), + Declaration( + kind="connection", + name="Finance Slack", + type="uipath-slack", + id=CONNECTION_ID, + ), + Declaration( + kind="skillBundle", + name="finance", + folder_path="Shared/Skills", + version="7", + ), + Declaration(kind="skillBundle", name="ops"), + ] + assert [d.key for d in parsed.resources][:2] == [ + "InvoiceThreshold.Finance/Shared", + "Review", + ] + assert parsed.resources[6].key == CONNECTION_ID + + @pytest.mark.parametrize( + ("call", "reason"), + [ + ("resource.asset(name=ASSET_NAME)", "has a non-literal name"), + ('resource.queue("Review")', "has a positional argument"), + ('resource.queue(name=f"{x}")', "has a non-literal name"), + ("resource.queue(**kwargs)", "unpacks its arguments"), + ('resource.queue(folder_path="Shared")', "is missing a name"), + ('resource.queue(name="")', "has an empty name"), + ( + 'resource.queue(name="Q", type="text")', + "has an argument a queue does not take: type", + ), + ( + 'resource.bucket(name="B", region="eu")', + "has an argument a bucket does not take: region", + ), + ('resource.connection(connector="x")', "is missing an id"), + ( + 'resource.connection(id="nope", connector="x")', + "has an id that is not a connection id (a GUID)", + ), + (f'resource.connection(id="{CONNECTION_ID}")', "is missing a connector"), + ( + f'resource.connection(id="{CONNECTION_ID}", connector=" ")', + "has an empty connector", + ), + ( + f'resource.connection(id="{CONNECTION_ID}", connector="x", folder_path="F")', + "has an argument a connection does not take: folder_path", + ), + ], + ) + def test_a_call_that_breaks_the_rules_is_a_diagnostic_with_its_line( + self, call: str, reason: str + ) -> None: + source = src( + f""" + from uipath.resources import resource + + + class ProjectResources: + good = resource.queue(name="Good") + bad = {call} + """ + ) + parsed = parse_declarations(source, FILE) + assert [d.name for d in parsed.resources] == ["Good"] + assert len(parsed.diagnostics) == 1 + assert parsed.diagnostics[0].startswith(f"{FILE}:6: resource.") + assert parsed.diagnostics[0].endswith(f"{reason}; skipped") + + def test_calls_in_comments_and_strings_are_not_declarations(self) -> None: + source = src( + """ + from uipath.resources import resource + + # old = resource.queue(name="Old") + DOC = 'resource.queue(name="InString")' + + + class ProjectResources: + review = resource.queue(name="Review") + """ + ) + assert [d.name for d in parse_declarations(source, FILE).resources] == [ + "Review" + ] + + def test_a_call_nested_in_an_expression_is_read_but_not_a_statement(self) -> None: + source = src( + """ + from uipath.resources import resource + + + class ProjectResources: + queues = [resource.queue(name="Nested")] + """ + ) + parsed = parse_declarations(source, FILE) + assert parsed.resources == [Declaration(kind="queue", name="Nested")] + assert parsed.declarations[0].attribute is None + assert parsed.declarations[0].statement_lines is None + + def test_an_aliased_helper_is_not_the_import(self) -> None: + source = "from uipath.resources import resource as r\n\n\nclass ProjectResources:\n pass\n" + parsed = parse_declarations(source, FILE) + assert not parsed.imports_helper + assert parsed.project_resources is not None + assert parsed.project_resources.only_placeholder + + def test_a_syntax_error_names_the_line(self) -> None: + with pytest.raises(DeclarationsSyntaxError, match=rf"{FILE}:2: "): + parse_declarations( + 'class ProjectResources:\n x = resource.queue(name="A"\n', FILE + ) + + def test_find_matches_kind_and_key_without_case_on_the_kind(self) -> None: + source = src( + """ + from uipath.resources import resource + + + class ProjectResources: + a = resource.asset(name="A", folder_path="Shared") + """ + ) + parsed = parse_declarations(source, FILE) + assert parsed.find("Asset", "A.Shared") is not None + assert parsed.find("asset", "A") is None + + +class TestResolveKind: + @pytest.mark.parametrize( + ("value", "kind"), + [ + ("asset", "asset"), + ("mcpServer", "mcpServer"), + ("mcp_server", "mcpServer"), + ("MCPSERVER", "mcpServer"), + ("skill-bundle", "skillBundle"), + ("widget", None), + ], + ) + def test_accepts_binding_kinds_and_method_names( + self, value: str, kind: str | None + ) -> None: + assert resolve_kind(value) == kind + + +class TestIdentifier: + @pytest.mark.parametrize( + ("name", "taken", "expected"), + [ + ("InvoiceThreshold", set(), "invoice_threshold"), + ("Finance Slack", set(), "finance_slack"), + ("my-queue.v2", set(), "my_queue_v2"), + ("2FA", set(), "_2_fa"), + ("class", set(), "class_"), + ("resource", set(), "resource_2"), + ("Review", {"review"}, "review_2"), + ("Review", {"review", "review_2"}, "review_3"), + ("***", set(), "resource_2"), + ], + ) + def test_snake_case_unique_and_never_a_keyword( + self, name: str, taken: set[str], expected: str + ) -> None: + assert to_python_identifier(name, taken) == expected + + +class TestInsert: + def test_a_blank_file_becomes_a_new_file(self) -> None: + result = insert_declaration( + "", + Declaration( + kind="asset", + name="InvoiceThreshold", + folder_path="Finance/Shared", + type="integer", + ), + FILE, + ) + assert result.added + assert result.attribute == "invoice_threshold" + assert result.source == src( + """ + from uipath.resources import resource + + + class ProjectResources: + invoice_threshold = resource.asset(name="InvoiceThreshold", folder_path="Finance/Shared", type="integer") + """ + ) + + def test_appends_after_the_last_member_with_the_class_indent(self) -> None: + source = src( + """ + from uipath.resources import resource + + + class ProjectResources: + review = resource.queue(name="Review") + + def helper(self): + return 1 + """ + ) + result = insert_declaration( + source, Declaration(kind="queue", name="Review 2"), FILE + ) + assert result.added and result.attribute == "review_2" + assert result.source.endswith( + ' return 1\n review_2 = resource.queue(name="Review 2")\n' + ) + + def test_the_same_kind_and_key_is_not_added_twice(self) -> None: + source = insert_declaration( + "", Declaration(kind="queue", name="Review"), FILE + ).source + again = insert_declaration( + source, Declaration(kind="queue", name="Review"), FILE + ) + assert not again.added + assert again.source == source + # Same name in another folder, or another kind with the same name, is another resource. + assert insert_declaration( + source, Declaration(kind="queue", name="Review", folder_path="Shared"), FILE + ).added + assert insert_declaration( + source, Declaration(kind="asset", name="Review"), FILE + ).added + + def test_replaces_a_placeholder_body_and_adds_the_import_after_docstring_and_future( + self, + ) -> None: + source = '"""Resources."""\nfrom __future__ import annotations\n\n\nclass ProjectResources:\n ...\n' + result = insert_declaration( + source, Declaration(kind="queue", name="Review"), FILE + ) + assert result.source == ( + '"""Resources."""\nfrom __future__ import annotations\n' + "from uipath.resources import resource\n\n\n" + 'class ProjectResources:\n review = resource.queue(name="Review")\n' + ) + + def test_the_import_goes_after_a_shebang_and_encoding_cookie(self) -> None: + source = "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nclass ProjectResources:\n pass\n" + result = insert_declaration( + source, Declaration(kind="queue", name="Review"), FILE + ) + assert result.source.startswith( + "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom uipath.resources import resource\n" + ) + + def test_keeps_crlf_line_endings(self) -> None: + source = 'from uipath.resources import resource\r\n\r\n\r\nclass ProjectResources:\r\n a = resource.queue(name="A")\r\n' + result = insert_declaration(source, Declaration(kind="queue", name="B"), FILE) + assert result.source == source + ' b = resource.queue(name="B")\r\n' + + def test_a_file_without_the_class_is_refused(self) -> None: + with pytest.raises(DeclarationsFileError, match="no `class ProjectResources:`"): + insert_declaration( + "x = 1\n", Declaration(kind="queue", name="Review"), FILE + ) + + def test_renders_a_connection_by_id_and_connector(self) -> None: + line = render_declaration( + "slack", + Declaration( + kind="connection", + name="Finance Slack", + type="uipath-slack", + id=CONNECTION_ID, + ), + ) + assert ( + line + == f' slack = resource.connection(id="{CONNECTION_ID}", connector="uipath-slack", name="Finance Slack")' + ) + unnamed = insert_declaration( + "", + Declaration( + kind="connection", name="", type="uipath-slack", id=CONNECTION_ID + ), + FILE, + ) + assert unnamed.attribute == "uipath_slack" + + def test_renders_a_skill_bundle_version_and_escapes_quotes(self) -> None: + assert ( + render_declaration( + "s", Declaration(kind="skillBundle", name='a"b', version="7") + ) + == ' s = resource.skill_bundle(name="a\\"b", version="7")' + ) + assert ( + render_declaration( + "m", Declaration(kind="mcpServer", name="Docs", folder_path="Shared") + ) + == ' m = resource.mcp_server(name="Docs", folder_path="Shared")' + ) + + +class TestRemove: + SOURCE = src( + """ + from uipath.resources import resource + + + class ProjectResources: + a = resource.queue(name="A") + b = resource.asset( + name="B", + folder_path="Shared", + ) # multi-line + """ + ) + + def test_removes_the_whole_statement(self) -> None: + result = remove_declaration(self.SOURCE, "asset", "B.Shared", FILE) + assert result.removed and result.attribute == "b" + assert ( + result.source + == 'from uipath.resources import resource\n\n\nclass ProjectResources:\n a = resource.queue(name="A")\n' + ) + + def test_nothing_matching_leaves_the_file(self) -> None: + result = remove_declaration(self.SOURCE, "asset", "B", FILE) + assert not result.removed + assert result.source == self.SOURCE + + def test_the_last_member_leaves_a_pass(self) -> None: + once = remove_declaration(self.SOURCE, "queue", "A", FILE).source + twice = remove_declaration(once, "asset", "B.Shared", FILE) + assert twice.source.endswith("class ProjectResources:\n pass\n") + + def test_a_nested_call_is_left_to_the_user(self) -> None: + source = 'from uipath.resources import resource\n\n\nclass ProjectResources:\n q = [resource.queue(name="N")]\n' + with pytest.raises( + DeclarationsFileError, match=f"{FILE}:5: .*remove it by hand" + ): + remove_declaration(source, "queue", "N", FILE) + + +class TestDeriveBindings: + def test_entry_shapes(self) -> None: + asset = binding_entry( + Declaration( + kind="asset", + name="InvoiceThreshold", + folder_path="Finance/Shared", + type="integer", + ) + ) + assert asset == { + "resource": "asset", + "key": "InvoiceThreshold.Finance/Shared", + "value": { + "name": { + "defaultValue": "InvoiceThreshold", + "isExpression": False, + "displayName": "Name", + }, + "folderPath": { + "defaultValue": "Finance/Shared", + "isExpression": False, + "displayName": "Folder Path", + }, + }, + "metadata": { + "BindingsVersion": "2.2", + "SubType": "integer", + "Source": "code", + }, + } + queue = binding_entry(Declaration(kind="queue", name="Review")) + assert queue["key"] == "Review" + assert queue["value"]["folderPath"]["defaultValue"] == "." + assert queue["metadata"] == {"BindingsVersion": "2.2", "Source": "code"} + connection = binding_entry( + Declaration( + kind="connection", name="Slack", type="uipath-slack", id=CONNECTION_ID + ) + ) + assert connection == { + "resource": "connection", + "key": CONNECTION_ID, + "value": { + "ConnectionId": { + "defaultValue": CONNECTION_ID, + "isExpression": False, + "displayName": "Connection", + } + }, + "metadata": { + "BindingsVersion": "2.2", + "Connector": "uipath-slack", + "UseConnectionService": "true", + "SolutionsSupport": "true", + "Source": "code", + }, + } + bundle = binding_entry( + Declaration( + kind="skillBundle", + name="finance", + folder_path="Shared/Skills", + version="7", + ) + ) + assert bundle["key"] == "finance.Shared/Skills" + assert bundle["value"]["version"] == { + "defaultValue": "7", + "isExpression": False, + "displayName": "Version", + } + assert ( + binding_entry(Declaration(kind="skillBundle", name="ops"))["value"][ + "version" + ]["defaultValue"] + == "latest" + ) + + def test_keeps_hand_written_entries_and_replaces_derived_and_same_key_ones( + self, + ) -> None: + base = { + "version": "2.1", + "resources": [ + { + "resource": "mcpServer", + "key": "Legacy", + "value": {}, + "metadata": {"BindingsVersion": "2.2"}, + }, + { + "resource": "queue", + "key": "Gone", + "value": {}, + "metadata": {"Source": "code"}, + }, + {"resource": "Asset", "key": "A.Shared", "value": {"old": True}}, + ], + } + declared = [ + Declaration(kind="asset", name="A", folder_path="Shared", type="text"), + Declaration(kind="queue", name="Review"), + ] + derived = derive_bindings(declared, base) + assert derived.document["version"] == "2.1" + assert [(r["resource"], r["key"]) for r in derived.document["resources"]] == [ + ("mcpServer", "Legacy"), + ("asset", "A.Shared"), + ("queue", "Review"), + ] + assert (derived.derived, derived.kept) == (2, 1) + assert derived.document["resources"][1]["metadata"]["SubType"] == "text" + + def test_no_base_gives_version_2_0_and_duplicates_are_reported_once(self) -> None: + declared = [ + Declaration(kind="asset", name="A", type="text"), + Declaration(kind="asset", name="A", type="json"), + Declaration(kind="asset", name="A", type="text"), + ] + derived = derive_bindings(declared, None) + assert derived.document["version"] == "2.0" + assert derived.derived == 1 + assert derived.diagnostics == [ + 'asset "A" is declared more than once with different types; the first declaration is used.' + ] + + +class TestSyncBindings: + def test_without_a_declarations_file_nothing_happens(self, tmp_path) -> None: + assert sync_bindings(str(tmp_path)) is None + assert not os.path.exists(tmp_path / "bindings.json") + + def test_writes_bindings_json_and_reports_unchanged_on_a_rerun( + self, tmp_path + ) -> None: + (tmp_path / "uipath_resources.py").write_text( + 'from uipath.resources import resource\n\n\nclass ProjectResources:\n a = resource.queue(name="A")\n bad = resource.queue(name=NAME)\n' + ) + sync = sync_bindings(str(tmp_path)) + assert sync is not None + assert (sync.declared, sync.derived, sync.kept, sync.changed) == (1, 1, 0, True) + assert sync.diagnostics == [ + "uipath_resources.py:6: resource.queue() has a non-literal name; skipped" + ] + document = json.loads((tmp_path / "bindings.json").read_text()) + assert [r["key"] for r in document["resources"]] == ["A"] + again = sync_bindings(str(tmp_path)) + assert again is not None and not again.changed + + def test_reads_src_uipath_resources_py_too(self, tmp_path) -> None: + (tmp_path / "src").mkdir() + (tmp_path / "src" / "uipath_resources.py").write_text( + 'from uipath.resources import resource\n\n\nclass ProjectResources:\n a = resource.queue(name="A")\n' + ) + sync = sync_bindings(str(tmp_path)) + assert sync is not None and sync.declarations_file == os.path.join( + "src", "uipath_resources.py" + ) + assert (tmp_path / "bindings.json").exists() + + def test_a_broken_bindings_file_stops_the_sync(self, tmp_path) -> None: + (tmp_path / "uipath_resources.py").write_text( + "from uipath.resources import resource\n\n\nclass ProjectResources:\n pass\n" + ) + (tmp_path / "bindings.json").write_text("not json") + with pytest.raises(BindingsFileError, match="not valid JSON"): + sync_bindings(str(tmp_path)) + (tmp_path / "bindings.json").write_text('{"version": "2.0"}') + with pytest.raises(BindingsFileError, match='"resources" list'): + sync_bindings(str(tmp_path)) diff --git a/packages/uipath/tests/cli/test_resources.py b/packages/uipath/tests/cli/test_resources.py new file mode 100644 index 000000000..53b5778d1 --- /dev/null +++ b/packages/uipath/tests/cli/test_resources.py @@ -0,0 +1,709 @@ +# type: ignore +"""Tests for ``uipath resources`` and the bindings regeneration in ``pack`` and ``push``.""" + +import json +import os +import zipfile + +import pytest +from click.testing import CliRunner +from utils.project_details import ProjectDetails + +from tests.cli.utils.common import configure_env_vars +from uipath._cli import cli + +CONNECTION_ID = "3121165f-ce9b-4503-8c10-289ae6b21bd8" +FILE = "uipath_resources.py" + + +def write_pyproject(project_details: ProjectDetails) -> None: + with open("pyproject.toml", "w") as f: + f.write(project_details.to_toml()) + + +def read_file(path: str = FILE) -> str: + with open(path, encoding="utf-8", newline="") as f: + return f.read() + + +def read_bindings() -> dict: + with open("bindings.json") as f: + return json.load(f) + + +@pytest.fixture +def project(runner: CliRunner, temp_dir: str, project_details: ProjectDetails): + with runner.isolated_filesystem(temp_dir=temp_dir): + write_pyproject(project_details) + yield + + +@pytest.mark.usefixtures("project") +class TestResourcesAdd: + def test_creates_the_file_with_import_class_and_declaration( + self, runner: CliRunner + ) -> None: + result = runner.invoke( + cli, + [ + "resources", + "add", + "InvoiceThreshold", + "--kind", + "asset", + "--folder-path", + "Finance/Shared", + "--type", + "integer", + ], + ) + assert result.exit_code == 0, result.output + assert "Created uipath_resources.py" in result.output + assert read_file() == ( + "from uipath.resources import resource\n\n\n" + "class ProjectResources:\n" + ' invoice_threshold = resource.asset(name="InvoiceThreshold", folder_path="Finance/Shared", type="integer")\n' + ) + + def test_appends_to_an_existing_file_and_re_adding_leaves_it_unchanged( + self, runner: CliRunner + ) -> None: + assert ( + runner.invoke( + cli, ["resources", "add", "Review", "--kind", "queue"] + ).exit_code + == 0 + ) + result = runner.invoke( + cli, + [ + "resources", + "add", + "Invoices", + "--kind", + "bucket", + "--type", + "Orchestrator", + ], + ) + assert result.exit_code == 0, result.output + before = read_file() + assert before.endswith( + ' review = resource.queue(name="Review")\n' + ' invoices = resource.bucket(name="Invoices", type="orchestrator")\n' + ) + again = runner.invoke(cli, ["resources", "add", "Review", "--kind", "queue"]) + assert again.exit_code == 0 + assert "already declared" in again.output + assert read_file() == before + + def test_the_projects_own_folder_is_written_without_a_folder( + self, runner: CliRunner + ) -> None: + for folder in [".", "solution_folder", ""]: + runner.invoke( + cli, + [ + "resources", + "add", + f"Q{folder}", + "--kind", + "queue", + "--folder-path", + folder, + ], + ) + assert "folder_path" not in read_file() + + def test_declares_a_connection_by_id_and_connector(self, runner: CliRunner) -> None: + result = runner.invoke( + cli, + [ + "resources", + "add", + "Finance Slack", + "--kind", + "connection", + "--id", + CONNECTION_ID, + "--connector", + "uipath-slack", + ], + ) + assert result.exit_code == 0, result.output + assert ( + f'finance_slack = resource.connection(id="{CONNECTION_ID}", connector="uipath-slack", name="Finance Slack")' + in read_file() + ) + + @pytest.mark.parametrize( + ("args", "message"), + [ + (["X", "--kind", "connection"], "pass --id and --connector"), + ( + ["X", "--kind", "connection", "--id", "nope", "--connector", "x"], + "is not a connection id", + ), + ( + [ + "X", + "--kind", + "connection", + "--id", + CONNECTION_ID, + "--connector", + "x", + "--folder-path", + "F", + ], + "do not apply to a connection", + ), + (["X"], "Pass --kind"), + (["X", "--kind", "widget"], '"widget" is not a resource kind'), + (["--kind", "queue"], "Pass the resource name"), + ( + ["X", "--kind", "queue", "--type", "text"], + "--type does not apply to a queue", + ), + ( + ["X", "--kind", "asset", "--type", "float"], + '"float" is not an asset type', + ), + (["X", "--kind", "bucket", "--type", "s3"], '"s3" is not a bucket type'), + ( + ["X", "--kind", "queue", "--version", "7"], + "--version applies to a skill bundle only", + ), + ( + ["X", "--kind", "queue", "--id", CONNECTION_ID], + "--id and --connector apply to a connection only", + ), + ], + ) + def test_invalid_options_fail_without_writing( + self, runner: CliRunner, args: list[str], message: str + ) -> None: + result = runner.invoke(cli, ["resources", "add", *args]) + assert result.exit_code == 1, result.output + assert message in result.output + assert not os.path.exists(FILE) + + def test_kind_accepts_the_method_spelling_and_any_case( + self, runner: CliRunner + ) -> None: + assert ( + runner.invoke( + cli, + [ + "resources", + "add", + "Docs", + "--kind", + "mcp_server", + "--folder-path", + "Shared", + ], + ).exit_code + == 0 + ) + assert ( + runner.invoke(cli, ["resources", "add", "Idx", "--kind", "INDEX"]).exit_code + == 0 + ) + assert ( + runner.invoke( + cli, + [ + "resources", + "add", + "finance", + "--kind", + "skillBundle", + "--version", + "7", + ], + ).exit_code + == 0 + ) + assert ( + runner.invoke( + cli, + [ + "resources", + "add", + "ops", + "--kind", + "skill_bundle", + "--version", + "latest", + ], + ).exit_code + == 0 + ) + content = read_file() + assert ( + 'docs = resource.mcp_server(name="Docs", folder_path="Shared")' in content + ) + assert 'idx = resource.index(name="Idx")' in content + assert 'finance = resource.skill_bundle(name="finance", version="7")' in content + assert 'ops = resource.skill_bundle(name="ops")' in content + + def test_re_adding_with_another_type_fails_and_names_the_line( + self, runner: CliRunner + ) -> None: + runner.invoke( + cli, ["resources", "add", "A", "--kind", "asset", "--type", "text"] + ) + result = runner.invoke( + cli, ["resources", "add", "A", "--kind", "asset", "--type", "json"] + ) + assert result.exit_code == 1 + assert ( + 'asset "A" is already declared in uipath_resources.py:5 with type text' + in result.output + ) + assert 'type="text"' in read_file() + + def test_a_file_without_the_class_fails(self, runner: CliRunner) -> None: + with open(FILE, "w") as f: + f.write( + "from uipath.resources import resource\n\nx = resource.queue(name='A')\n" + ) + result = runner.invoke(cli, ["resources", "add", "B", "--kind", "queue"]) + assert result.exit_code == 1 + assert "no `class ProjectResources:`" in result.output + + def test_skip_verify_is_accepted_for_uip_parity(self, runner: CliRunner) -> None: + result = runner.invoke( + cli, ["resources", "add", "Review", "--kind", "queue", "--skip-verify"] + ) + assert result.exit_code == 0, result.output + + def test_json_output(self, runner: CliRunner) -> None: + result = runner.invoke( + cli, + [ + "--format", + "json", + "resources", + "add", + "Review", + "--kind", + "queue", + "--folder-path", + "Shared", + ], + ) + assert result.exit_code == 0, result.output + assert json.loads(result.stdout) == { + "added": True, + "kind": "queue", + "name": "Review", + "folderPath": "Shared", + "attribute": "review", + "file": FILE, + } + + def test_project_path_points_at_another_folder( + self, runner: CliRunner, project_details: ProjectDetails + ) -> None: + os.mkdir("other") + with open(os.path.join("other", "pyproject.toml"), "w") as f: + f.write(project_details.to_toml()) + result = runner.invoke( + cli, + [ + "resources", + "add", + "Review", + "--kind", + "queue", + "--project-path", + "other", + ], + ) + assert result.exit_code == 0, result.output + assert os.path.exists(os.path.join("other", FILE)) + assert not os.path.exists(FILE) + + def test_outside_a_project_fails(self, runner: CliRunner) -> None: + os.mkdir("empty") + result = runner.invoke( + cli, + [ + "resources", + "add", + "Review", + "--kind", + "queue", + "--project-path", + "empty", + ], + ) + assert result.exit_code == 1 + assert "No pyproject.toml" in result.output + + +@pytest.mark.usefixtures("project") +class TestResourcesList: + def test_lists_declarations_and_warns_on_unreadable_ones( + self, runner: CliRunner + ) -> None: + with open(FILE, "w") as f: + f.write( + "from uipath.resources import resource\n\n\nclass ProjectResources:\n" + ' a = resource.asset(name="A", folder_path="Shared", type="text")\n' + ' q = resource.queue(name="Q")\n' + " bad = resource.queue(name=NAME)\n" + ) + result = runner.invoke(cli, ["resources", "list"]) + assert result.exit_code == 0, result.output + assert ( + "uipath_resources.py:7: resource.queue() has a non-literal name; skipped" + in result.output + ) + assert "a = asset A, folder Shared, type text" in result.output + assert "q = queue Q" in result.output + only_assets = runner.invoke( + cli, ["resources", "list", "--kind", "asset", "--format", "json"] + ) + assert json.loads(only_assets.stdout) == [ + { + "kind": "asset", + "name": "A", + "folderPath": "Shared", + "type": "text", + "attribute": "a", + } + ] + + def test_without_a_file_says_so_and_json_is_an_empty_list( + self, runner: CliRunner + ) -> None: + result = runner.invoke(cli, ["resources", "list"]) + assert result.exit_code == 0 + assert "No uipath_resources.py in the project" in result.output + assert ( + json.loads( + runner.invoke(cli, ["--format", "json", "resources", "list"]).stdout + ) + == [] + ) + + def test_a_syntax_error_fails(self, runner: CliRunner) -> None: + with open(FILE, "w") as f: + f.write('class ProjectResources:\n x = resource.queue(name="A"\n') + result = runner.invoke(cli, ["resources", "list"]) + assert result.exit_code == 1 + assert "uipath_resources.py:2:" in result.output + + +@pytest.mark.usefixtures("project") +class TestResourcesRemove: + def _declare(self, runner: CliRunner) -> None: + runner.invoke(cli, ["resources", "add", "Review", "--kind", "queue"]) + runner.invoke( + cli, + [ + "resources", + "add", + "A", + "--kind", + "asset", + "--folder-path", + "Shared", + "--type", + "text", + ], + ) + runner.invoke( + cli, + [ + "resources", + "add", + "Slack", + "--kind", + "connection", + "--id", + CONNECTION_ID, + "--connector", + "uipath-slack", + ], + ) + + def test_removes_by_kind_name_and_folder(self, runner: CliRunner) -> None: + self._declare(runner) + wrong_folder = runner.invoke( + cli, ["resources", "remove", "A", "--kind", "asset"] + ) + assert wrong_folder.exit_code == 0 and "is not declared" in wrong_folder.output + result = runner.invoke( + cli, + ["resources", "remove", "A", "--kind", "asset", "--folder-path", "Shared"], + ) + assert result.exit_code == 0, result.output + assert "Removed asset A (a)" in result.output + assert "resource.asset" not in read_file() + assert "resource.queue" in read_file() + + def test_removes_a_connection_by_id_with_json_output( + self, runner: CliRunner + ) -> None: + self._declare(runner) + result = runner.invoke( + cli, + [ + "resources", + "remove", + "--kind", + "connection", + "--id", + CONNECTION_ID, + "--format", + "json", + ], + ) + assert result.exit_code == 0, result.output + assert json.loads(result.stdout) == { + "removed": True, + "kind": "connection", + "key": CONNECTION_ID, + "attribute": "slack", + "file": FILE, + } + assert CONNECTION_ID not in read_file() + + def test_removing_the_last_declaration_leaves_a_valid_class( + self, runner: CliRunner + ) -> None: + runner.invoke(cli, ["resources", "add", "Review", "--kind", "queue"]) + assert ( + runner.invoke( + cli, ["resources", "remove", "Review", "--kind", "queue"] + ).exit_code + == 0 + ) + assert read_file().endswith("class ProjectResources:\n pass\n") + assert ( + runner.invoke( + cli, ["resources", "add", "Review", "--kind", "queue"] + ).exit_code + == 0 + ) + assert read_file().endswith( + 'class ProjectResources:\n review = resource.queue(name="Review")\n' + ) + + @pytest.mark.parametrize( + ("args", "message"), + [ + (["--kind", "connection"], "pass --id"), + (["--kind", "queue"], "Pass the resource name"), + (["X", "--kind", "queue"], "nothing to remove"), + ], + ) + def test_invalid_options_fail( + self, runner: CliRunner, args: list[str], message: str + ) -> None: + result = runner.invoke(cli, ["resources", "remove", *args]) + assert result.exit_code == 1, result.output + assert message in result.output + + +@pytest.mark.usefixtures("project") +class TestResourcesBindings: + def test_writes_bindings_json_over_the_hand_written_entries( + self, runner: CliRunner + ) -> None: + with open("bindings.json", "w") as f: + json.dump( + { + "version": "2.0", + "resources": [ + { + "resource": "mcpServer", + "key": "Legacy", + "value": {}, + "metadata": {"BindingsVersion": "2.2"}, + }, + { + "resource": "queue", + "key": "Gone", + "value": {}, + "metadata": {"Source": "code"}, + }, + ], + }, + f, + ) + runner.invoke(cli, ["resources", "add", "Review", "--kind", "queue"]) + runner.invoke( + cli, + [ + "resources", + "add", + "Slack", + "--kind", + "connection", + "--id", + CONNECTION_ID, + "--connector", + "uipath-slack", + ], + ) + result = runner.invoke(cli, ["resources", "bindings"]) + assert result.exit_code == 0, result.output + assert "2 declared, 1 hand-written kept" in result.output + document = read_bindings() + assert [(r["resource"], r["key"]) for r in document["resources"]] == [ + ("mcpServer", "Legacy"), + ("queue", "Review"), + ("connection", CONNECTION_ID), + ] + assert document["resources"][1]["metadata"] == { + "BindingsVersion": "2.2", + "Source": "code", + } + again = runner.invoke(cli, ["resources", "bindings", "--format", "json"]) + assert json.loads(again.stdout)["changed"] is False + + def test_without_a_declarations_file_fails(self, runner: CliRunner) -> None: + result = runner.invoke(cli, ["resources", "bindings"]) + assert result.exit_code == 1 + assert "No uipath_resources.py in the project" in result.output + assert not os.path.exists("bindings.json") + + def test_a_broken_bindings_json_fails(self, runner: CliRunner) -> None: + runner.invoke(cli, ["resources", "add", "Review", "--kind", "queue"]) + with open("bindings.json", "w") as f: + f.write("{") + result = runner.invoke(cli, ["resources", "bindings"]) + assert result.exit_code == 1 + assert "not valid JSON" in result.output + + +def _write_packable_project(project_details: ProjectDetails) -> None: + write_pyproject(project_details) + with open("uipath.json", "w") as f: + json.dump({"functions": {"main": "main.py:main"}}, f) + with open("main.py", "w") as f: + f.write("def main(input): return input\n") + with open("entry-points.json", "w") as f: + json.dump( + { + "$schema": "https://cloud.uipath.com/draft/2024-12/entry-point", + "$id": "entry-points.json", + "entryPoints": [ + { + "filePath": "main", + "uniqueId": "00000000-0000-0000-0000-000000000000", + "type": "function", + "input": {"type": "object", "properties": {}}, + "output": {"type": "object", "properties": {}}, + } + ], + }, + f, + ) + + +class TestBindingsRegeneration: + def test_pack_derives_the_packaged_bindings_from_the_declarations( + self, runner: CliRunner, temp_dir: str, project_details: ProjectDetails + ) -> None: + with runner.isolated_filesystem(temp_dir=temp_dir): + _write_packable_project(project_details) + with open("bindings.json", "w") as f: + json.dump( + { + "version": "2.0", + "resources": [ + { + "resource": "mcpServer", + "key": "Legacy", + "value": {}, + "metadata": {"BindingsVersion": "2.2"}, + }, + { + "resource": "queue", + "key": "Stale", + "value": {}, + "metadata": {"Source": "code"}, + }, + ], + }, + f, + ) + with open(FILE, "w") as f: + f.write( + "from uipath.resources import resource\n\n\nclass ProjectResources:\n" + ' threshold = resource.asset(name="InvoiceThreshold", folder_path="Finance/Shared", type="integer")\n' + ) + result = runner.invoke(cli, ["pack", "./", "--nolock"], env={}) + assert result.exit_code == 0, result.output + assert "Updated" in result.output and "bindings.json" in result.output + assert [ + (r["resource"], r["key"]) for r in read_bindings()["resources"] + ] == [ + ("mcpServer", "Legacy"), + ("asset", "InvoiceThreshold.Finance/Shared"), + ] + with zipfile.ZipFile( + f".uipath/{project_details.name}.{project_details.version}.nupkg" + ) as z: + packaged = json.loads(z.read("content/bindings_v2.json")) + assert "content/uipath_resources.py" in z.namelist() + assert [r["key"] for r in packaged["resources"]] == [ + "Legacy", + "InvoiceThreshold.Finance/Shared", + ] + assert packaged["resources"][1]["metadata"]["SubType"] == "integer" + + def test_pack_without_a_declarations_file_keeps_bindings_json( + self, runner: CliRunner, temp_dir: str, project_details: ProjectDetails + ) -> None: + with runner.isolated_filesystem(temp_dir=temp_dir): + _write_packable_project(project_details) + bindings = { + "version": "2.0", + "resources": [{"resource": "queue", "key": "Hand", "value": {}}], + } + with open("bindings.json", "w") as f: + json.dump(bindings, f, indent=4) + result = runner.invoke(cli, ["pack", "./", "--nolock"], env={}) + assert result.exit_code == 0, result.output + assert read_bindings() == bindings + + def test_pack_stops_on_a_broken_declarations_file( + self, runner: CliRunner, temp_dir: str, project_details: ProjectDetails + ) -> None: + with runner.isolated_filesystem(temp_dir=temp_dir): + _write_packable_project(project_details) + with open(FILE, "w") as f: + f.write('class ProjectResources:\n x = resource.queue(name="A"\n') + result = runner.invoke(cli, ["pack", "./", "--nolock"], env={}) + assert result.exit_code == 1 + assert "uipath_resources.py:2:" in result.output + assert not os.path.exists(".uipath") + + def test_push_regenerates_bindings_before_anything_else( + self, + runner: CliRunner, + temp_dir: str, + project_details: ProjectDetails, + mock_env_vars: dict[str, str], + ) -> None: + with runner.isolated_filesystem(temp_dir=temp_dir): + configure_env_vars(mock_env_vars) + os.environ.pop("UIPATH_PROJECT_ID", None) + _write_packable_project(project_details) + with open(FILE, "w") as f: + f.write( + "from uipath.resources import resource\n\n\nclass ProjectResources:\n" + ' review = resource.queue(name="Review")\n' + ) + # The push stops at the missing project id, after the bindings were derived. + result = runner.invoke(cli, ["push", "./", "--ignore-resources"]) + assert result.exit_code == 1, result.output + assert "UIPATH_PROJECT_ID environment variable not found" in result.output + assert [r["key"] for r in read_bindings()["resources"]] == ["Review"] From 2fcf2f8d2a53571270989ca7c9cfeb78f8bbe06b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 10:40:33 +0000 Subject: [PATCH 2/8] refactor(cli): drop uipath resources remove to match uip uip has no remove on purpose: a declaration is one line the user deletes. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_014t9fy7CGYG2vBLEfHwu12m --- README.md | 1 - packages/uipath/README.md | 1 - .../src/uipath/_cli/_declarations/__init__.py | 2 +- .../src/uipath/_cli/_declarations/_editor.py | 55 +-------- .../uipath/src/uipath/_cli/cli_resources.py | 88 -------------- .../tests/cli/test_resource_declarations.py | 42 ------- packages/uipath/tests/cli/test_resources.py | 112 ------------------ 7 files changed, 4 insertions(+), 297 deletions(-) diff --git a/README.md b/README.md index 843ca8567..35164a749 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,6 @@ Publishes the most recently created package to your UiPath Orchestrator. uipath resources add InvoiceThreshold --kind asset --folder-path Finance/Shared --type integer uipath resources add InvoiceReview --kind queue uipath resources list -uipath resources remove InvoiceReview --kind queue uipath resources bindings ``` diff --git a/packages/uipath/README.md b/packages/uipath/README.md index 843ca8567..35164a749 100644 --- a/packages/uipath/README.md +++ b/packages/uipath/README.md @@ -189,7 +189,6 @@ Publishes the most recently created package to your UiPath Orchestrator. uipath resources add InvoiceThreshold --kind asset --folder-path Finance/Shared --type integer uipath resources add InvoiceReview --kind queue uipath resources list -uipath resources remove InvoiceReview --kind queue uipath resources bindings ``` diff --git a/packages/uipath/src/uipath/_cli/_declarations/__init__.py b/packages/uipath/src/uipath/_cli/_declarations/__init__.py index eaa336cb1..664234643 100644 --- a/packages/uipath/src/uipath/_cli/_declarations/__init__.py +++ b/packages/uipath/src/uipath/_cli/_declarations/__init__.py @@ -8,7 +8,7 @@ - ``_model``: a declaration as the commands see it, and its binding key. - ``_parser``: the literal-only ``ast`` reader, with a diagnostic per call it skips. -- ``_editor``: adds and removes declarations in the file's text. +- ``_editor``: adds declarations to the file's text. - ``_bindings``: derives ``bindings.json`` over the hand-written entries. - ``_project``: where the files live. """ diff --git a/packages/uipath/src/uipath/_cli/_declarations/_editor.py b/packages/uipath/src/uipath/_cli/_declarations/_editor.py index da49d7e58..cdf29795e 100644 --- a/packages/uipath/src/uipath/_cli/_declarations/_editor.py +++ b/packages/uipath/src/uipath/_cli/_declarations/_editor.py @@ -1,8 +1,9 @@ -"""Adds and removes declarations in the text of ``uipath_resources.py``. +"""Adds declarations to the text of ``uipath_resources.py``. The file is edited as text so that everything else in it (comments, other members, formatting) stays as the user wrote it: a declaration is one line -added after the last member of ``ProjectResources``, or one statement removed. +added after the last member of ``ProjectResources``. There is no remove, as in +the ``uip`` CLI: a declaration is one line the user deletes. """ import ast @@ -43,21 +44,6 @@ class InsertResult: attribute: str | None -@dataclass(frozen=True) -class RemoveResult: - """What removing a declaration did. - - Attributes: - source: The file's new text; the input unchanged when nothing matched. - removed: Whether a declaration was removed. - attribute: The attribute the removed declaration was bound to, if any. - """ - - source: str - removed: bool - attribute: str | None - - def to_python_identifier(name: str, taken: frozenset[str] | set[str]) -> str: """A snake_case attribute name for ``name``, unique among ``taken`` and never a keyword. @@ -206,46 +192,11 @@ def insert_declaration( return InsertResult(source="\n".join(lines), added=True, attribute=attribute) -def remove_declaration( - source: str, kind: str, key: str, file_name: str -) -> RemoveResult: - """Removes the declaration of ``kind`` with binding key ``key``: the whole statement that holds it. - - Raises: - DeclarationsSyntaxError: The file is not valid Python. - DeclarationsFileError: The declaration is not a plain - ``attribute = resource.(...)`` statement, so it is left for - the user to remove. - """ - parsed = parse_declarations(source, file_name) - found = parsed.find(kind, key) - if found is None: - return RemoveResult(source=source, removed=False, attribute=None) - if found.statement_lines is None: - raise DeclarationsFileError( - f"{file_name}:{found.lineno}: the {found.declaration.label} declaration is " - f"part of a larger expression; remove it by hand." - ) - start, end = found.statement_lines - lines = source.split("\n") - del lines[start - 1 : end] - - info = parsed.project_resources - if info is not None and info.body_lines == found.statement_lines: - # The class body would be empty, which is not valid Python. - lines.insert(start - 1, f"{info.indent}pass" + _line_end(lines, start - 2)) - return RemoveResult( - source="\n".join(lines), removed=True, attribute=found.attribute - ) - - __all__ = [ "DeclarationsFileError", "InsertResult", "ParsedDeclarations", - "RemoveResult", "insert_declaration", - "remove_declaration", "render_declaration", "to_python_identifier", ] diff --git a/packages/uipath/src/uipath/_cli/cli_resources.py b/packages/uipath/src/uipath/_cli/cli_resources.py index 5c12ca89f..b40412eee 100644 --- a/packages/uipath/src/uipath/_cli/cli_resources.py +++ b/packages/uipath/src/uipath/_cli/cli_resources.py @@ -255,7 +255,6 @@ def resources() -> None: uipath resources add InvoiceReview --kind queue uipath resources add "Finance Slack" --kind connection --id 3121165f-ce9b-4503-8c10-289ae6b21bd8 --connector uipath-slack uipath resources list - uipath resources remove InvoiceReview --kind queue uipath resources bindings """ # noqa: D301 @@ -430,93 +429,6 @@ def list_declarations( console.info(f" {attribute}{_describe(row.declaration)}") -@resources.command(name="remove") -@click.argument("name", required=False) -@_kind_option("Resource kind") -@click.option( - "--folder-path", - help="The folder the declaration names; omit it for a declaration without one.", -) -@click.option("--id", "connection_id", help="A connection's id (a GUID)") -@_format_option -@_project_path_option -@track_command("resources remove") -def remove( - name: str | None, - kind: str | None, - folder_path: str | None, - connection_id: str | None, - format: str | None, - project_path: str | None, -) -> None: - """Remove a declaration from uipath_resources.py. - - Removes the statement that declares the resource of that kind, name and - folder (a connection by its id). Code that still uses the attribute is - left to you. bindings.json drops the binding at the next - `uipath resources bindings`, pack or push. - - \b - Examples: - uipath resources remove InvoiceReview --kind queue - uipath resources remove InvoiceThreshold --kind asset --folder-path Finance/Shared - uipath resources remove --kind connection --id 3121165f-ce9b-4503-8c10-289ae6b21bd8 - """ # noqa: D301 - from ._declarations._editor import DeclarationsFileError, remove_declaration - from ._declarations._model import ( - CONNECTION_KIND, - binding_key, - normalize_folder_path, - ) - from ._declarations._parser import DeclarationsSyntaxError - from ._declarations._project import read_declarations_file, write_declarations_file - - root = _resolve_root(project_path) - resolved_kind = _resolved_kind(kind) - if resolved_kind == CONNECTION_KIND: - if not connection_id: - _fail("A connection is identified by its id: pass --id.") - assert connection_id is not None - key = connection_id - label = f"connection {connection_id}" - else: - if not name or not name.strip(): - _fail("Pass the resource name, as declared.") - assert name is not None - key = binding_key(name, normalize_folder_path(folder_path)) - label = f"{resolved_kind} {name}" - - file = read_declarations_file(root) - if not file.exists: - _fail(f"No {file.relative_path} in the project; nothing to remove.") - try: - result = remove_declaration( - file.content, resolved_kind, key, file.relative_path - ) - except (DeclarationsSyntaxError, DeclarationsFileError) as error: - _fail(str(error)) - return - if result.removed: - write_declarations_file(file, result.source) - - if _wants_json(): - _emit( - { - "removed": result.removed, - "kind": resolved_kind, - "key": key, - **({"attribute": result.attribute} if result.attribute else {}), - "file": file.relative_path, - } - ) - return - if result.removed: - attribute = f" ({result.attribute})" if result.attribute else "" - console.success(f"Removed {label}{attribute} from {file.relative_path}.") - else: - console.info(f"{label} is not declared in {file.relative_path}.") - - @resources.command(name="bindings") @_format_option @_project_path_option diff --git a/packages/uipath/tests/cli/test_resource_declarations.py b/packages/uipath/tests/cli/test_resource_declarations.py index 9141155bc..a9355216d 100644 --- a/packages/uipath/tests/cli/test_resource_declarations.py +++ b/packages/uipath/tests/cli/test_resource_declarations.py @@ -15,7 +15,6 @@ from uipath._cli._declarations._editor import ( DeclarationsFileError, insert_declaration, - remove_declaration, render_declaration, to_python_identifier, ) @@ -383,47 +382,6 @@ def test_renders_a_skill_bundle_version_and_escapes_quotes(self) -> None: ) -class TestRemove: - SOURCE = src( - """ - from uipath.resources import resource - - - class ProjectResources: - a = resource.queue(name="A") - b = resource.asset( - name="B", - folder_path="Shared", - ) # multi-line - """ - ) - - def test_removes_the_whole_statement(self) -> None: - result = remove_declaration(self.SOURCE, "asset", "B.Shared", FILE) - assert result.removed and result.attribute == "b" - assert ( - result.source - == 'from uipath.resources import resource\n\n\nclass ProjectResources:\n a = resource.queue(name="A")\n' - ) - - def test_nothing_matching_leaves_the_file(self) -> None: - result = remove_declaration(self.SOURCE, "asset", "B", FILE) - assert not result.removed - assert result.source == self.SOURCE - - def test_the_last_member_leaves_a_pass(self) -> None: - once = remove_declaration(self.SOURCE, "queue", "A", FILE).source - twice = remove_declaration(once, "asset", "B.Shared", FILE) - assert twice.source.endswith("class ProjectResources:\n pass\n") - - def test_a_nested_call_is_left_to_the_user(self) -> None: - source = 'from uipath.resources import resource\n\n\nclass ProjectResources:\n q = [resource.queue(name="N")]\n' - with pytest.raises( - DeclarationsFileError, match=f"{FILE}:5: .*remove it by hand" - ): - remove_declaration(source, "queue", "N", FILE) - - class TestDeriveBindings: def test_entry_shapes(self) -> None: asset = binding_entry( diff --git a/packages/uipath/tests/cli/test_resources.py b/packages/uipath/tests/cli/test_resources.py index 53b5778d1..eee98c0d1 100644 --- a/packages/uipath/tests/cli/test_resources.py +++ b/packages/uipath/tests/cli/test_resources.py @@ -398,118 +398,6 @@ def test_a_syntax_error_fails(self, runner: CliRunner) -> None: assert "uipath_resources.py:2:" in result.output -@pytest.mark.usefixtures("project") -class TestResourcesRemove: - def _declare(self, runner: CliRunner) -> None: - runner.invoke(cli, ["resources", "add", "Review", "--kind", "queue"]) - runner.invoke( - cli, - [ - "resources", - "add", - "A", - "--kind", - "asset", - "--folder-path", - "Shared", - "--type", - "text", - ], - ) - runner.invoke( - cli, - [ - "resources", - "add", - "Slack", - "--kind", - "connection", - "--id", - CONNECTION_ID, - "--connector", - "uipath-slack", - ], - ) - - def test_removes_by_kind_name_and_folder(self, runner: CliRunner) -> None: - self._declare(runner) - wrong_folder = runner.invoke( - cli, ["resources", "remove", "A", "--kind", "asset"] - ) - assert wrong_folder.exit_code == 0 and "is not declared" in wrong_folder.output - result = runner.invoke( - cli, - ["resources", "remove", "A", "--kind", "asset", "--folder-path", "Shared"], - ) - assert result.exit_code == 0, result.output - assert "Removed asset A (a)" in result.output - assert "resource.asset" not in read_file() - assert "resource.queue" in read_file() - - def test_removes_a_connection_by_id_with_json_output( - self, runner: CliRunner - ) -> None: - self._declare(runner) - result = runner.invoke( - cli, - [ - "resources", - "remove", - "--kind", - "connection", - "--id", - CONNECTION_ID, - "--format", - "json", - ], - ) - assert result.exit_code == 0, result.output - assert json.loads(result.stdout) == { - "removed": True, - "kind": "connection", - "key": CONNECTION_ID, - "attribute": "slack", - "file": FILE, - } - assert CONNECTION_ID not in read_file() - - def test_removing_the_last_declaration_leaves_a_valid_class( - self, runner: CliRunner - ) -> None: - runner.invoke(cli, ["resources", "add", "Review", "--kind", "queue"]) - assert ( - runner.invoke( - cli, ["resources", "remove", "Review", "--kind", "queue"] - ).exit_code - == 0 - ) - assert read_file().endswith("class ProjectResources:\n pass\n") - assert ( - runner.invoke( - cli, ["resources", "add", "Review", "--kind", "queue"] - ).exit_code - == 0 - ) - assert read_file().endswith( - 'class ProjectResources:\n review = resource.queue(name="Review")\n' - ) - - @pytest.mark.parametrize( - ("args", "message"), - [ - (["--kind", "connection"], "pass --id"), - (["--kind", "queue"], "Pass the resource name"), - (["X", "--kind", "queue"], "nothing to remove"), - ], - ) - def test_invalid_options_fail( - self, runner: CliRunner, args: list[str], message: str - ) -> None: - result = runner.invoke(cli, ["resources", "remove", *args]) - assert result.exit_code == 1, result.output - assert message in result.output - - @pytest.mark.usefixtures("project") class TestResourcesBindings: def test_writes_bindings_json_over_the_hand_written_entries( From 95f5b9a9dc91d22d7c1f9626b3e99dfd46277ade Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:01:58 +0000 Subject: [PATCH 3/8] feat(cli): regenerate bindings.json before debug and eval fetch overrides A resource declared after the last pack or push had no override in a debug or eval run, because Studio Web keys the overrides by the bindings it is sent and bindings.json was stale. Same derivation as pack and push. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_014t9fy7CGYG2vBLEfHwu12m --- packages/uipath/CLAUDE.md | 1 + packages/uipath/src/uipath/_cli/cli_debug.py | 7 + packages/uipath/src/uipath/_cli/cli_eval.py | 6 + packages/uipath/tests/cli/test_resources.py | 129 +++++++++++++++++++ 4 files changed, 143 insertions(+) diff --git a/packages/uipath/CLAUDE.md b/packages/uipath/CLAUDE.md index a5b489af5..45f624753 100644 --- a/packages/uipath/CLAUDE.md +++ b/packages/uipath/CLAUDE.md @@ -61,6 +61,7 @@ Uses **click** framework. Commands are organized as `cli_.py` files. | `cli_server.py` | `server` | Run as server | | `cli_register.py` | `register` | Register resource | | `cli_debug.py` | `debug` | Debug execution | +| `cli_resources.py` | `resources` | Declare the project's platform resources in `uipath_resources.py` (`add`, `list`) and derive `bindings.json` from it (`bindings`); `pack`, `push`, `debug` and `eval` regenerate the bindings first. Parsing and editing live in `_declarations/` | Sub-commands: `services/cli_assets.py` (asset management), `services/cli_buckets.py` (bucket management). diff --git a/packages/uipath/src/uipath/_cli/cli_debug.py b/packages/uipath/src/uipath/_cli/cli_debug.py index 5d67a0d51..b631cb64a 100644 --- a/packages/uipath/src/uipath/_cli/cli_debug.py +++ b/packages/uipath/src/uipath/_cli/cli_debug.py @@ -1,4 +1,5 @@ import logging +import os from typing import Any, cast, get_args import click @@ -288,6 +289,12 @@ async def execute_debug_runtime(): await runtime.dispose() if project_id := UiPathConfig.project_id: + # The overrides Studio Web returns are keyed by the + # bindings it is sent, which are derived from + # uipath_resources.py. + from .cli_resources import regenerate_bindings + + regenerate_bindings(os.getcwd()) studio_client = StudioClient(project_id) async with ResourceOverwritesContext( diff --git a/packages/uipath/src/uipath/_cli/cli_eval.py b/packages/uipath/src/uipath/_cli/cli_eval.py index c7870a0cc..56807e7ea 100644 --- a/packages/uipath/src/uipath/_cli/cli_eval.py +++ b/packages/uipath/src/uipath/_cli/cli_eval.py @@ -486,6 +486,12 @@ async def execute_eval(): # time, and those lookups need the overwritten folder paths. async with AsyncExitStack() as stack: if project_id: + # The overrides Studio Web returns are keyed by + # the bindings it is sent, which are derived + # from uipath_resources.py. + from .cli_resources import regenerate_bindings + + regenerate_bindings(os.getcwd()) studio_client = StudioClient(project_id) await stack.enter_async_context( diff --git a/packages/uipath/tests/cli/test_resources.py b/packages/uipath/tests/cli/test_resources.py index eee98c0d1..09861d73c 100644 --- a/packages/uipath/tests/cli/test_resources.py +++ b/packages/uipath/tests/cli/test_resources.py @@ -595,3 +595,132 @@ def test_push_regenerates_bindings_before_anything_else( assert result.exit_code == 1, result.output assert "UIPATH_PROJECT_ID environment variable not found" in result.output assert [r["key"] for r in read_bindings()["resources"]] == ["Review"] + + +def _write_declarations_and_stale_bindings() -> None: + with open(FILE, "w") as f: + f.write( + "from uipath.resources import resource\n\n\nclass ProjectResources:\n" + ' review = resource.queue(name="Review")\n' + ) + with open("bindings.json", "w") as f: + json.dump({"version": "2.0", "resources": []}, f) + + +def _recording_studio_client(seen: list[list[str]]): + """A Studio client whose override fetch records the bindings file as it is at that moment.""" + from unittest.mock import AsyncMock, Mock + + async def get_resource_overwrites() -> dict: + seen.append([r["key"] for r in read_bindings()["resources"]]) + return {} + + client = Mock() + client.get_resource_overwrites = AsyncMock(side_effect=get_resource_overwrites) + return client + + +class TestOverridesRegeneration: + def test_eval_regenerates_bindings_before_fetching_overrides( + self, runner: CliRunner, temp_dir: str, monkeypatch: pytest.MonkeyPatch + ) -> None: + from contextlib import ExitStack + from unittest.mock import patch + + from tests.cli.eval.test_eval_resource_overwrites import ( + _enter_base_patches, + _make_mock_factory, + _make_mock_runtime, + _write_project_files, + ) + + monkeypatch.setenv("UIPATH_PROJECT_ID", "project-123") + with runner.isolated_filesystem(temp_dir=temp_dir): + _write_project_files() + _write_declarations_and_stale_bindings() + seen: list[list[str]] = [] + mock_runtime = _make_mock_runtime() + with ExitStack() as stack: + _enter_base_patches(stack, _make_mock_factory(mock_runtime)) + stack.enter_context( + patch( + "uipath._cli.cli_eval.StudioClient", + return_value=_recording_studio_client(seen), + ) + ) + result = runner.invoke(cli, ["eval"]) + assert result.exit_code == 0, result.output + assert seen == [["Review"]] + + def test_debug_regenerates_bindings_before_fetching_overrides( + self, runner: CliRunner, temp_dir: str, monkeypatch: pytest.MonkeyPatch + ) -> None: + from contextlib import ExitStack + from unittest.mock import AsyncMock, Mock, patch + + from uipath._cli.middlewares import MiddlewareResult + + monkeypatch.setenv("UIPATH_PROJECT_ID", "project-123") + with runner.isolated_filesystem(temp_dir=temp_dir): + with open("entrypoint.py", "w") as f: + f.write("def main(input): return {'result': 'success'}") + with open("uipath.json", "w") as f: + json.dump({"functions": {"main": "entrypoint.py:main"}}, f) + _write_declarations_and_stale_bindings() + seen: list[list[str]] = [] + + mock_runtime = Mock() + mock_runtime.dispose = AsyncMock() + mock_runtime.get_schema = AsyncMock(return_value=Mock(metadata=None)) + mock_factory = Mock() + mock_factory.new_runtime = AsyncMock(return_value=mock_runtime) + mock_factory.get_settings = AsyncMock( + return_value=Mock(trace_settings=None) + ) + mock_factory.dispose = AsyncMock() + mock_debug_runtime = Mock() + mock_debug_runtime.dispose = AsyncMock() + mock_mock_runtime = Mock() + mock_mock_runtime.execute = AsyncMock( + return_value=Mock(status="SUCCESSFUL", output={}) + ) + + with ExitStack() as stack: + stack.enter_context( + patch( + "uipath._cli.cli_debug.Middlewares.next", + return_value=MiddlewareResult( + should_continue=True, + info_message=None, + error_message=None, + should_include_stacktrace=False, + ), + ) + ) + stack.enter_context( + patch( + "uipath._cli.cli_debug.UiPathRuntimeFactoryRegistry.get", + return_value=mock_factory, + ) + ) + stack.enter_context(patch("uipath._cli.cli_debug.get_debug_bridge")) + stack.enter_context( + patch( + "uipath._cli.cli_debug.UiPathDebugRuntime", + return_value=mock_debug_runtime, + ) + ) + stack.enter_context( + patch( + "uipath._cli.cli_debug.UiPathMockRuntime", + return_value=mock_mock_runtime, + ) + ) + stack.enter_context( + patch( + "uipath._cli.cli_debug.StudioClient", + return_value=_recording_studio_client(seen), + ) + ) + runner.invoke(cli, ["debug", "main", "{}"]) + assert seen == [["Review"]] From ea7efbc35b4812276e826ed6b8326641e1af6214 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:13:54 +0000 Subject: [PATCH 4/8] fix(cli): declare an entity without a folder, as uip does An entity is found by name across the tenant and the solution never creates one, so a folder on its declaration has no meaning and uip drops it. The handle takes no folder_path, the parser reports one as an argument an entity does not take, and add warns and ignores --folder-path for an entity. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_014t9fy7CGYG2vBLEfHwu12m --- .../src/uipath/resources/_handles.py | 14 ++++++++++---- .../tests/resources/test_handles.py | 18 ++++++++++++------ .../src/uipath/_cli/_declarations/_parser.py | 10 ++++++++-- .../uipath/src/uipath/_cli/cli_resources.py | 9 ++++++++- packages/uipath/tests/cli/test_resources.py | 17 +++++++++++++++++ 5 files changed, 55 insertions(+), 13 deletions(-) diff --git a/packages/uipath-platform/src/uipath/resources/_handles.py b/packages/uipath-platform/src/uipath/resources/_handles.py index 14c218aae..f6abfe61b 100644 --- a/packages/uipath-platform/src/uipath/resources/_handles.py +++ b/packages/uipath-platform/src/uipath/resources/_handles.py @@ -136,9 +136,15 @@ def binding_key(self) -> str: class EntityHandle(ResourceHandle): - """A Data Fabric entity, found by name; the folder is optional.""" + """A Data Fabric entity, found by name across the tenant. + + An entity is not folder scoped: a declaration never names a folder, and the + solution never creates one, so ``folder_path`` is always ``None``. The + folder an entity is bound to at deploy time arrives through the override. + """ kind: Literal["entity"] = "entity" + folder_path: None = None class ConnectionHandle(BaseModel): @@ -276,9 +282,9 @@ def ontology(self, *, name: str, folder_path: str | None = None) -> ResourceHand """An ontology.""" return self._generic("ontology", name, folder_path) - def entity(self, *, name: str, folder_path: str | None = None) -> EntityHandle: - """A Data Fabric entity; the folder is optional.""" - return EntityHandle(name=name, folder_path=normalize_folder_path(folder_path)) + def entity(self, *, name: str) -> EntityHandle: + """A Data Fabric entity, found by name across the tenant; it takes no folder.""" + return EntityHandle(name=name) def connection( self, *, id: str, connector: str, name: str | None = None diff --git a/packages/uipath-platform/tests/resources/test_handles.py b/packages/uipath-platform/tests/resources/test_handles.py index 9bee79e16..031e3330a 100644 --- a/packages/uipath-platform/tests/resources/test_handles.py +++ b/packages/uipath-platform/tests/resources/test_handles.py @@ -98,12 +98,18 @@ def test_snake_case_methods_declare_camel_case_kinds(method: str, kind: str) -> assert (handle.kind, handle.name, handle.folder_path) == (kind, "X", "Shared") -def test_entity_keeps_an_optional_folder() -> None: - assert resource.entity(name="Invoices").folder_path is None - with_folder = resource.entity(name="Invoices", folder_path="Finance") - assert isinstance(with_folder, EntityHandle) - assert with_folder.kind == "entity" - assert with_folder.binding_key == "Invoices.Finance" +def test_entity_has_no_folder() -> None: + handle = resource.entity(name="Invoices") + assert isinstance(handle, EntityHandle) + assert (handle.kind, handle.folder_path, handle.binding_key) == ( + "entity", + None, + "Invoices", + ) + with pytest.raises(TypeError): + resource.entity(name="Invoices", folder_path="Finance") # type: ignore[call-arg] + with pytest.raises(ValidationError): + EntityHandle(name="Invoices", folder_path="Finance") # type: ignore[arg-type] def test_connection_is_identified_by_its_id() -> None: diff --git a/packages/uipath/src/uipath/_cli/_declarations/_parser.py b/packages/uipath/src/uipath/_cli/_declarations/_parser.py index e7d49c96b..67bccad9e 100644 --- a/packages/uipath/src/uipath/_cli/_declarations/_parser.py +++ b/packages/uipath/src/uipath/_cli/_declarations/_parser.py @@ -3,7 +3,8 @@ Grammar, shared with the ``uip`` CLI's reader of the same file: every ``resource.(...)`` call whose arguments are all keywords with string literal values declares a resource. ``name`` is required; ``folder_path``, -``type`` and ``version`` are optional where the kind takes them; a connection +``type`` and ``version`` are optional where the kind takes them (an entity +takes no folder: it is found by name across the tenant); a connection takes ``id`` and ``connector`` instead, with an optional ``name``. A call that breaks the rules (a positional argument, a variable, an f-string, an unknown keyword) is reported with its line and skipped, so a declaration the CLI cannot @@ -17,6 +18,7 @@ CLASS_NAME, CONNECTION_ID_PATTERN, CONNECTION_KIND, + ENTITY_KIND, KIND_METHODS, SDK_HELPER_NAME, SKILL_BUNDLE_KIND, @@ -162,13 +164,17 @@ def _to_declaration(method: str, values: dict[str, str]) -> Declaration | str: ) allowed = set(_COMMON_KEYWORDS) + if kind == ENTITY_KIND: + # An entity is found by name across the tenant; it never names a folder. + allowed.discard("folder_path") if kind in TYPED_KINDS: allowed.add("type") if kind == SKILL_BUNDLE_KIND: allowed.add("version") unknown = set(values) - allowed if unknown: - return f"has an argument a {kind} does not take: {', '.join(sorted(unknown))}" + article = "an" if kind[0] in "aeiou" else "a" + return f"has an argument {article} {kind} does not take: {', '.join(sorted(unknown))}" name = values.get("name") if name is None: return "is missing a name" diff --git a/packages/uipath/src/uipath/_cli/cli_resources.py b/packages/uipath/src/uipath/_cli/cli_resources.py index b40412eee..0a8270de7 100644 --- a/packages/uipath/src/uipath/_cli/cli_resources.py +++ b/packages/uipath/src/uipath/_cli/cli_resources.py @@ -150,6 +150,7 @@ def _declaration_from_options( from ._declarations._model import ( CONNECTION_ID_PATTERN, CONNECTION_KIND, + ENTITY_KIND, SKILL_BUNDLE_KIND, Declaration, normalize_folder_path, @@ -178,6 +179,12 @@ def _declaration_from_options( assert name is not None if version is not None and version.strip().lower() in ("", "latest"): version = None + if kind == ENTITY_KIND and folder_path is not None: + # Same as `uip`: an entity is found by name across the tenant and never declares a folder. + _warn( + f"--folder-path is ignored for an entity: {name} is declared without a folder." + ) + folder_path = None return Declaration( kind=kind, name=name, @@ -264,7 +271,7 @@ def resources() -> None: @_kind_option("Resource kind") @click.option( "--folder-path", - help="Folder the resource sits in. Omit it for a resource the solution creates.", + help="Folder the resource sits in. Omit it for a resource the solution creates. An entity takes none.", ) @click.option( "--type", diff --git a/packages/uipath/tests/cli/test_resources.py b/packages/uipath/tests/cli/test_resources.py index 09861d73c..4ab324330 100644 --- a/packages/uipath/tests/cli/test_resources.py +++ b/packages/uipath/tests/cli/test_resources.py @@ -115,6 +115,23 @@ def test_the_projects_own_folder_is_written_without_a_folder( ) assert "folder_path" not in read_file() + def test_an_entity_is_declared_without_a_folder(self, runner: CliRunner) -> None: + result = runner.invoke( + cli, + [ + "resources", + "add", + "Invoices", + "--kind", + "entity", + "--folder-path", + "Finance", + ], + ) + assert result.exit_code == 0, result.output + assert "--folder-path is ignored for an entity" in result.output + assert 'invoices = resource.entity(name="Invoices")' in read_file() + def test_declares_a_connection_by_id_and_connector(self, runner: CliRunner) -> None: result = runner.invoke( cli, From 59518862ee1aa58261aa3a048e3dfad99b6f3169 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:26:55 +0000 Subject: [PATCH 5/8] fix(cli): rename bindings to generate-bindings and close three review findings - the verb is generate-bindings, named after what it does (uip has no such verb to match) - two skill bundles pinned to different versions are reported, as two assets with different types are - a class whose body sits on the class line is refused instead of edited into a second class - a blank --connector is refused before anything is written Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_014t9fy7CGYG2vBLEfHwu12m --- README.md | 4 ++-- packages/uipath/CLAUDE.md | 2 +- packages/uipath/README.md | 4 ++-- .../src/uipath/_cli/_declarations/__init__.py | 2 +- .../uipath/_cli/_declarations/_bindings.py | 12 +++++----- .../src/uipath/_cli/_declarations/_editor.py | 7 +++++- .../src/uipath/_cli/_declarations/_parser.py | 4 ++++ .../uipath/src/uipath/_cli/cli_resources.py | 16 +++++++------- .../tests/cli/test_resource_declarations.py | 22 +++++++++++++++++++ packages/uipath/tests/cli/test_resources.py | 22 +++++++++++++++---- 10 files changed, 71 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 35164a749..94708a42b 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,7 @@ Publishes the most recently created package to your UiPath Orchestrator. uipath resources add InvoiceThreshold --kind asset --folder-path Finance/Shared --type integer uipath resources add InvoiceReview --kind queue uipath resources list -uipath resources bindings +uipath resources generate-bindings ``` Declares the platform resources the project uses in one place, `uipath_resources.py`: @@ -203,7 +203,7 @@ class ProjectResources: invoice_review = resource.queue(name="InvoiceReview") # no folder: the project's own ``` -The code passes a handle's fields to the SDK (`sdk.assets.retrieve(name=ProjectResources.invoice_threshold.name, folder_path=ProjectResources.invoice_threshold.folder_path)`). `uipath resources bindings`, `uipath pack` and `uipath push` derive `bindings.json` from the file, keeping any hand-written entries, so the package carries exactly the bindings the code declares. The commands work offline; looking a resource up in the tenant and adding it to a solution is done by the `uip` CLI (`uip codedagent resources`, `uip function resources`), which forwards to these commands. +The code passes a handle's fields to the SDK (`sdk.assets.retrieve(name=ProjectResources.invoice_threshold.name, folder_path=ProjectResources.invoice_threshold.folder_path)`). `uipath resources generate-bindings`, `uipath pack` and `uipath push` derive `bindings.json` from the file, keeping any hand-written entries, so the package carries exactly the bindings the code declares. The commands work offline; looking a resource up in the tenant and adding it to a solution is done by the `uip` CLI (`uip codedagent resources`, `uip function resources`), which forwards to these commands. ## Project Structure diff --git a/packages/uipath/CLAUDE.md b/packages/uipath/CLAUDE.md index 45f624753..acca6f739 100644 --- a/packages/uipath/CLAUDE.md +++ b/packages/uipath/CLAUDE.md @@ -61,7 +61,7 @@ Uses **click** framework. Commands are organized as `cli_.py` files. | `cli_server.py` | `server` | Run as server | | `cli_register.py` | `register` | Register resource | | `cli_debug.py` | `debug` | Debug execution | -| `cli_resources.py` | `resources` | Declare the project's platform resources in `uipath_resources.py` (`add`, `list`) and derive `bindings.json` from it (`bindings`); `pack`, `push`, `debug` and `eval` regenerate the bindings first. Parsing and editing live in `_declarations/` | +| `cli_resources.py` | `resources` | Declare the project's platform resources in `uipath_resources.py` (`add`, `list`) and derive `bindings.json` from it (`generate-bindings`); `pack`, `push`, `debug` and `eval` regenerate the bindings first. Parsing and editing live in `_declarations/` | Sub-commands: `services/cli_assets.py` (asset management), `services/cli_buckets.py` (bucket management). diff --git a/packages/uipath/README.md b/packages/uipath/README.md index 35164a749..94708a42b 100644 --- a/packages/uipath/README.md +++ b/packages/uipath/README.md @@ -189,7 +189,7 @@ Publishes the most recently created package to your UiPath Orchestrator. uipath resources add InvoiceThreshold --kind asset --folder-path Finance/Shared --type integer uipath resources add InvoiceReview --kind queue uipath resources list -uipath resources bindings +uipath resources generate-bindings ``` Declares the platform resources the project uses in one place, `uipath_resources.py`: @@ -203,7 +203,7 @@ class ProjectResources: invoice_review = resource.queue(name="InvoiceReview") # no folder: the project's own ``` -The code passes a handle's fields to the SDK (`sdk.assets.retrieve(name=ProjectResources.invoice_threshold.name, folder_path=ProjectResources.invoice_threshold.folder_path)`). `uipath resources bindings`, `uipath pack` and `uipath push` derive `bindings.json` from the file, keeping any hand-written entries, so the package carries exactly the bindings the code declares. The commands work offline; looking a resource up in the tenant and adding it to a solution is done by the `uip` CLI (`uip codedagent resources`, `uip function resources`), which forwards to these commands. +The code passes a handle's fields to the SDK (`sdk.assets.retrieve(name=ProjectResources.invoice_threshold.name, folder_path=ProjectResources.invoice_threshold.folder_path)`). `uipath resources generate-bindings`, `uipath pack` and `uipath push` derive `bindings.json` from the file, keeping any hand-written entries, so the package carries exactly the bindings the code declares. The commands work offline; looking a resource up in the tenant and adding it to a solution is done by the `uip` CLI (`uip codedagent resources`, `uip function resources`), which forwards to these commands. ## Project Structure diff --git a/packages/uipath/src/uipath/_cli/_declarations/__init__.py b/packages/uipath/src/uipath/_cli/_declarations/__init__.py index 664234643..3758f2f75 100644 --- a/packages/uipath/src/uipath/_cli/_declarations/__init__.py +++ b/packages/uipath/src/uipath/_cli/_declarations/__init__.py @@ -3,7 +3,7 @@ A coded project declares the platform resources it uses as attributes of a ``ProjectResources`` class in ``uipath_resources.py`` (see ``uipath.resources``). The ``uipath resources`` commands read and edit that -file as text, never importing it, and ``uipath resources bindings``, ``pack`` +file as text, never importing it, and ``uipath resources generate-bindings``, ``pack`` and ``push`` derive the project's ``bindings.json`` from it. - ``_model``: a declaration as the commands see it, and its binding key. diff --git a/packages/uipath/src/uipath/_cli/_declarations/_bindings.py b/packages/uipath/src/uipath/_cli/_declarations/_bindings.py index bd36d7b64..0c5e5c174 100644 --- a/packages/uipath/src/uipath/_cli/_declarations/_bindings.py +++ b/packages/uipath/src/uipath/_cli/_declarations/_bindings.py @@ -1,7 +1,7 @@ """``bindings.json`` derived from the project's resource declarations. The declarations are the source and the bindings a build output: ``uipath -resources bindings``, ``pack`` and ``push`` write them before they read them. +resources generate-bindings``, ``pack`` and ``push`` write them before they read them. A hand-written ``bindings.json`` is the base: its entries are kept, except an entry a declaration replaces (same kind and key) and entries an earlier derivation wrote (``metadata.Source`` is ``code``), so bindings for kinds @@ -129,19 +129,21 @@ def derive_bindings( ) -> DerivedBindings: """One entry per declared kind and key, after the base entries the declarations leave in place.""" derived: dict[str, dict[str, Any]] = {} - declared_types: dict[str, str | None] = {} + declared_details: dict[str, tuple[str | None, str | None]] = {} diagnostics: list[str] = [] for declaration in declarations: identity = declaration.identity + details = (declaration.type, declaration.version) if identity in derived: - if declared_types[identity] != declaration.type: + if declared_details[identity] != details: + what = "versions" if declaration.kind == SKILL_BUNDLE_KIND else "types" diagnostics.append( f'{declaration.kind} "{declaration.key}" is declared more than once ' - f"with different types; the first declaration is used." + f"with different {what}; the first declaration is used." ) continue derived[identity] = binding_entry(declaration) - declared_types[identity] = declaration.type + declared_details[identity] = details kept = [ entry diff --git a/packages/uipath/src/uipath/_cli/_declarations/_editor.py b/packages/uipath/src/uipath/_cli/_declarations/_editor.py index cdf29795e..914149665 100644 --- a/packages/uipath/src/uipath/_cli/_declarations/_editor.py +++ b/packages/uipath/src/uipath/_cli/_declarations/_editor.py @@ -158,7 +158,7 @@ def insert_declaration( Raises: DeclarationsSyntaxError: The file is not valid Python. DeclarationsFileError: The file has content but no module-level - ``class ProjectResources``. + ``class ProjectResources``, or the class body sits on the class line. """ if not source.strip(): return _new_file(declaration) @@ -174,6 +174,11 @@ def insert_declaration( f"Add the declaration by hand, or move your declarations into that class." ) + if info.inline: + raise DeclarationsFileError( + f"{file_name}:{info.lineno}: the body of `class {CLASS_NAME}` is on the " + f"class line itself; put its members on their own indented lines, then run the command again." + ) attribute = to_python_identifier(_identifier_source(declaration), info.taken) lines = source.split("\n") body_start, body_end = info.body_lines diff --git a/packages/uipath/src/uipath/_cli/_declarations/_parser.py b/packages/uipath/src/uipath/_cli/_declarations/_parser.py index 67bccad9e..be1f57fc8 100644 --- a/packages/uipath/src/uipath/_cli/_declarations/_parser.py +++ b/packages/uipath/src/uipath/_cli/_declarations/_parser.py @@ -70,6 +70,8 @@ class ClassInfo: indent: The indentation of its body. taken: Attribute, method and nested class names already bound in the body. only_placeholder: Whether the body is a lone ``pass`` or ``...``. + inline: Whether the body sits on the ``class`` line itself + (``class ProjectResources: a = ...``), where no line can be added. """ lineno: int @@ -78,6 +80,7 @@ class ClassInfo: indent: str taken: frozenset[str] only_placeholder: bool + inline: bool @dataclass(frozen=True) @@ -260,6 +263,7 @@ def _class_info(tree: ast.Module, lines: list[str]) -> ClassInfo | None: indent=indent, taken=frozenset(taken), only_placeholder=only_placeholder, + inline=first.lineno == statement.lineno, ) return None diff --git a/packages/uipath/src/uipath/_cli/cli_resources.py b/packages/uipath/src/uipath/_cli/cli_resources.py index 0a8270de7..3cdc5abf6 100644 --- a/packages/uipath/src/uipath/_cli/cli_resources.py +++ b/packages/uipath/src/uipath/_cli/cli_resources.py @@ -157,7 +157,7 @@ def _declaration_from_options( ) if kind == CONNECTION_KIND: - if not connection_id or not connector: + if not (connection_id or "").strip() or not (connector or "").strip(): _fail( "A connection is declared by its id and connector key: pass --id and " "--connector (uip codedagent resources add looks them up by name)." @@ -252,7 +252,7 @@ def resources() -> None: \b The file is the one place a coded project names the platform resources it - uses; bindings.json is derived from it by `uipath resources bindings`, + uses; bindings.json is derived from it by `uipath resources generate-bindings`, `uipath pack` and `uipath push`. These commands work offline and never import the file. @@ -262,7 +262,7 @@ def resources() -> None: uipath resources add InvoiceReview --kind queue uipath resources add "Finance Slack" --kind connection --id 3121165f-ce9b-4503-8c10-289ae6b21bd8 --connector uipath-slack uipath resources list - uipath resources bindings + uipath resources generate-bindings """ # noqa: D301 @@ -360,7 +360,7 @@ def add( f"{click.style(result.attribute or '', fg='cyan')} = {_describe(declaration)}" ) console.hint( - f"Run {click.style('uipath resources bindings', fg='cyan')} to regenerate " + f"Run {click.style('uipath resources generate-bindings', fg='cyan')} to regenerate " f"bindings.json now; pack and push do it for you." ) else: @@ -436,11 +436,11 @@ def list_declarations( console.info(f" {attribute}{_describe(row.declaration)}") -@resources.command(name="bindings") +@resources.command(name="generate-bindings") @_format_option @_project_path_option -@track_command("resources bindings") -def bindings(format: str | None, project_path: str | None) -> None: +@track_command("resources generate-bindings") +def generate_bindings(format: str | None, project_path: str | None) -> None: """Write bindings.json from the declarations in uipath_resources.py. One binding per declared resource, after the hand-written entries the @@ -450,7 +450,7 @@ def bindings(format: str | None, project_path: str | None) -> None: \b Examples: - uipath resources bindings + uipath resources generate-bindings """ # noqa: D301 from ._declarations._bindings import BindingsFileError, sync_bindings from ._declarations._parser import DeclarationsSyntaxError diff --git a/packages/uipath/tests/cli/test_resource_declarations.py b/packages/uipath/tests/cli/test_resource_declarations.py index a9355216d..bcf5ea3cf 100644 --- a/packages/uipath/tests/cli/test_resource_declarations.py +++ b/packages/uipath/tests/cli/test_resource_declarations.py @@ -344,6 +344,13 @@ def test_a_file_without_the_class_is_refused(self) -> None: "x = 1\n", Declaration(kind="queue", name="Review"), FILE ) + def test_an_inline_class_body_is_refused(self) -> None: + source = 'from uipath.resources import resource\n\n\nclass ProjectResources: a = resource.queue(name="A")\n' + with pytest.raises( + DeclarationsFileError, match=rf"{FILE}:4: .*own indented lines" + ): + insert_declaration(source, Declaration(kind="queue", name="B"), FILE) + def test_renders_a_connection_by_id_and_connector(self) -> None: line = render_declaration( "slack", @@ -509,6 +516,21 @@ def test_no_base_gives_version_2_0_and_duplicates_are_reported_once(self) -> Non 'asset "A" is declared more than once with different types; the first declaration is used.' ] + def test_skill_bundles_pinned_to_different_versions_are_reported(self) -> None: + declared = [ + Declaration(kind="skillBundle", name="finance", version="7"), + Declaration(kind="skillBundle", name="finance", version="8"), + Declaration(kind="skillBundle", name="finance", version="7"), + ] + derived = derive_bindings(declared, None) + assert derived.derived == 1 + assert ( + derived.document["resources"][0]["value"]["version"]["defaultValue"] == "7" + ) + assert derived.diagnostics == [ + 'skillBundle "finance" is declared more than once with different versions; the first declaration is used.' + ] + class TestSyncBindings: def test_without_a_declarations_file_nothing_happens(self, tmp_path) -> None: diff --git a/packages/uipath/tests/cli/test_resources.py b/packages/uipath/tests/cli/test_resources.py index 4ab324330..9e25a024a 100644 --- a/packages/uipath/tests/cli/test_resources.py +++ b/packages/uipath/tests/cli/test_resources.py @@ -161,6 +161,18 @@ def test_declares_a_connection_by_id_and_connector(self, runner: CliRunner) -> N ["X", "--kind", "connection", "--id", "nope", "--connector", "x"], "is not a connection id", ), + ( + [ + "X", + "--kind", + "connection", + "--id", + CONNECTION_ID, + "--connector", + " ", + ], + "pass --id and --connector", + ), ( [ "X", @@ -456,7 +468,7 @@ def test_writes_bindings_json_over_the_hand_written_entries( "uipath-slack", ], ) - result = runner.invoke(cli, ["resources", "bindings"]) + result = runner.invoke(cli, ["resources", "generate-bindings"]) assert result.exit_code == 0, result.output assert "2 declared, 1 hand-written kept" in result.output document = read_bindings() @@ -469,11 +481,13 @@ def test_writes_bindings_json_over_the_hand_written_entries( "BindingsVersion": "2.2", "Source": "code", } - again = runner.invoke(cli, ["resources", "bindings", "--format", "json"]) + again = runner.invoke( + cli, ["resources", "generate-bindings", "--format", "json"] + ) assert json.loads(again.stdout)["changed"] is False def test_without_a_declarations_file_fails(self, runner: CliRunner) -> None: - result = runner.invoke(cli, ["resources", "bindings"]) + result = runner.invoke(cli, ["resources", "generate-bindings"]) assert result.exit_code == 1 assert "No uipath_resources.py in the project" in result.output assert not os.path.exists("bindings.json") @@ -482,7 +496,7 @@ def test_a_broken_bindings_json_fails(self, runner: CliRunner) -> None: runner.invoke(cli, ["resources", "add", "Review", "--kind", "queue"]) with open("bindings.json", "w") as f: f.write("{") - result = runner.invoke(cli, ["resources", "bindings"]) + result = runner.invoke(cli, ["resources", "generate-bindings"]) assert result.exit_code == 1 assert "not valid JSON" in result.output From c71847ddc1d594418ab8def852ff73b82221fd46 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:34:01 +0000 Subject: [PATCH 6/8] feat(cli): add uipath resources remove Removes the one declaration that matches the name and whatever else is passed (--kind, --folder-path, --id). No match is an error; several matches are listed with their lines and nothing is removed. A declaration that shares its line with other code or sits inside a larger expression is left to the user, so no neighbouring statement is ever cut. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_014t9fy7CGYG2vBLEfHwu12m --- README.md | 1 + packages/uipath/CLAUDE.md | 2 +- packages/uipath/README.md | 1 + .../src/uipath/_cli/_declarations/__init__.py | 2 +- .../src/uipath/_cli/_declarations/_editor.py | 48 +++++- .../src/uipath/_cli/_declarations/_parser.py | 62 +++++-- .../uipath/src/uipath/_cli/cli_resources.py | 124 ++++++++++++++ .../tests/cli/test_resource_declarations.py | 81 +++++++++ packages/uipath/tests/cli/test_resources.py | 159 ++++++++++++++++++ 9 files changed, 458 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 94708a42b..8c78c9c9a 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,7 @@ Publishes the most recently created package to your UiPath Orchestrator. uipath resources add InvoiceThreshold --kind asset --folder-path Finance/Shared --type integer uipath resources add InvoiceReview --kind queue uipath resources list +uipath resources remove InvoiceReview uipath resources generate-bindings ``` diff --git a/packages/uipath/CLAUDE.md b/packages/uipath/CLAUDE.md index acca6f739..c312a1756 100644 --- a/packages/uipath/CLAUDE.md +++ b/packages/uipath/CLAUDE.md @@ -61,7 +61,7 @@ Uses **click** framework. Commands are organized as `cli_.py` files. | `cli_server.py` | `server` | Run as server | | `cli_register.py` | `register` | Register resource | | `cli_debug.py` | `debug` | Debug execution | -| `cli_resources.py` | `resources` | Declare the project's platform resources in `uipath_resources.py` (`add`, `list`) and derive `bindings.json` from it (`generate-bindings`); `pack`, `push`, `debug` and `eval` regenerate the bindings first. Parsing and editing live in `_declarations/` | +| `cli_resources.py` | `resources` | Declare the project's platform resources in `uipath_resources.py` (`add`, `list`, `remove`) and derive `bindings.json` from it (`generate-bindings`); `pack`, `push`, `debug` and `eval` regenerate the bindings first. Parsing and editing live in `_declarations/` | Sub-commands: `services/cli_assets.py` (asset management), `services/cli_buckets.py` (bucket management). diff --git a/packages/uipath/README.md b/packages/uipath/README.md index 94708a42b..8c78c9c9a 100644 --- a/packages/uipath/README.md +++ b/packages/uipath/README.md @@ -189,6 +189,7 @@ Publishes the most recently created package to your UiPath Orchestrator. uipath resources add InvoiceThreshold --kind asset --folder-path Finance/Shared --type integer uipath resources add InvoiceReview --kind queue uipath resources list +uipath resources remove InvoiceReview uipath resources generate-bindings ``` diff --git a/packages/uipath/src/uipath/_cli/_declarations/__init__.py b/packages/uipath/src/uipath/_cli/_declarations/__init__.py index 3758f2f75..9ca9b4fcc 100644 --- a/packages/uipath/src/uipath/_cli/_declarations/__init__.py +++ b/packages/uipath/src/uipath/_cli/_declarations/__init__.py @@ -8,7 +8,7 @@ - ``_model``: a declaration as the commands see it, and its binding key. - ``_parser``: the literal-only ``ast`` reader, with a diagnostic per call it skips. -- ``_editor``: adds declarations to the file's text. +- ``_editor``: adds and removes declarations in the file's text. - ``_bindings``: derives ``bindings.json`` over the hand-written entries. - ``_project``: where the files live. """ diff --git a/packages/uipath/src/uipath/_cli/_declarations/_editor.py b/packages/uipath/src/uipath/_cli/_declarations/_editor.py index 914149665..50eaf5d12 100644 --- a/packages/uipath/src/uipath/_cli/_declarations/_editor.py +++ b/packages/uipath/src/uipath/_cli/_declarations/_editor.py @@ -1,9 +1,8 @@ -"""Adds declarations to the text of ``uipath_resources.py``. +"""Adds and removes declarations in the text of ``uipath_resources.py``. The file is edited as text so that everything else in it (comments, other members, formatting) stays as the user wrote it: a declaration is one line -added after the last member of ``ProjectResources``. There is no remove, as in -the ``uip`` CLI: a declaration is one line the user deletes. +added after the last member of ``ProjectResources``, or one statement removed. """ import ast @@ -18,7 +17,7 @@ SDK_IMPORT_LINE, Declaration, ) -from ._parser import ParsedDeclarations, parse_declarations +from ._parser import ParsedDeclaration, ParsedDeclarations, parse_declarations _DEFAULT_INDENT = " " _FALLBACK_IDENTIFIER = "resource" @@ -44,6 +43,19 @@ class InsertResult: attribute: str | None +@dataclass(frozen=True) +class RemoveResult: + """What removing a declaration did. + + Attributes: + source: The file's new text. + attribute: The attribute the removed declaration was bound to, if any. + """ + + source: str + attribute: str | None + + def to_python_identifier(name: str, taken: frozenset[str] | set[str]) -> str: """A snake_case attribute name for ``name``, unique among ``taken`` and never a keyword. @@ -197,11 +209,39 @@ def insert_declaration( return InsertResult(source="\n".join(lines), added=True, attribute=attribute) +def remove_declaration( + source: str, parsed: ParsedDeclarations, target: ParsedDeclaration, file_name: str +) -> RemoveResult: + """Removes ``target``, one of ``parsed.declarations``: the whole statement that holds it. + + Raises: + DeclarationsFileError: The declaration is nested in a larger + expression or shares its line with another statement, so it is left + for the user to remove. + """ + if target.statement_lines is None: + raise DeclarationsFileError( + f"{file_name}:{target.lineno}: the {target.declaration.label} declaration " + f"shares its line with other code or is part of a larger expression; " + f"remove it by hand." + ) + start, end = target.statement_lines + lines = source.split("\n") + del lines[start - 1 : end] + info = parsed.project_resources + if info is not None and info.body_lines == target.statement_lines: + # The class body would be empty, which is not valid Python. + lines.insert(start - 1, f"{info.indent}pass" + _line_end(lines, start - 2)) + return RemoveResult(source="\n".join(lines), attribute=target.attribute) + + __all__ = [ "DeclarationsFileError", "InsertResult", "ParsedDeclarations", + "RemoveResult", "insert_declaration", + "remove_declaration", "render_declaration", "to_python_identifier", ] diff --git a/packages/uipath/src/uipath/_cli/_declarations/_parser.py b/packages/uipath/src/uipath/_cli/_declarations/_parser.py index be1f57fc8..bbe5825ef 100644 --- a/packages/uipath/src/uipath/_cli/_declarations/_parser.py +++ b/packages/uipath/src/uipath/_cli/_declarations/_parser.py @@ -50,7 +50,9 @@ class ParsedDeclaration: lineno: The line of the ``resource.(`` call. statement_lines: The first and last line of the statement that holds the call, when the call is the whole value of an assignment or an - expression statement; ``None`` when it is nested in something else. + expression statement and no other statement shares those lines; + ``None`` when it is nested in something else or shares a line + (``a = resource.queue(...); b = ...``), so it cannot be cut out alone. """ declaration: Declaration @@ -214,6 +216,32 @@ def _statement_value(statement: ast.stmt) -> ast.expr | None: return None +def _statement_lists(tree: ast.Module) -> list[tuple[ast.AST, list[ast.stmt]]]: + """Every list of statements in the module (a body, an ``else``, a ``finally``), with the node that holds it.""" + lists: list[tuple[ast.AST, list[ast.stmt]]] = [] + for node in ast.walk(tree): + for _, field in ast.iter_fields(node): + if ( + isinstance(field, list) + and field + and all(isinstance(item, ast.stmt) for item in field) + ): + lists.append((node, field)) + return lists + + +def _owns_its_lines(parent: ast.AST, body: list[ast.stmt], index: int) -> bool: + """Whether no sibling, and not the parent's header, shares a line with ``body[index]``.""" + node = body[index] + start, end = node.lineno, node.end_lineno or node.lineno + if index > 0 and (body[index - 1].end_lineno or body[index - 1].lineno) >= start: + return False + if index + 1 < len(body) and body[index + 1].lineno <= end: + return False + header = getattr(parent, "lineno", None) + return header is None or header < start + + def _imports_helper(tree: ast.Module) -> bool: """Whether the module binds the SDK helper as ``resource``; ``resource as r`` does not.""" from ._model import SDK_MODULE @@ -284,35 +312,37 @@ def parse_declarations(source: str, file_name: str) -> ParsedDeclarations: diagnostics: list[str] = [] # A call that is the whole value of a statement, keyed by its node, so the # walk below knows which calls can be removed as one statement. - statements: dict[int, tuple[str | None, tuple[int, int]]] = {} - for node in ast.walk(tree): - if isinstance(node, ast.stmt): + statements: dict[int, tuple[str | None, tuple[int, int] | None]] = {} + for parent, body in _statement_lists(tree): + for index, node in enumerate(body): value = _statement_value(node) - if isinstance(value, ast.Call) and _declared_method(value): - statements[id(value)] = ( - _bound_name(node), - (node.lineno, node.end_lineno or node.lineno), - ) + if not (isinstance(value, ast.Call) and _declared_method(value)): + continue + span = (node.lineno, node.end_lineno or node.lineno) + statements[id(value)] = ( + _bound_name(node), + span if _owns_its_lines(parent, body, index) else None, + ) - for node in ast.walk(tree): - if not isinstance(node, ast.Call): + for call in ast.walk(tree): + if not isinstance(call, ast.Call): continue - method = _declared_method(node) + method = _declared_method(call) if method is None: continue - values = _literal_keywords(node) + values = _literal_keywords(call) result = values if isinstance(values, str) else _to_declaration(method, values) if isinstance(result, str): diagnostics.append( - f"{file_name}:{node.lineno}: resource.{method}() {result}; skipped" + f"{file_name}:{call.lineno}: resource.{method}() {result}; skipped" ) continue - attribute, statement_lines = statements.get(id(node), (None, None)) + attribute, statement_lines = statements.get(id(call), (None, None)) declarations.append( ParsedDeclaration( declaration=result, attribute=attribute, - lineno=node.lineno, + lineno=call.lineno, statement_lines=statement_lines, ) ) diff --git a/packages/uipath/src/uipath/_cli/cli_resources.py b/packages/uipath/src/uipath/_cli/cli_resources.py index 3cdc5abf6..eaa456c3d 100644 --- a/packages/uipath/src/uipath/_cli/cli_resources.py +++ b/packages/uipath/src/uipath/_cli/cli_resources.py @@ -262,6 +262,7 @@ def resources() -> None: uipath resources add InvoiceReview --kind queue uipath resources add "Finance Slack" --kind connection --id 3121165f-ce9b-4503-8c10-289ae6b21bd8 --connector uipath-slack uipath resources list + uipath resources remove InvoiceReview uipath resources generate-bindings """ # noqa: D301 @@ -436,6 +437,129 @@ def list_declarations( console.info(f" {attribute}{_describe(row.declaration)}") +@resources.command(name="remove") +@click.argument("name", required=False) +@_kind_option("Resource kind; omit it when the name alone identifies the declaration") +@click.option( + "--folder-path", + help="The folder the declaration names; pass it when the same name is declared in several folders.", +) +@click.option("--id", "connection_id", help="A connection's id (a GUID)") +@_format_option +@_project_path_option +@track_command("resources remove") +def remove( + name: str | None, + kind: str | None, + folder_path: str | None, + connection_id: str | None, + format: str | None, + project_path: str | None, +) -> None: + """Remove a declaration from uipath_resources.py. + + Finds the one declaration matching the name (exactly) and whatever else + you pass: --kind, --folder-path, or --id for a connection. No match is an + error, and so is more than one: the matches are listed so you can pass + --folder-path or --kind to pick one. The statement is cut out as a whole. + Code that still uses the attribute is left to you; the binding leaves + bindings.json at the next `uipath resources generate-bindings`, pack or push. + + \b + Examples: + uipath resources remove InvoiceReview + uipath resources remove InvoiceThreshold --kind asset --folder-path Finance/Shared + uipath resources remove --kind connection --id 3121165f-ce9b-4503-8c10-289ae6b21bd8 + """ # noqa: D301 + from ._declarations._editor import DeclarationsFileError, remove_declaration + from ._declarations._model import normalize_folder_path + from ._declarations._parser import DeclarationsSyntaxError, parse_declarations + from ._declarations._project import read_declarations_file, write_declarations_file + + root = _resolve_root(project_path) + wanted_kind = _resolved_kind(kind) if kind is not None else None + if not (name or "").strip() and not (connection_id or "").strip(): + _fail("Pass the resource name as declared, or --id for a connection.") + wanted_folder = ( + normalize_folder_path(folder_path) or "" if folder_path is not None else None + ) + + file = read_declarations_file(root) + if not file.exists: + _fail(f"No {file.relative_path} in the project; nothing to remove.") + try: + parsed = parse_declarations(file.content, file.relative_path) + except DeclarationsSyntaxError as error: + _fail(str(error)) + return + for diagnostic in parsed.diagnostics: + _warn(diagnostic) + + matches = [ + candidate + for candidate in parsed.declarations + if (wanted_kind is None or candidate.declaration.kind == wanted_kind) + and (not name or candidate.declaration.name == name) + and (connection_id is None or candidate.declaration.id == connection_id) + and ( + wanted_folder is None or candidate.declaration.folder_path == wanted_folder + ) + ] + asked = " ".join( + part + for part in [ + wanted_kind or "resource", + f'"{name}"' if name else "", + f"with id {connection_id}" if connection_id else "", + f'in folder "{wanted_folder}"' + if wanted_folder + else ("without a folder" if wanted_folder == "" else ""), + ] + if part + ) + if not matches: + _fail( + f"No {asked} is declared in {file.relative_path}. " + f"Run `uipath resources list` to see the declarations." + ) + if len(matches) > 1: + listed = "; ".join( + f"line {m.lineno}: {_describe(m.declaration)}" for m in matches + ) + _fail( + f"{asked} matches {len(matches)} declarations in {file.relative_path}: {listed}. " + f"Pass --kind, --folder-path or --id to pick one." + ) + target = matches[0] + try: + result = remove_declaration(file.content, parsed, target, file.relative_path) + except DeclarationsFileError as error: + _fail(str(error)) + return + write_declarations_file(file, result.source) + + if _wants_json(): + _emit( + { + "removed": True, + **_row(target.declaration), + **({"attribute": result.attribute} if result.attribute else {}), + "line": target.lineno, + "file": file.relative_path, + } + ) + return + attribute = f" ({result.attribute})" if result.attribute else "" + console.success( + f"Removed {_describe(target.declaration)}{attribute} from {file.relative_path}." + ) + if result.attribute: + console.hint( + f"Code that still uses ProjectResources.{result.attribute} needs updating; " + f"the binding leaves bindings.json at the next `uipath resources generate-bindings`, pack or push." + ) + + @resources.command(name="generate-bindings") @_format_option @_project_path_option diff --git a/packages/uipath/tests/cli/test_resource_declarations.py b/packages/uipath/tests/cli/test_resource_declarations.py index bcf5ea3cf..e5535053f 100644 --- a/packages/uipath/tests/cli/test_resource_declarations.py +++ b/packages/uipath/tests/cli/test_resource_declarations.py @@ -15,6 +15,7 @@ from uipath._cli._declarations._editor import ( DeclarationsFileError, insert_declaration, + remove_declaration, render_declaration, to_python_identifier, ) @@ -209,6 +210,29 @@ class ProjectResources: assert parsed.find("Asset", "A.Shared") is not None assert parsed.find("asset", "A") is None + def test_a_declaration_sharing_its_line_is_read_but_not_removable(self) -> None: + source = src( + """ + from uipath.resources import resource + + + class ProjectResources: + a = resource.queue(name="A"); b = resource.queue(name="B") + c = resource.queue(name="C") + """ + ) + parsed = parse_declarations(source, FILE) + assert [p.attribute for p in parsed.declarations] == ["a", "b", "c"] + assert [p.statement_lines for p in parsed.declarations] == [None, None, (6, 6)] + + def test_an_inline_class_body_is_read_but_flagged(self) -> None: + parsed = parse_declarations( + 'class ProjectResources: a = resource.queue(name="A")\n', FILE + ) + assert parsed.resources == [Declaration(kind="queue", name="A")] + assert parsed.project_resources is not None and parsed.project_resources.inline + assert parsed.declarations[0].statement_lines is None + class TestResolveKind: @pytest.mark.parametrize( @@ -389,6 +413,63 @@ def test_renders_a_skill_bundle_version_and_escapes_quotes(self) -> None: ) +class TestRemove: + SOURCE = src( + """ + from uipath.resources import resource + + + class ProjectResources: + a = resource.queue(name="A") + b = resource.asset( + name="B", + folder_path="Shared", + ) # multi-line + """ + ) + + def _target(self, parsed, name: str): + return next(p for p in parsed.declarations if p.declaration.name == name) + + def test_removes_the_whole_statement(self) -> None: + parsed = parse_declarations(self.SOURCE, FILE) + result = remove_declaration( + self.SOURCE, parsed, self._target(parsed, "B"), FILE + ) + assert result.attribute == "b" + assert ( + result.source + == 'from uipath.resources import resource\n\n\nclass ProjectResources:\n a = resource.queue(name="A")\n' + ) + + def test_the_last_member_leaves_a_pass(self) -> None: + parsed = parse_declarations(self.SOURCE, FILE) + once = remove_declaration( + self.SOURCE, parsed, self._target(parsed, "A"), FILE + ).source + parsed = parse_declarations(once, FILE) + twice = remove_declaration(once, parsed, self._target(parsed, "B"), FILE) + assert twice.source.endswith("class ProjectResources:\n pass\n") + + @pytest.mark.parametrize( + "body", + [ + ' q = [resource.queue(name="N")]', + ' q = resource.queue(name="N"); r = resource.queue(name="R")', + ], + ids=["nested", "shared-line"], + ) + def test_a_declaration_that_does_not_own_its_lines_is_left_to_the_user( + self, body: str + ) -> None: + source = f"from uipath.resources import resource\n\n\nclass ProjectResources:\n{body}\n" + parsed = parse_declarations(source, FILE) + with pytest.raises( + DeclarationsFileError, match=f"{FILE}:5: .*remove it by hand" + ): + remove_declaration(source, parsed, self._target(parsed, "N"), FILE) + + class TestDeriveBindings: def test_entry_shapes(self) -> None: asset = binding_entry( diff --git a/packages/uipath/tests/cli/test_resources.py b/packages/uipath/tests/cli/test_resources.py index 9e25a024a..33f115709 100644 --- a/packages/uipath/tests/cli/test_resources.py +++ b/packages/uipath/tests/cli/test_resources.py @@ -427,6 +427,165 @@ def test_a_syntax_error_fails(self, runner: CliRunner) -> None: assert "uipath_resources.py:2:" in result.output +@pytest.mark.usefixtures("project") +class TestResourcesRemove: + def _declare(self, runner: CliRunner) -> None: + with open(FILE, "w") as f: + f.write( + "from uipath.resources import resource\n\n\nclass ProjectResources:\n" + ' threshold = resource.asset(name="InvoiceThreshold", folder_path="Finance/Shared", type="integer")\n' + ' threshold_2 = resource.asset(name="InvoiceThreshold", folder_path="Shared", type="integer")\n' + ' review = resource.queue(name="Review")\n' + ' review_entity = resource.entity(name="Review")\n' + f' slack = resource.connection(id="{CONNECTION_ID}", connector="uipath-slack", name="Finance Slack")\n' + ' a = resource.queue(name="A"); b = resource.queue(name="B")\n' + ) + + def test_the_name_alone_removes_a_unique_declaration( + self, runner: CliRunner + ) -> None: + self._declare(runner) + result = runner.invoke(cli, ["resources", "remove", "Finance Slack"]) + assert result.exit_code == 0, result.output + assert "Removed connection Finance Slack" in result.output + assert "ProjectResources.slack needs updating" in result.output + assert CONNECTION_ID not in read_file() + + def test_a_missing_declaration_is_an_error(self, runner: CliRunner) -> None: + self._declare(runner) + before = read_file() + result = runner.invoke(cli, ["resources", "remove", "Missing"]) + assert result.exit_code == 1 + assert ( + 'No resource "Missing" is declared in uipath_resources.py' in result.output + ) + wrong_folder = runner.invoke( + cli, + [ + "resources", + "remove", + "Review", + "--kind", + "queue", + "--folder-path", + "Shared", + ], + ) + assert wrong_folder.exit_code == 1 + assert 'No queue "Review" in folder "Shared" is declared' in wrong_folder.output + assert read_file() == before + + def test_several_matches_are_listed_and_nothing_is_removed( + self, runner: CliRunner + ) -> None: + self._declare(runner) + before = read_file() + by_folder = runner.invoke(cli, ["resources", "remove", "InvoiceThreshold"]) + assert by_folder.exit_code == 1 + assert 'resource "InvoiceThreshold" matches 2 declarations' in by_folder.output + assert ( + "line 5: asset InvoiceThreshold, folder Finance/Shared" in by_folder.output + ) + assert "line 6: asset InvoiceThreshold, folder Shared" in by_folder.output + assert "Pass --kind, --folder-path or --id to pick one" in by_folder.output + by_kind = runner.invoke(cli, ["resources", "remove", "Review"]) + assert by_kind.exit_code == 1 + assert "line 7: queue Review; line 8: entity Review" in by_kind.output + assert read_file() == before + + def test_folder_kind_and_id_pick_one(self, runner: CliRunner) -> None: + self._declare(runner) + assert ( + runner.invoke( + cli, + ["resources", "remove", "InvoiceThreshold", "--folder-path", "Shared"], + ).exit_code + == 0 + ) + assert ( + runner.invoke( + cli, ["resources", "remove", "Review", "--kind", "entity"] + ).exit_code + == 0 + ) + result = runner.invoke( + cli, + [ + "resources", + "remove", + "--kind", + "connection", + "--id", + CONNECTION_ID, + "--format", + "json", + ], + ) + assert result.exit_code == 0, result.output + assert json.loads(result.stdout) == { + "removed": True, + "kind": "connection", + "name": "Finance Slack", + "id": CONNECTION_ID, + "type": "uipath-slack", + "attribute": "slack", + "line": 7, + "file": FILE, + } + content = read_file() + assert 'folder_path="Shared"' not in content + assert "resource.entity" not in content + assert CONNECTION_ID not in content + assert ( + 'threshold = resource.asset(name="InvoiceThreshold", folder_path="Finance/Shared"' + in content + ) + assert 'review = resource.queue(name="Review")' in content + + def test_a_declaration_sharing_its_line_is_refused(self, runner: CliRunner) -> None: + self._declare(runner) + result = runner.invoke(cli, ["resources", "remove", "A"]) + assert result.exit_code == 1 + assert ( + 'uipath_resources.py:10: the queue "A" declaration shares its line' + in result.output + ) + assert ( + 'a = resource.queue(name="A"); b = resource.queue(name="B")' in read_file() + ) + + def test_removing_the_last_declaration_leaves_a_valid_class( + self, runner: CliRunner + ) -> None: + runner.invoke(cli, ["resources", "add", "Review", "--kind", "queue"]) + assert runner.invoke(cli, ["resources", "remove", "Review"]).exit_code == 0 + assert read_file().endswith("class ProjectResources:\n pass\n") + assert ( + runner.invoke( + cli, ["resources", "add", "Review", "--kind", "queue"] + ).exit_code + == 0 + ) + assert read_file().endswith( + 'class ProjectResources:\n review = resource.queue(name="Review")\n' + ) + + @pytest.mark.parametrize( + ("args", "message"), + [ + ([], "Pass the resource name as declared, or --id"), + (["X", "--kind", "widget"], '"widget" is not a resource kind'), + (["X"], "nothing to remove"), + ], + ) + def test_invalid_options_fail( + self, runner: CliRunner, args: list[str], message: str + ) -> None: + result = runner.invoke(cli, ["resources", "remove", *args]) + assert result.exit_code == 1, result.output + assert message in result.output + + @pytest.mark.usefixtures("project") class TestResourcesBindings: def test_writes_bindings_json_over_the_hand_written_entries( From adc8753b0b820e0055fb3529298a64efb944d8a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:41:52 +0000 Subject: [PATCH 7/8] chore: update lock files for the version bumps Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_014t9fy7CGYG2vBLEfHwu12m --- packages/uipath-platform/uv.lock | 2 +- packages/uipath/uv.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/uipath-platform/uv.lock b/packages/uipath-platform/uv.lock index 249f0a23b..6e32115d0 100644 --- a/packages/uipath-platform/uv.lock +++ b/packages/uipath-platform/uv.lock @@ -1091,7 +1091,7 @@ dev = [ [[package]] name = "uipath-platform" -version = "0.3.22" +version = "0.3.23" source = { editable = "." } dependencies = [ { name = "anyio" }, diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index a1839c99e..9058b4ef2 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2720,7 +2720,7 @@ wheels = [ [[package]] name = "uipath" -version = "2.15.15" +version = "2.15.16" source = { editable = "." } dependencies = [ { name = "applicationinsights" }, @@ -2883,7 +2883,7 @@ wheels = [ [[package]] name = "uipath-platform" -version = "0.3.22" +version = "0.3.23" source = { editable = "../uipath-platform" } dependencies = [ { name = "anyio" }, From 9a1c8358aa48ddb0498bb66e15f2c2272b8d076b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:48:06 +0000 Subject: [PATCH 8/8] fix(cli): report debug and eval bindings regeneration through logging Inside the debug and eval execution loop the console stream is not the command's to write to: on Windows click refuses it with a bad file descriptor. Those two callers now report through logging, as they do for the rest of that path, and an error is raised for their own handler. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_014t9fy7CGYG2vBLEfHwu12m --- packages/uipath/src/uipath/_cli/cli_debug.py | 2 +- packages/uipath/src/uipath/_cli/cli_eval.py | 2 +- .../uipath/src/uipath/_cli/cli_resources.py | 31 +++++++++++++++++-- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/packages/uipath/src/uipath/_cli/cli_debug.py b/packages/uipath/src/uipath/_cli/cli_debug.py index b631cb64a..88f2b3f42 100644 --- a/packages/uipath/src/uipath/_cli/cli_debug.py +++ b/packages/uipath/src/uipath/_cli/cli_debug.py @@ -294,7 +294,7 @@ async def execute_debug_runtime(): # uipath_resources.py. from .cli_resources import regenerate_bindings - regenerate_bindings(os.getcwd()) + regenerate_bindings(os.getcwd(), via_logger=True) studio_client = StudioClient(project_id) async with ResourceOverwritesContext( diff --git a/packages/uipath/src/uipath/_cli/cli_eval.py b/packages/uipath/src/uipath/_cli/cli_eval.py index 56807e7ea..5c4b331a5 100644 --- a/packages/uipath/src/uipath/_cli/cli_eval.py +++ b/packages/uipath/src/uipath/_cli/cli_eval.py @@ -491,7 +491,7 @@ async def execute_eval(): # from uipath_resources.py. from .cli_resources import regenerate_bindings - regenerate_bindings(os.getcwd()) + regenerate_bindings(os.getcwd(), via_logger=True) studio_client = StudioClient(project_id) await stack.enter_async_context( diff --git a/packages/uipath/src/uipath/_cli/cli_resources.py b/packages/uipath/src/uipath/_cli/cli_resources.py index eaa456c3d..c9bc3d71c 100644 --- a/packages/uipath/src/uipath/_cli/cli_resources.py +++ b/packages/uipath/src/uipath/_cli/cli_resources.py @@ -10,6 +10,7 @@ """ import json +import logging from typing import Any import click @@ -21,6 +22,7 @@ from ._utils._context import CliContext console = ConsoleLogger() +logger = logging.getLogger(__name__) _KIND_CHOICES = list(RESOURCE_KINDS) _PROJECT_PATH_HELP = ( @@ -609,12 +611,20 @@ def generate_bindings(format: str | None, project_path: str | None) -> None: _report_sync(sync) -def regenerate_bindings(root: str) -> None: - """Regenerates ``bindings.json`` before a pack or a push, when the project declares resources. +def regenerate_bindings(root: str, *, via_logger: bool = False) -> None: + """Regenerates ``bindings.json`` before a pack, push, debug or eval, when the project declares resources. A project without ``uipath_resources.py`` keeps its ``bindings.json`` as it is. Errors in either file stop the command: a package built on stale bindings would deploy wrong. + + Args: + root: The project folder. + via_logger: Report through ``logging`` instead of the console. Debug + and eval call this inside their execution loop, where the console + stream is not theirs to write to (on Windows, click refuses it). + An error is then raised as a ``click.ClickException`` for the + command's own handler to report. """ from ._declarations._bindings import BindingsFileError, sync_bindings from ._declarations._parser import DeclarationsSyntaxError @@ -622,6 +632,21 @@ def regenerate_bindings(root: str) -> None: try: sync = sync_bindings(root) except (DeclarationsSyntaxError, BindingsFileError) as error: + if via_logger: + raise click.ClickException(str(error)) from error console.error(str(error)) - if sync is not None: + if sync is None: + return + if not via_logger: _report_sync(sync, quiet=not sync.changed) + return + for diagnostic in sync.diagnostics: + logger.warning(diagnostic) + if sync.changed: + logger.info( + "Updated %s from %s: %d declared, %d hand-written kept.", + sync.path, + sync.declarations_file, + sync.derived, + sync.kept, + )