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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/uipath/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "uipath"
version = "2.15.16"
version = "2.15.17"
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"
Expand Down
140 changes: 139 additions & 1 deletion packages/uipath/src/uipath/_cli/cli_new.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
import importlib.metadata
import json
import os
import re
import shutil
import tomllib
import uuid
from collections.abc import Iterator

Expand Down Expand Up @@ -34,7 +36,7 @@
template_path = os.path.join(
os.path.dirname(__file__), "_templates/main.py.template"
)
target_path = os.path.join(target_directory, "main.py")

Check failure on line 39 in packages/uipath/src/uipath/_cli/cli_new.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Define a constant instead of duplicating this literal "main.py" 4 times.

See more on https://sonarcloud.io/project/issues?id=UiPath_uipath-python&issues=AaJChq8PJfbagd_jvREG&open=AaJChq8PJfbagd_jvREG&pullRequest=2042

shutil.copyfile(template_path, target_path)

Expand All @@ -58,6 +60,122 @@
f.write(toml_content)


# What `uv init` writes, plus the `uv add uipath` of the quickstart. These hold
# nothing to lose, so a function scaffold may replace them without --force.
UV_STARTER_MAIN = re.compile(
r'def main\(\):\n print\("Hello from [^"\n]*!"\)\n\n\n'
r'if __name__ == "__main__":\n main\(\)\n?'
)
UV_STARTER_PROJECT_KEYS = {
"name",
"version",
"description",
"readme",
"requires-python",
"dependencies",
# uv 0.12 and later: the starter is a package built with uv_build.
"authors",
"scripts",
}
# name and requires-python come from the folder and --python, so they vary.
UV_STARTER_REQUIRES_PYTHON = re.compile(r">=\d+(\.\d+)*")
UV_STARTER_DEFAULTS = {
"version": "0.1.0",
"description": "Add your description here",
"readme": "README.md",
}
# What `uv add uipath` writes. An extra or a pin is the author's choice.
UIPATH_REQUIREMENT = re.compile(r"uipath(>=\d+(\.\d+)*)?")
UV_BUILD_REQUIREMENT = re.compile(r"uv_build>=[\d.]+,<[\d.]+")


def _read_text(path: str) -> str | None:
if os.path.islink(path) or not os.path.isfile(path):
return None
try:
with open(path, encoding="utf-8") as f:
return f.read()
except (OSError, UnicodeDecodeError):
return None


def _is_uv_starter(path: str) -> bool:
name = os.path.basename(path)
text = _read_text(path)
if text is None or name not in ("main.py", PYTHON_CONFIGURATION_FILE):
return False
if name == "main.py":
return UV_STARTER_MAIN.fullmatch(text) is not None
try:
data = tomllib.loads(text)
except tomllib.TOMLDecodeError:
return False
if not data:
return True
project = data.get("project")
if not set(data) <= {"project", "build-system"} or not isinstance(project, dict):
return False
script = project.get("name")
authors = project.get("authors", [])
dependencies = project.get("dependencies", [])
return (
set(project) <= UV_STARTER_PROJECT_KEYS
and all(project.get(k, v) == v for k, v in UV_STARTER_DEFAULTS.items())
and UV_STARTER_REQUIRES_PYTHON.fullmatch(
str(project.get("requires-python", ">=3"))
)
is not None
and isinstance(authors, list)
and all(_is_uv_author(a) for a in authors)
and isinstance(dependencies, list)
and all(
isinstance(d, str) and UIPATH_REQUIREMENT.fullmatch(d) for d in dependencies
)
and (
"scripts" not in project
or isinstance(script, str)
and project["scripts"] == {script: f"{re.sub('[-.]', '_', script)}:main"}
)
and _is_uv_build_system(data.get("build-system"))
)


def _is_uv_author(author: object) -> bool:
return (
isinstance(author, dict)
and set(author) <= {"name", "email"}
and all(isinstance(v, str) for v in author.values())
)


def _is_uv_build_system(build_system: object) -> bool:
if build_system is None:
return True
if not isinstance(build_system, dict) or set(build_system) != {
"requires",
"build-backend",
}:
return False
requires = build_system["requires"]
return (
build_system["build-backend"] == "uv_build"
and isinstance(requires, list)
and len(requires) == 1
and isinstance(requires[0], str)
and UV_BUILD_REQUIREMENT.fullmatch(requires[0]) is not None
)


def existing_project_files(directory: str) -> list[str]:
"""Files a function scaffold would overwrite that hold more than a uv starter."""
return [
f
for f in ("main.py", PYTHON_CONFIGURATION_FILE, UIPATH_CONFIG_FILE)
if os.path.lexists(path := os.path.join(directory, f))
and not _is_uv_starter(path)
]


