Files
nanobot/nanobot/utils/delivery.py
Hua 9ac73f1e26
Some checks failed
Test Suite / test (3.11) (push) Failing after 1m24s
Test Suite / test (3.12) (push) Failing after 1m46s
Test Suite / test (3.13) (push) Failing after 2m1s
refactor(delivery): use workspace out as artifact root
2026-03-20 09:10:33 +08:00

63 lines
1.9 KiB
Python

"""Helpers for workspace-scoped delivery artifacts."""
from __future__ import annotations
from pathlib import Path
from urllib.parse import quote, urljoin
from loguru import logger
from nanobot.utils.helpers import detect_image_mime
def delivery_artifacts_root(workspace: Path) -> Path:
"""Return the workspace root used for generated delivery artifacts."""
return workspace.resolve(strict=False) / "out"
def is_image_file(path: Path) -> bool:
"""Return True when a local file looks like a supported image."""
try:
with path.open("rb") as f:
header = f.read(16)
except OSError:
return False
return detect_image_mime(header) is not None
def resolve_delivery_media(
media_path: str | Path,
workspace: Path,
media_base_url: str,
) -> tuple[Path | None, str | None, str | None]:
"""Resolve a local delivery artifact to a public URL under media_base_url."""
if not media_base_url:
return None, None, "local media publishing is not configured"
source = Path(media_path).expanduser()
try:
resolved = source.resolve(strict=True)
except FileNotFoundError:
return None, None, "local file not found"
except OSError as e:
logger.warning("Failed to resolve local delivery media path {}: {}", media_path, e)
return None, None, "local file unavailable"
if not resolved.is_file():
return None, None, "local file not found"
artifacts_root = delivery_artifacts_root(workspace)
try:
relative_path = resolved.relative_to(artifacts_root)
except ValueError:
return None, None, f"local delivery media must stay under {artifacts_root}"
if not is_image_file(resolved):
return None, None, "local delivery media must be an image"
media_url = urljoin(
f"{media_base_url.rstrip('/')}/",
quote(relative_path.as_posix(), safe="/"),
)
return resolved, media_url, None