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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions aws_lambda_builders/workflows/python_uv/packager.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from aws_lambda_builders.architecture import ARM64, X86_64

from .exceptions import LockFileError, MissingUvError, UvBuildError, UvInstallationError
from .utils import OSUtils, UvConfig
from .utils import OSUtils, UvConfig, normalize_package_name

LOG = logging.getLogger(__name__)

Expand Down Expand Up @@ -561,7 +561,7 @@ def _check_prune_names(lock_path: str, prune: List[str]) -> None:
return

locked = {package.get("name") for package in packages if isinstance(package, dict)}
missing = [name for name in prune if re.sub(r"[-_.]+", "-", name).lower() not in locked]
missing = [name for name in prune if normalize_package_name(name) not in locked]
if missing:
raise LockFileError(reason=f"Build option uv_prune names packages not in {lock_path}: {', '.join(missing)}")

Expand Down
6 changes: 6 additions & 0 deletions aws_lambda_builders/workflows/python_uv/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import logging
import os
import re
import shutil
import subprocess
from typing import List, Optional
Expand All @@ -15,6 +16,11 @@
EXPERIMENTAL_FLAG_BUILD_PERFORMANCE = "experimentalBuildPerformance"


def normalize_package_name(name: str) -> str:
"""PEP 503 normalized name, the form uv.lock stores package names in."""
return re.sub(r"[-_.]+", "-", name).lower()


class OSUtils(BaseOSUtils):
"""Extended OS utilities for UV workflow."""

Expand Down
24 changes: 23 additions & 1 deletion aws_lambda_builders/workflows/python_uv/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from aws_lambda_builders.workflow import BaseWorkflow, BuildDirectory, BuildInSourceSupport, Capability

from .actions import PythonUvBuildAction
from .utils import OSUtils, UvConfig, detect_uv_manifest
from .utils import OSUtils, UvConfig, detect_uv_manifest, normalize_package_name

LOG = logging.getLogger(__name__)

Expand Down Expand Up @@ -150,13 +150,35 @@ def _uv_config_from_options(self, manifest_path):
f"but this build uses {os.path.basename(manifest_path) if manifest_path else 'no manifest'}"
)

project_name = self._project_name(manifest_path)
if project_name and any(
normalize_package_name(name) == normalize_package_name(project_name) for name in values.get("uv_prune", [])
):
self._fail(f"Build option uv_prune cannot name the project being built ({project_name})")

return UvConfig(
groups=values.get("uv_groups"),
extras=values.get("uv_extras"),
all_extras=values.get("uv_all_extras", False),
prune=values.get("uv_prune"),
)

@staticmethod
def _project_name(pyproject_path):
"""[project].name of the function's own pyproject.toml, or None if it has none."""
try:
import tomllib
except ModuleNotFoundError: # Python 3.10
import tomli as tomllib

try:
with open(pyproject_path, "rb") as pyproject_file:
project = tomllib.load(pyproject_file).get("project")
except (OSError, ValueError): # Leave unreadable manifests to uv's own diagnostics
return None
name = project.get("name") if isinstance(project, dict) else None
return name if isinstance(name, str) else None

def _setup_build_actions(self, source_dir, artifacts_dir, scratch_dir, manifest_path, runtime, config=None):
"""
Set up the build actions based on configuration.
Expand Down
10 changes: 10 additions & 0 deletions tests/integration/workflows/python_uv/test_python_uv.py
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,16 @@ def test_workflow_prunes_runtime_provided_packages(self):
)
self.assertIn("uv_prune names packages not in", str(ctx.exception))

# uv would export nothing and the build would pass with no dependencies
with self.assertRaises(WorkflowFailedError) as ctx:
builder.build(
*build_args,
runtime=runtime,
experimental_flags=self.experimental_flags,
options={"uv_prune": ["PruneApp"]},
)
self.assertIn("uv_prune cannot name the project being built (pruneapp)", str(ctx.exception))

@skipIf(which("uv") is None, "uv not available")
def test_workflow_shows_uv_warnings(self):
with tempfile.TemporaryDirectory() as source_dir:
Expand Down
43 changes: 39 additions & 4 deletions tests/unit/workflows/python_uv/test_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,21 +219,56 @@ def _workflow(self, options, manifest=None, **kwargs):
**kwargs,
)

def test_options_are_passed_to_the_build_action(self):
@parameterized.expand(
[
("named_extras", {"uv_extras": ["fast"]}, ["fast"], False),
# uv_extras and uv_all_extras cannot be combined, so all_extras gets its own case
("all_extras", {"uv_all_extras": True}, [], True),
]
)
def test_options_are_passed_to_the_build_action(self, _, extras_options, extras, all_extras):
workflow = self._workflow(
{
"build_logical_id": "Fn",
"uv_groups": ["lambda"],
"uv_extras": ["fast"],
"uv_prune": ["boto3"],
**extras_options,
}
)
config = workflow.actions[0].config
self.assertEqual(config.groups, ["lambda"])
self.assertEqual(config.extras, ["fast"])
self.assertFalse(config.all_extras)
self.assertEqual(config.extras, extras)
self.assertEqual(config.all_extras, all_extras)
self.assertEqual(config.prune, ["boto3"])

@parameterized.expand(
[("app", "app"), ("app", "App"), ("my-app", "my_app"), ("My_App", "my.app"), ("my-app", "My--App")]
)
def test_prune_of_the_project_itself_fails(self, project_name, prune_name):
with open(self.pyproject, "w") as f:
f.write(f'[project]\nname = "{project_name}"\nversion = "0.1.0"\n')
with self.assertRaises(WorkflowFailedError) as ctx:
self._workflow({"uv_prune": ["boto3", prune_name]})
self.assertTrue(str(ctx.exception).startswith("PythonUvBuilder:Validation - "), str(ctx.exception))
self.assertIn("uv_prune cannot name the project being built", str(ctx.exception))

def test_prune_of_a_similar_name_is_allowed(self):
workflow = self._workflow({"uv_prune": ["app-core"]})
self.assertEqual(workflow.actions[0].config.prune, ["app-core"])

@parameterized.expand(
[
("[tool.uv.workspace]\nmembers = []\n",), # virtual workspace root, no [project]
("[project\n",), # unreadable; uv reports it
("[project]\nversion = 1\n",), # no name
]
)
def test_prune_without_a_project_name_is_left_to_uv(self, content):
with open(self.pyproject, "w") as f:
f.write(content)
workflow = self._workflow({"uv_prune": ["app"]})
self.assertEqual(workflow.actions[0].config.prune, ["app"])

def test_no_options_keep_defaults(self):
config = self._workflow(None).actions[0].config
self.assertEqual(config.to_export_args(), [])
Expand Down
Loading