def generate_uipath_json(target_directory):
uipath_json_path = os.path.join(target_directory, UIPATH_CONFIG_FILE)
project_id = resolve_existing_project_id(target_directory) or str(uuid.uuid4())
Expand Down Expand Up @@ -176,9 +294,21 @@
help="Directory to scaffold the project into, created when missing. "
"Defaults to the current directory.",
)
@click.option(
"--force",
is_flag=True,
default=False,
help="Overwrite main.py, pyproject.toml and uipath.json when they already exist. "
"The files `uv init` writes are replaced without it. Applies to function "
"projects; agent framework scaffolds decide for themselves.",
)
@track_command("new")
def new(
name: str, project_type: str, agent_framework: str | None, target_dir: str | None
name: str,
project_type: str,
agent_framework: str | None,
target_dir: str | None,
force: bool,
):
"""Generate a quick-start project."""
directory = os.path.abspath(target_dir) if target_dir else os.getcwd()
Expand Down Expand Up @@ -226,6 +356,14 @@
"function project."
)

existing = existing_project_files(directory)
if existing and not force:
Comment thread
rge-uipath marked this conversation as resolved.
Resolved
console.error(
f"Refusing to overwrite existing {', '.join(repr(f) for f in existing)} "
f"in {target_dir or 'the current directory'}. "
"Run `uipath new` in an empty folder, or pass --force to overwrite."
)

location = f"in '{target_dir}'" if target_dir else "in current directory"
with console.spinner(f"Creating new project {name} {location} ..."):
generate_script(directory)
Expand Down
194 changes: 191 additions & 3 deletions packages/uipath/tests/cli/test_new.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import cast
from unittest.mock import MagicMock, patch

import pytest
from click.testing import CliRunner
from packaging.specifiers import SpecifierSet
from packaging.version import Version
Expand All @@ -17,6 +18,47 @@
from uipath._cli.middlewares import MiddlewareResult
from uipath._cli.models.agent_frameworks import AgentFramework

# `uv init . --python 3.11` (uv 0.9.30 and 0.11.0) followed by `uv add uipath`.
UV_STARTER_PYPROJECT = """[project]
name = "my-function"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"uipath>=2.15.0",
]
"""
# `uv init . --python 3.11` (uv 0.13.4) followed by `uv add uipath`. It writes
# src/my_fn/__init__.py and no main.py.
UV_BUILD_STARTER_PYPROJECT = """[project]
name = "my-fn"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
authors = [
{ name = "Jane Doe", email = "jane.doe@example.com" }
]
requires-python = ">=3.11"
dependencies = [
"uipath",
]

[project.scripts]
my-fn = "my_fn:main"

[build-system]
requires = ["uv_build>=0.13.4,<0.14.0"]
build-backend = "uv_build"
"""
UV_STARTER_MAIN_PY = """def main():
print("Hello from my-function!")


if __name__ == "__main__":
main()
"""


def _framework(package: str) -> AgentFramework:
"""An installed agent framework whose scaffold claims the project."""
Expand Down Expand Up @@ -63,15 +105,161 @@ def test_new_project_without_name(self, runner: CliRunner, temp_dir: str) -> Non
def test_new_project_with_existing_files(
self, runner: CliRunner, temp_dir: str
) -> None:
"""Test creating a new project when files already exist."""
"""An existing project is refused and left untouched."""
with runner.isolated_filesystem(temp_dir=temp_dir):
# Create existing files
with open("main.py", "w") as f:
f.write("print('Existing file')")

result = runner.invoke(cli, ["new", "my_project"])
result = runner.invoke(cli, ["new", "my_project", "--type", "function"])
assert result.exit_code == 1
assert "Refusing to overwrite existing 'main.py'" in result.output
assert "--force" in result.output
with open("main.py") as f:
assert f.read() == "print('Existing file')"
assert not os.path.exists("pyproject.toml")
assert not os.path.exists("uipath.json")

def test_new_project_refuses_dangling_symlink(
self, runner: CliRunner, temp_dir: str
) -> None:
"""A dangling main.py symlink still counts as existing."""
with runner.isolated_filesystem(temp_dir=temp_dir):
try:
os.symlink("missing.py", "main.py")
except OSError:
pytest.skip("symlinks need privileges on this platform")

result = runner.invoke(cli, ["new", "my_project", "--type", "function"])
assert result.exit_code == 1
assert "Refusing to overwrite existing 'main.py'" in result.output
assert not os.path.exists("missing.py")

@pytest.mark.parametrize(
"pyproject", [UV_STARTER_PYPROJECT, UV_BUILD_STARTER_PYPROJECT]
)
@pytest.mark.parametrize("with_main", [True, False])
def test_new_project_replaces_uv_init_starter(
self, runner: CliRunner, temp_dir: str, with_main: bool, pyproject: str
) -> None:
"""The quickstart: `uv init` (main.py up to uv 0.11) then `uv add uipath`."""
with runner.isolated_filesystem(temp_dir=temp_dir):
with open("pyproject.toml", "w") as f:
f.write(pyproject)
if with_main:
with open("main.py", "w") as f:
f.write(UV_STARTER_MAIN_PY)

result = runner.invoke(cli, ["new", "my_project", "--type", "function"])
assert result.exit_code == 0, result.output
with open("main.py") as f:
assert f.read() != UV_STARTER_MAIN_PY
with open("pyproject.toml") as f:
assert 'name = "my_project"' in f.read()

@pytest.mark.parametrize(
"pyproject",
[
UV_STARTER_PYPROJECT.replace('"uipath>=2.15.0"', '"requests"'),
UV_STARTER_PYPROJECT + "\n[tool.ruff]\nline-length = 100\n",
UV_STARTER_PYPROJECT.replace("[project]", "[project]\nkeywords = []"),
UV_STARTER_PYPROJECT.replace("uipath>=2.15.0", "uipath[ipc]==2.14.0"),
UV_STARTER_PYPROJECT.replace("uipath>=2.15.0", "uipath==2.14.0"),
UV_STARTER_PYPROJECT.replace(">=3.11", ">=3.11,<3.13"),
UV_BUILD_STARTER_PYPROJECT.replace("my_fn:main", "my_fn.cli:run"),
UV_BUILD_STARTER_PYPROJECT + 'serve = "my_fn:serve"\n',
UV_BUILD_STARTER_PYPROJECT.replace("uv_build", "hatchling"),
UV_STARTER_PYPROJECT.replace('"0.1.0"', '"1.4.0"'),
UV_STARTER_PYPROJECT.replace("Add your description here", "Billing sync"),
UV_STARTER_PYPROJECT.replace('"README.md"', '"docs/intro.md"'),
"not toml [",
],
ids=[
"other-dependency",
"tool-config",
"extra-key",
"uipath-extra",
"uipath-pin",
"edited-requires-python",
"edited-script",
"edited-build-system",
"other-build-backend",
"edited-version",
"edited-description",
"edited-readme",
"invalid",
],
)
def test_new_project_refuses_configured_pyproject(
self, runner: CliRunner, temp_dir: str, pyproject: str
) -> None:
"""A pyproject.toml with more than a uv starter is kept."""
with runner.isolated_filesystem(temp_dir=temp_dir):
with open("pyproject.toml", "w") as f:
f.write(pyproject)

result = runner.invoke(cli, ["new", "my_project", "--type", "function"])
assert result.exit_code == 1
assert "Refusing to overwrite existing 'pyproject.toml'" in result.output
with open("pyproject.toml") as f:
assert f.read() == pyproject
assert not os.path.exists("main.py")

def test_new_project_refuses_edited_uv_main(
self, runner: CliRunner, temp_dir: str
) -> None:
"""An edited uv main.py is the author's code, so it is kept."""
with runner.isolated_filesystem(temp_dir=temp_dir):
edited = UV_STARTER_MAIN_PY.replace("main()\n", "main()\n run()\n")
with open("main.py", "w") as f:
f.write(edited)

result = runner.invoke(cli, ["new", "my_project", "--type", "function"])
assert result.exit_code == 1
assert "Refusing to overwrite existing 'main.py'" in result.output
with open("main.py") as f:
assert f.read() == edited

def test_new_project_refuses_empty_uipath_json(
self, runner: CliRunner, temp_dir: str
) -> None:
"""uv never writes uipath.json, so any uipath.json is kept."""
with runner.isolated_filesystem(temp_dir=temp_dir):
open("uipath.json", "w").close()

result = runner.invoke(cli, ["new", "my_project", "--type", "function"])
assert result.exit_code == 1
assert "Refusing to overwrite existing 'uipath.json'" in result.output

def test_new_project_with_existing_files_force_overwrites(
self, runner: CliRunner, temp_dir: str
) -> None:
"""--force keeps the in-place overwrite, pyproject.toml included."""
with runner.isolated_filesystem(temp_dir=temp_dir):
with open("main.py", "w") as f:
f.write("print('Existing file')")
with open("pyproject.toml", "w") as f:
f.write("[tool.ruff]\nline-length = 100\n")

result = runner.invoke(
cli, ["new", "my_project", "--type", "function", "--force"]
)
assert result.exit_code == 0
assert "Created 'main.py' file." in result.output
with open("pyproject.toml") as f:
assert 'name = "my_project"' in f.read()
assert os.path.exists("uipath.json")

def test_new_project_force_overwrites_uipath_json(
self, runner: CliRunner, temp_dir: str
) -> None:
with runner.isolated_filesystem(temp_dir=temp_dir):
open("uipath.json", "w").close()

result = runner.invoke(
cli, ["new", "my_project", "--type", "function", "--force"]
)
assert result.exit_code == 0, result.output
assert os.path.getsize("uipath.json") > 0

def test_new_dir_scaffolds_into_that_directory(
self, runner: CliRunner, temp_dir: str
Expand Down
Loading
Loading