diff --git a/CHANGELOG.md b/CHANGELOG.md index 66ffbab..0b74df3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] ### Added +- `planecli attachment get` (aliases `download`, `dl`) downloads work item attachments: `get ISSUE [SELECTOR] [--all] [--dir DIR | -o FILE] [--force] [--json]`. SELECTOR is an attachment id or exact file name; a name shared by several attachments needs an id or `--all`, which saves every match with repeated names suffixed (`image-2.png`). Files stream to disk through the presigned storage redirect, and existing files are not overwritten without `--force` - `planecli intake` command group: `ls`, `create`, `accept`, `decline`, `delete`, `enabled` for project intake queues. Mutations take the work item UUID shown in the `Issue ID` column of `intake ls`. `accept`/`decline` require the project Admin role (the API silently ignores the change for lower roles, so the CLI verifies it and fails loudly). `delete` also permanently deletes the underlying work item for any status other than `accepted` ## [0.5.1] - 2026-07-03 diff --git a/README.md b/README.md index f9532cb..bc764f6 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ The main differentiator is **intelligent fuzzy search**: reference any resource - **Documents**: Create, read, update, and delete project documents - **Intake**: Manage a project's intake queue — list, create, triage (accept/decline), and delete items - **Comments**: Add, update, and delete comments on work items +- **Attachments**: Upload, list, and download work item file attachments - **Users**: List workspace members and identify the authenticated user - **Fuzzy Search**: Intelligent resource resolution — `--project "Front"` finds "Frontend" - **Dual Output**: Rich tables (default) or JSON with `--json` for scripting @@ -261,6 +262,24 @@ planecli comment update --issue ABC-123 --body "Updated comment" planecli comment delete --issue ABC-123 ``` +### Attachments + +```bash +# List a work item's attachments +planecli attachment ls ABC-123 + +# Upload a file (asks before adding a second file with the same name; --force skips the check) +planecli attachment attach ABC-123 -f ./screenshot.png + +# Download: the only attachment, one by id or exact file name, or all of them +planecli attachment get ABC-123 +planecli attachment get ABC-123 3f2a9c1e-... # by id +planecli attachment get ABC-123 report.pdf -o ~/report.pdf +planecli attachment get ABC-123 --all -d ./downloads # repeated names saved as name-2.ext, ... +``` + +A file name shared by several attachments (pasted screenshots are all `image.png`) needs an id, or `--all` to save every match. Existing files in `--dir` are never overwritten unless `--force` is given; `--json` prints the saved paths. + ### Users ```bash @@ -288,6 +307,7 @@ planecli --no-cache wi ls -p "Frontend" | `planecli work-item` | `wi`, `issues`, `issue` | | `planecli project` | `projects` | | `planecli comment` | `comments` | +| `planecli attachment` | `attachments` | | `planecli document` | `documents`, `doc`, `docs` | | `planecli users` | `user` | | `planecli module` | `modules` | diff --git a/skills/SKILL.md b/skills/SKILL.md index 6087ab3..8548e04 100644 --- a/skills/SKILL.md +++ b/skills/SKILL.md @@ -123,6 +123,10 @@ planecli doc create --title "Spec" --content "## Details..." -p "Project" --json # Comments planecli comment ls ABC-123 --json planecli comment create ABC-123 --body "Fixed in PR #456" --json + +# Attachments (get saves to disk; a shared name like image.png needs an id or --all) +planecli attachment ls ABC-123 --json +planecli attachment get ABC-123 --all -d ./downloads --json ``` ## Gotchas diff --git a/skills/references/command-reference.md b/skills/references/command-reference.md index 1ad46ee..6508259 100644 --- a/skills/references/command-reference.md +++ b/skills/references/command-reference.md @@ -10,6 +10,7 @@ - [States](#states) - [Documents](#documents) - [Comments](#comments) +- [Attachments](#attachments) - [Intake](#intake) - [Users](#users) - [Cache](#cache) @@ -34,6 +35,7 @@ Environment variable `PLANECLI_NO_CACHE=1` disables cache globally. | `project` | `projects` | | `document` | `doc`, `docs`, `documents` | | `comment` | `comments` | +| `attachment` | `attachments` | | `module` | `modules` | | `label` | `labels` | | `state` | `states` | @@ -294,6 +296,25 @@ oldest → newest — not the first N chronologically. A limit of `0` or a negat value returns no comments (consistent with the `[:limit]` semantics used elsewhere, where `0` means "none"). +## Attachments + +Command group: `planecli attachment` (alias: `attachments`) + +``` +planecli attachment ls ISSUE [--project/-p PROJECT] +planecli attachment attach ISSUE -f FILE [--force] [--project/-p PROJECT] +planecli attachment get ISSUE [SELECTOR] [--all] [--dir/-d DIR | --output/-o FILE] [--force] [--project/-p PROJECT] +``` + +`get` (aliases `download`, `dl`) saves files to disk and never prints their content. +SELECTOR is an attachment id or exact file name; it may be omitted when the work item +has one attachment or `--all` is given. A name shared by several attachments +(screenshots are all `image.png`) fails with the list of ids unless `--all` is given, +which saves every match as `image.png`, `image-2.png`, ... Existing files in `--dir` +(default: the current directory) are sidestepped the same way unless `--force`; +`-o` saves exactly one attachment and overwrites. `--json` prints +`[{id, name, type, size, path}]` with absolute paths. + ## Intake Command group: `planecli intake` (no alias) diff --git a/src/planecli/app.py b/src/planecli/app.py index d6d2216..7f88007 100644 --- a/src/planecli/app.py +++ b/src/planecli/app.py @@ -18,6 +18,7 @@ ) # Import and register sub-apps +from planecli.commands.attachments import attachment_app # noqa: E402 from planecli.commands.cache_cmd import cache_app # noqa: E402 from planecli.commands.comments import comment_app # noqa: E402 from planecli.commands.cycles import cycle_app # noqa: E402 @@ -32,6 +33,7 @@ app.command(project_app) app.command(wi_app) +app.command(attachment_app) app.command(comment_app) app.command(doc_app) app.command(intake_app) diff --git a/src/planecli/commands/attachments.py b/src/planecli/commands/attachments.py new file mode 100644 index 0000000..282ee63 --- /dev/null +++ b/src/planecli/commands/attachments.py @@ -0,0 +1,578 @@ +"""Work item attachment commands (upload, list, download).""" + +from __future__ import annotations + +import mimetypes +import os +from pathlib import Path +from typing import Annotated + +import cyclopts +from cyclopts import Parameter +from plane.errors import PlaneError + +from planecli.api.async_sdk import run_sdk +from planecli.api.client import get_client, get_workspace, handle_api_error +from planecli.exceptions import APIError, ValidationError +from planecli.formatters import output, output_single +from planecli.utils.resolve import ( + resolve_work_item_across_projects_async, + resolve_work_item_async, +) + +attachment_app = cyclopts.App( + name=["attachment", "attachments"], + help="Manage work item file attachments.", +) + +ATTACHMENT_COLUMNS = [ + ("id", "ID"), + ("name", "Name"), + ("type", "Type"), + ("size", "Size"), + ("is_uploaded", "Uploaded"), + ("created_at", "Created"), +] + + +def _enrich_attachment(data: dict) -> dict: + """Flatten the nested `attributes` dict into top-level display fields. + + The attachment API stores the original filename/MIME under `attributes` + and the byte count at the top level; flatten both so formatters and + `--json` consumers see one consistent shape. + """ + attrs = data.get("attributes") or {} + data["name"] = attrs.get("name", "") + data["type"] = attrs.get("type", "") + data["size"] = data.get("size") if data.get("size") is not None else attrs.get("size") + return data + + +_EXTRA_MIME = {".md": "text/markdown", ".markdown": "text/markdown", ".log": "text/plain"} + + +def _guess_mime(filename: str) -> str: + """Guess a MIME type, defaulting to application/octet-stream.""" + mime, _ = mimetypes.guess_type(filename) + # The platform MIME database is not the same everywhere (macOS lacks .md). + return mime or _EXTRA_MIME.get(Path(filename).suffix.lower(), "application/octet-stream") + + +async def _resolve_item(issue: str, project: str | None): + """Resolve a work item to (item_dict, project_id), with or without -p.""" + client = get_client() + workspace = get_workspace() + if project: + from planecli.utils.resolve import resolve_project_async + + proj = await resolve_project_async(project, client, workspace) + project_id = proj["id"] + item = await resolve_work_item_async(issue, client, workspace, project_id) + else: + item, project_id = await resolve_work_item_across_projects_async( + issue, client, workspace + ) + return item, project_id + + +def embed_html(asset_id: str) -> str: + """Build an paragraph embedding an uploaded asset into a description. + + The editor's image node stores the asset UUID in src — not a URL. The web + app resolves it at render time (getEditorAssetSrc); a full path here is + mistaken for an asset id and the image fails to load. + """ + return f'

' + + +def _app_post_json(url: str, api_key: str, payload: dict): + """POST JSON to a session-only app endpoint, authenticating with an API token.""" + import requests + + return requests.post( + url, + headers={"X-Api-Key": api_key, "Content-Type": "application/json"}, + json=payload, + timeout=60, + ) + + +def _app_patch_json(url: str, api_key: str, payload: dict | None = None): + import requests + + return requests.patch( + url, + headers={"X-Api-Key": api_key, "Content-Type": "application/json"}, + json=payload or {}, + timeout=60, + ) + + +def _app_get(url: str, api_key: str): + import requests + + return requests.get(url, headers={"X-Api-Key": api_key}, timeout=60) + + +async def upload_embed_image( + client, workspace: str, project_id: str, item_id: str, path: str, force: bool = False +) -> str: + """Upload an image for description embedding; return the asset UUID. + + Prefers the native app asset endpoint (entity_type=ISSUE_DESCRIPTION — the + image renders inline and does not clutter the attachment list). Servers + whose app endpoints are session-only answer 401/403/404, in which case we + fall back to a v1 ISSUE_ATTACHMENT upload (see PLANE-4 for the server-side + fix that removes the need for the fallback). + """ + from planecli.api.client import get_config + + cfg = get_config() + path = os.path.expanduser(path) + if not os.path.isfile(path): + raise ValidationError(f"File not found: {path}") + name = os.path.basename(path) + size = os.path.getsize(path) + mime = _guess_mime(name) + + v2_url = f"{cfg.base_url}/api/assets/v2/workspaces/{workspace}/projects/{project_id}/" + # NOTE: raw requests + X-Api-Key, same pattern as documents.py — the SDK + # only covers /api/v1/ endpoints (see ADR-0003). + resp = await run_sdk( + _app_post_json, + v2_url, + cfg.api_key, + { + "name": name, + "type": mime, + "size": size, + "entity_type": "ISSUE_DESCRIPTION", + "entity_identifier": item_id, + }, + ) + if resp.status_code in (401, 403, 404): + att = await upload_attachment( + client, workspace, project_id, item_id, path, force=force + ) + return att["id"] + if resp.status_code != 200: + raise APIError(f"Asset upload failed: HTTP {resp.status_code}") + + created = resp.json() + upload = created["upload_data"] + import requests + + with open(path, "rb") as fh: + up = await run_sdk( + requests.post, + upload["url"], + data=upload["fields"], + files={"file": (name, fh, mime)}, + ) + if up.status_code not in (200, 201, 204): + raise APIError(f"File upload failed: HTTP {up.status_code}") + + asset_id = created["asset_id"] + mark = await run_sdk( + _app_patch_json, f"{v2_url}{asset_id}/", cfg.api_key, {"is_uploaded": True} + ) + if mark.status_code not in (200, 204): + raise APIError(f"Asset confirm failed: HTTP {mark.status_code}") + + # Read back through the v1 generic-asset endpoint (workspace-scoped, works + # for any entity type) — a 2xx on the PATCH is not proof of the write + # (see ADR-0007). + check = await run_sdk( + _app_get, + f"{cfg.base_url}/api/v1/workspaces/{workspace}/assets/{asset_id}/", + cfg.api_key, + ) + if check.status_code != 200: + raise APIError("Image asset was not confirmed by the server after upload.") + return asset_id + + +def _confirm_duplicate(name: str, existing: list[dict]) -> bool: + """Ask before uploading a file whose name is already attached. + + Interactive (TTY): prompt y/N. Non-interactive: refuse — scripts must + pass --force explicitly. + """ + import sys + + if not sys.stdin.isatty(): + return False + try: + answer = input( + f"An attachment named '{name}' already exists " + f"({len(existing)}x). Upload anyway? [y/N] " + ) + except EOFError: + return False + return answer.strip().lower() in ("y", "yes") + + +async def upload_attachment( + client, workspace: str, project_id: str, item_id: str, path: str, force: bool = False +) -> dict: + """Upload a file to a work item (dup-check -> register -> push -> mark -> verify). + + Returns the raw attachment dict with is_uploaded=True. Raises + ValidationError if the file does not exist (or the upload is cancelled at + the duplicate-name prompt), APIError if the server does not confirm the + upload (see ADR-0007). + """ + path = os.path.expanduser(path) + if not os.path.isfile(path): + raise ValidationError(f"File not found: {path}") + name = os.path.basename(path) + size = os.path.getsize(path) + endpoint = f"{workspace}/projects/{project_id}/work-items/{item_id}/attachments" + + # Guard against duplicate uploads: same-named attachments are easy to + # create by accident and hard to tell apart in the web UI (deleting the + # wrong one breaks embedded images). Confirm before adding another. + listed = await run_sdk(client.work_items.attachments._get, endpoint) + items = listed if isinstance(listed, list) else listed.get("results", []) + existing = [ + a + for a in items + if not a.get("is_deleted") and (a.get("attributes") or {}).get("name") == name + ] + if existing and not force and not _confirm_duplicate(name, existing): + raise ValidationError( + f"Upload cancelled: '{name}' is already attached " + f"({len(existing)}x). Re-run with --force to upload anyway." + ) + + mime = _guess_mime(name) + + # Three-step upload, mirroring what the Plane web app does: + # NOTE: the SDK's typed attachment methods drop `upload_data` (the + # presigned form), so the raw resource methods are used throughout — + # same escape hatch as the resolvers (see ADR-0003). + # 1. Register the attachment -> get a presigned upload target. + created = await run_sdk( + client.work_items.attachments._post, + endpoint, + {"name": name, "type": mime, "size": size}, + ) + asset_id = created["asset_id"] + upload = created["upload_data"] + + # 2. Push the bytes to the presigned URL. The signature lives in the + # form fields — no X-Api-Key header here. + import requests + + with open(path, "rb") as fh: + resp = await run_sdk( + requests.post, + upload["url"], + data=upload["fields"], + files={"file": (name, fh, mime)}, + ) + if resp.status_code not in (200, 201, 204): + raise APIError(f"File upload failed: HTTP {resp.status_code}") + + # 3. Mark the attachment uploaded, then read it back — a 2xx on the + # PATCH is not proof the write landed (see ADR-0007). + await run_sdk( + client.work_items.attachments._patch, + f"{endpoint}/{asset_id}", + {"is_uploaded": True}, + ) + listed = await run_sdk(client.work_items.attachments._get, endpoint) + items = listed if isinstance(listed, list) else listed.get("results", []) + mine = next((a for a in items if a.get("id") == asset_id), None) + if not mine or not mine.get("is_uploaded"): + raise APIError("Attachment was not confirmed by the server after upload.") + return mine + + +@attachment_app.command(alias=["upload", "new"]) +async def attach( + issue: str, + file: Annotated[str, Parameter(alias="-f")], + *, + project: Annotated[str | None, Parameter(alias="-p")] = None, + force: bool = False, + json: bool = False, +) -> None: + """Upload a file attachment to a work item. + + Parameters + ---------- + issue + Work item identifier (ABC-123) or UUID. + file + Path to the file to upload. + project + Project name/ID (required for name-based lookup). + force + Upload even if an attachment with the same file name already exists. + """ + from planecli.formatters import console + + # Fail on a bad path before touching the config or the network. + if not os.path.isfile(file): + raise ValidationError(f"File not found: {file}") + try: + item, project_id = await _resolve_item(issue, project) + client = get_client() + workspace = get_workspace() + mine = await upload_attachment( + client, workspace, project_id, item["id"], file, force=force + ) + except PlaneError as e: + raise handle_api_error(e) + + data = _enrich_attachment(mine) + if json: + output_single(data, [], as_json=True) + else: + console.print( + f"[green]Attached {data['name']} ({data['size']} bytes) to {issue}.[/]" + ) + + +@attachment_app.command(name="list", alias="ls") +async def list_( + issue: str, + *, + project: Annotated[str | None, Parameter(alias="-p")] = None, + json: bool = False, +) -> None: + """List attachments on a work item. + + Parameters + ---------- + issue + Work item identifier (ABC-123) or UUID. + project + Project name/ID (required for name-based lookup). + """ + try: + item, project_id = await _resolve_item(issue, project) + client = get_client() + workspace = get_workspace() + endpoint = ( + f"{workspace}/projects/{project_id}/work-items/{item['id']}/attachments" + ) + listed = await run_sdk(client.work_items.attachments._get, endpoint) + except PlaneError as e: + raise handle_api_error(e) + + items = listed if isinstance(listed, list) else listed.get("results", []) + data = [_enrich_attachment(a) for a in items] + output(data, ATTACHMENT_COLUMNS, title=f"Attachments on {issue}", as_json=json) + + +DOWNLOAD_COLUMNS = [ + ("id", "ID"), + ("name", "Name"), + ("size", "Size"), + ("path", "Saved To"), +] + + +def _describe(attachments: list[dict]) -> str: + """One line per attachment ('id name') for error messages.""" + return "\n".join(f" {a['id']} {a['name']}" for a in attachments) + + +def _select_attachments( + attachments: list[dict], selector: str | None, all_: bool +) -> list[dict]: + """Pick the attachments to download. + + SELECTOR matches an attachment id or its exact file name. Several + attachments may share a name (pasted screenshots are all "image.png"), + so a name that matches more than one is ambiguous unless --all is given. + Without a SELECTOR, --all takes everything and a lone attachment is + taken as-is. + """ + if selector is not None: + by_id = [a for a in attachments if a.get("id") == selector] + if by_id: + return by_id + by_name = [a for a in attachments if a["name"] == selector] + if not by_name: + raise ValidationError( + f"No attachment matches '{selector}'.", + hint="Available attachments:\n" + _describe(attachments) + if attachments + else "The work item has no attachments.", + ) + if len(by_name) > 1 and not all_: + raise ValidationError( + f"{len(by_name)} attachments are named '{selector}'.", + hint="Pass one id, or --all to save them all:\n" + _describe(by_name), + ) + return by_name + + if not attachments: + raise ValidationError("The work item has no attachments.") + if all_ or len(attachments) == 1: + return attachments + raise ValidationError( + f"The work item has {len(attachments)} attachments; choose one.", + hint="Pass an id or file name, or --all to save them all:\n" + + _describe(attachments), + ) + + +def _safe_filename(name: str, fallback: str) -> str: + """Reduce an attachment name to a bare file name (no directories).""" + base = os.path.basename(name.replace("\\", "/")).strip() + return base if base not in ("", ".", "..") else fallback + + +def _plan_paths(selected: list[dict], directory: Path, overwrite: bool) -> list[Path]: + """Choose a target path per attachment, suffixing duplicate names. + + Names repeated within the batch become name-2.ext, name-3.ext, ...; an + existing file on disk is sidestepped the same way unless overwrite is set. + """ + taken: set[Path] = set() + paths: list[Path] = [] + for att in selected: + name = _safe_filename(att["name"], att["id"]) + stem, suffix = os.path.splitext(name) + candidate = directory / name + n = 1 + while candidate in taken or (not overwrite and candidate.exists()): + n += 1 + candidate = directory / f"{stem}-{n}{suffix}" + taken.add(candidate) + paths.append(candidate) + return paths + + +def _download_attachment(url: str, api_key: str, dest: Path) -> int: + """Stream one attachment to dest; return the bytes written. + + The detail endpoint answers with a redirect to a presigned storage URL. + The redirect is followed by hand so the API key is not sent to the + storage host — the signature lives in the URL. Bytes go to a .part file + that is renamed on success, so a failed download leaves no partial file. + """ + from urllib.parse import urljoin + + import requests + + resp = requests.get( + url, headers={"X-Api-Key": api_key}, allow_redirects=False, stream=True, timeout=60 + ) + if resp.is_redirect: + location = urljoin(url, resp.headers["Location"]) + resp.close() + resp = requests.get(location, stream=True, timeout=60) + if resp.status_code == 401: + from planecli.exceptions import AuthenticationError + + raise AuthenticationError() + if resp.status_code != 200: + raise APIError(f"Download failed: HTTP {resp.status_code}", status_code=resp.status_code) + + part = dest.with_name(dest.name + ".part") + written = 0 + try: + with resp, open(part, "wb") as fh: + for chunk in resp.iter_content(chunk_size=64 * 1024): + fh.write(chunk) + written += len(chunk) + part.replace(dest) + except BaseException: + part.unlink(missing_ok=True) + raise + return written + + +@attachment_app.command(name="get", alias=["download", "dl"]) +async def get( + issue: str, + selector: str | None = None, + *, + all_: Annotated[bool, Parameter(name="--all")] = False, + dir: Annotated[str | None, Parameter(alias="-d")] = None, + output_file: Annotated[str | None, Parameter(name=["--output", "-o"])] = None, + force: bool = False, + project: Annotated[str | None, Parameter(alias="-p")] = None, + json: bool = False, +) -> None: + """Download work item attachments to disk. + + Parameters + ---------- + issue + Work item identifier (ABC-123) or UUID. + selector + Attachment id or exact file name. Optional when the work item has a + single attachment or --all is given. + all_ + Download every attachment (or every one named SELECTOR). Repeated + file names are saved as name-2.ext, name-3.ext, ... + dir + Directory to save into (default: the current directory). + output_file + File path to save a single attachment to (overwrites). + force + Overwrite existing files in --dir instead of adding a numeric suffix. + project + Project name/ID (required for name-based lookup). + """ + from planecli.api.client import get_config + + if output_file is not None and dir is not None: + raise ValidationError("Use either --output or --dir, not both.") + directory = Path(os.path.expanduser(dir)) if dir is not None else Path.cwd() + if not directory.is_dir(): + raise ValidationError(f"Directory not found: {directory}") + + try: + item, project_id = await _resolve_item(issue, project) + client = get_client() + workspace = get_workspace() + endpoint = ( + f"{workspace}/projects/{project_id}/work-items/{item['id']}/attachments" + ) + listed = await run_sdk(client.work_items.attachments._get, endpoint) + except PlaneError as e: + raise handle_api_error(e) + + items = listed if isinstance(listed, list) else listed.get("results", []) + attachments = [_enrich_attachment(a) for a in items if not a.get("is_deleted")] + selected = _select_attachments(attachments, selector, all_) + + if output_file is not None: + if len(selected) > 1: + raise ValidationError( + f"--output takes a single attachment, but {len(selected)} were selected.", + hint="Use --dir to save several files.", + ) + paths = [Path(os.path.expanduser(output_file))] + else: + paths = _plan_paths(selected, directory, overwrite=force) + + # NOTE: raw requests + X-Api-Key, same pattern as documents.py — the SDK + # has no download method, and its session would carry the API key across + # the storage redirect (see ADR-0003). + cfg = get_config() + base = f"{cfg.base_url}/api/v1/workspaces/{endpoint}" + saved = [] + for att, path in zip(selected, paths): + written = await run_sdk( + _download_attachment, f"{base}/{att['id']}/", cfg.api_key, path + ) + saved.append( + { + "id": att["id"], + "name": att["name"], + "type": att["type"], + "size": written, + "path": str(path.resolve()), + } + ) + + output(saved, DOWNLOAD_COLUMNS, title=f"Downloaded from {issue}", as_json=json) diff --git a/src/planecli/commands/comments.py b/src/planecli/commands/comments.py index 606ca76..095da70 100644 --- a/src/planecli/commands/comments.py +++ b/src/planecli/commands/comments.py @@ -2,6 +2,8 @@ from __future__ import annotations +import html +import re from typing import Annotated import cyclopts @@ -30,6 +32,86 @@ ] +_URL_RE = re.compile(r"(?=])(https?://[A-Za-z0-9\-._~:/?#\[\]@!$&()*+,;=%]+)") +# Trailing punctuation that belongs to the sentence, not the URL. +_URL_TRAIL = ".,;:!?)]}。,;:!?)】、" + + +def _linkify(text: str) -> str: + """Turn bare http(s) URLs into anchors. + + The API stores comment HTML verbatim and does not auto-link URLs — only + the web editor does — so links posted via the CLI would render as plain + text. URLs already inside an href attribute are left alone. + """ + + def _sub(m: re.Match[str]) -> str: + url = m.group(1).rstrip(_URL_TRAIL) + trail = m.group(1)[len(url) :] + return f'{url}{trail}' + + return _URL_RE.sub(_sub, text) + + +def _inline_code(text: str) -> str: + """Convert `inline code` to a code tag with HTML-escaped content.""" + return re.sub( + r"`([^`\n]+)`", + lambda m: f"{html.escape(m.group(1))}", + text, + ) + + +def _extract_code_blocks(text: str) -> tuple[str, list[str]]: + """Pull fenced code blocks out of the text, replacing each with a token. + + Returns the text with \x00N\x00 placeholders and the list of HTML + fragments (pre-wrapped escaped code) to restore at the end. Extracting + first keeps their content out of linkify and the newline-to-br pass. + """ + blocks: list[str] = [] + + def _hold(match: re.Match[str]) -> str: + code = html.escape(match.group(1).strip("\n")) + blocks.append(f"
{code}
") + return f"\x00{len(blocks) - 1}\x00" + + text = re.sub( + r"```[ \t]*\w*[ \t]*\n(.*?)```", + _hold, + text, + flags=re.DOTALL, + ) + return text, blocks + + +def _body_to_html(body: str) -> str: + """Convert plain comment text to HTML paragraphs. + + Blank lines separate paragraphs; a single newline becomes a br tag — + the editor collapses whitespace inside a paragraph, so unconverted + newlines would render as one long line. Backticks become code tags and + fenced blocks become pre-wrapped code (the editor stores HTML, it does + not parse markdown). + """ + text, blocks = _extract_code_blocks(body.strip()) + parts: list[str] = [] + for p in re.split(r"\n\s*\n", text): + p = p.strip() + if not p: + continue + converted = _linkify(_inline_code(p)).replace(chr(10), "
") + if re.fullmatch(r"(?:\x00\d+\x00[ \t]*)+", p): + # A paragraph that is only a code block keeps its pre wrapper. + parts.append(converted) + else: + parts.append(f"

{converted}

") + result = "".join(parts) + for i, fragment in enumerate(blocks): + result = result.replace(f"\x00{i}\x00", fragment) + return result + + def _enrich_comment(data: dict, members_map: dict[str, str] | None = None) -> dict: """Add convenience fields to a comment dict. @@ -48,6 +130,7 @@ def _enrich_comment(data: dict, members_map: dict[str, str] | None = None) -> di body_html = data.get("comment_html") or "" if body_html: import re + data["body_text"] = re.sub(r"<[^>]+>", "", body_html).strip() else: data["body_text"] = "" @@ -55,9 +138,7 @@ def _enrich_comment(data: dict, members_map: dict[str, str] | None = None) -> di return data -async def fetch_issue_comments( - workspace: str, project_id: str, item_id: str -) -> list[dict]: +async def fetch_issue_comments(workspace: str, project_id: str, item_id: str) -> list[dict]: """Fetch, enrich, and chronologically sort all comments for a work item. Single source of truth shared by `comment ls` and `wi show`. Resolves the @@ -111,6 +192,7 @@ async def list_( if project: from planecli.utils.resolve import resolve_project_async + proj = await resolve_project_async(project, client, workspace) project_id = proj["id"] item = await resolve_work_item_async(issue, client, workspace, project_id) @@ -159,6 +241,7 @@ async def create( if project: from planecli.utils.resolve import resolve_project_async + proj = await resolve_project_async(project, client, workspace) project_id = proj["id"] item = await resolve_work_item_async(issue, client, workspace, project_id) @@ -169,13 +252,17 @@ async def create( item_id = item["id"] - comment_data = CreateWorkItemComment(comment_html=f"

{body}

") + comment_data = CreateWorkItemComment(comment_html=_body_to_html(body)) comment = await run_sdk( client.work_items.comments.create, - workspace, project_id, item_id, comment_data, + workspace, + project_id, + item_id, + comment_data, ) data = _enrich_comment(comment.model_dump()) from planecli.cache import invalidate_resource + await invalidate_resource("comments", workspace, project_id, item_id) except PlaneError as e: raise handle_api_error(e) @@ -184,6 +271,7 @@ async def create( output_single(data, [], as_json=True) else: from planecli.formatters import console + console.print(f"[green]Comment added to {issue}.[/]") @@ -217,6 +305,7 @@ async def update( if project: from planecli.utils.resolve import resolve_project_async + proj = await resolve_project_async(project, client, workspace) project_id = proj["id"] item = await resolve_work_item_async(issue, client, workspace, project_id) @@ -227,13 +316,18 @@ async def update( item_id = item["id"] - update_data = UpdateWorkItemComment(comment_html=f"

{body}

") + update_data = UpdateWorkItemComment(comment_html=_body_to_html(body)) comment = await run_sdk( client.work_items.comments.update, - workspace, project_id, item_id, comment_id, update_data, + workspace, + project_id, + item_id, + comment_id, + update_data, ) data = _enrich_comment(comment.model_dump()) from planecli.cache import invalidate_resource + await invalidate_resource("comments", workspace, project_id, item_id) except PlaneError as e: raise handle_api_error(e) @@ -242,6 +336,7 @@ async def update( output_single(data, [], as_json=True) else: from planecli.formatters import console + console.print(f"[green]Comment updated on {issue}.[/]") @@ -271,6 +366,7 @@ async def delete( if project: from planecli.utils.resolve import resolve_project_async + proj = await resolve_project_async(project, client, workspace) project_id = proj["id"] item = await resolve_work_item_async(issue, client, workspace, project_id) @@ -282,9 +378,13 @@ async def delete( item_id = item["id"] await run_sdk( client.work_items.comments.delete, - workspace, project_id, item_id, comment_id, + workspace, + project_id, + item_id, + comment_id, ) from planecli.cache import invalidate_resource + await invalidate_resource("comments", workspace, project_id, item_id) except PlaneError as e: raise handle_api_error(e) diff --git a/src/planecli/commands/work_items.py b/src/planecli/commands/work_items.py index 8030118..a98c3c5 100644 --- a/src/planecli/commands/work_items.py +++ b/src/planecli/commands/work_items.py @@ -491,6 +491,8 @@ async def create( parent: str | None = None, estimate: Annotated[int | None, Parameter(alias="-e")] = None, description: Annotated[str | None, Parameter(alias="-d")] = None, + image: Annotated[list[str] | None, Parameter(alias="-i")] = None, + force: bool = False, json: bool = False, ) -> None: """Create a new work item. @@ -517,6 +519,11 @@ async def create( Story point estimate. description Work item description (plain text). + image + Image file path to embed in the description (repeatable). The image is + uploaded as an attachment and an img tag is appended to the description. + force + Upload images even if an attachment with the same file name already exists. """ from plane.models.work_items import CreateWorkItem @@ -540,7 +547,7 @@ async def create( create_data = CreateWorkItem(name=title) - if description: + if description and not image: create_data.description_html = f"

{description}

" if priority: @@ -607,6 +614,27 @@ async def create( workspace, project_id, module_data["id"], [data["id"]], ) + # Embed images: upload each, then append tags to the description + # (set here, not in create, because uploads need the issue to exist). + if image: + from plane.models.work_items import UpdateWorkItem + + from planecli.commands.attachments import embed_html, upload_embed_image + + parts = [f"

{description}

"] if description else [] + for path in image: + asset_id = await upload_embed_image( + client, workspace, project_id, data["id"], path, force=force + ) + parts.append(embed_html(asset_id)) + await run_sdk( + client.work_items.update, + workspace, project_id, data["id"], + UpdateWorkItem(description_html="".join(parts)), + ) + data["description_html"] = "".join(parts) + data = _enrich_work_item(data) + except PlaneError as e: raise handle_api_error(e) @@ -626,6 +654,8 @@ async def update( name: str | None = None, estimate: Annotated[int | None, Parameter(alias="-e")] = None, description: Annotated[str | None, Parameter(alias="-d")] = None, + image: Annotated[list[str] | None, Parameter(alias="-i")] = None, + force: bool = False, json: bool = False, ) -> None: """Update a work item. @@ -652,6 +682,12 @@ async def update( Story point estimate. description New description (plain text). + image + Image file path to embed in the description (repeatable). Uploaded as + an attachment and appended to the existing description, or to the new + --description if one is given. + force + Upload images even if an attachment with the same file name already exists. """ from plane.models.work_items import UpdateWorkItem @@ -674,7 +710,22 @@ async def update( if name: update_data.name = name - if description: + # Embed images: upload each, then append tags — to the new + # --description when given, otherwise to the existing one. + if image: + from planecli.commands.attachments import embed_html, upload_embed_image + + parts = [f"

{description}

"] if description else [ + item_data.get("description_html") or "" + ] + for path in image: + asset_id = await upload_embed_image( + client, workspace, project_id, item_id, path, force=force + ) + parts.append(embed_html(asset_id)) + update_data.description_html = "".join(parts) + + if description and not image: update_data.description_html = f"

{description}

" if priority: diff --git a/tests/test_commands/test_attachments.py b/tests/test_commands/test_attachments.py new file mode 100644 index 0000000..ccc3e1b --- /dev/null +++ b/tests/test_commands/test_attachments.py @@ -0,0 +1,449 @@ +"""Tests for work item attachment commands.""" + +from __future__ import annotations + +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from planecli.commands.attachments import _enrich_attachment, _guess_mime, embed_html + + +def test_embed_html_uses_asset_id_as_src(): + # The web editor stores the asset UUID in src and resolves it at render + # time — a full URL here breaks image loading. + assert embed_html("a1") == '

' + + +def test_guess_mime_known_extension(): + assert _guess_mime("shot.png") == "image/png" + assert _guess_mime("notes.MD") == "text/markdown" + + +def test_guess_mime_unknown_extension_defaults_to_octet_stream(): + assert _guess_mime("data.unknownext") == "application/octet-stream" + assert _guess_mime("noext") == "application/octet-stream" + + +def test_enrich_attachment_flattens_attributes(): + data = { + "id": "a1", + "attributes": {"name": "shot.png", "type": "image/png"}, + "size": 191318.0, + "is_uploaded": True, + } + result = _enrich_attachment(data) + assert result["name"] == "shot.png" + assert result["type"] == "image/png" + assert result["size"] == 191318.0 + + +def test_enrich_attachment_tolerates_missing_attributes(): + result = _enrich_attachment({"id": "a1"}) + assert result["name"] == "" + assert result["type"] == "" + assert result["size"] is None + + +@patch( + "planecli.commands.attachments._resolve_item", + new_callable=AsyncMock, +) +async def test_attach_rejects_missing_file(mock_resolve): + from planecli.exceptions import ValidationError + + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + with pytest.raises(ValidationError): + await _run_attach("/definitely/not/here.png") + + +def _upload_side_effects(verify_list): + return [ + [], # 0. dup-check: no existing attachments + { # 1. register -> presigned target + "asset_id": "asset-1", + "upload_data": {"url": "http://uploads.local", "fields": {"key": "k"}}, + }, + MagicMock(status_code=204), # 2. binary upload + None, # 3. PATCH is_uploaded + verify_list, # 4. verify + ] + + +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +@patch("planecli.commands.attachments.get_workspace", return_value="ws") +@patch("planecli.commands.attachments.get_client") +@patch( + "planecli.commands.attachments.resolve_work_item_across_projects_async", + new_callable=AsyncMock, +) +async def test_attach_uploads_then_marks_uploaded(mock_resolve, mock_client, _ws, mock_run): + from planecli.commands.attachments import attach + + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_run.side_effect = _upload_side_effects( + [{"id": "asset-1", "attributes": {"name": "x.png"}, "is_uploaded": True}] + ) + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("builtins.open", MagicMock()), + ): + await attach("ABC-1", "x.png", json=True) + + # binary push went to the presigned URL with form fields, not the API + post_call = mock_run.call_args_list[2] + assert post_call.args[1] == "http://uploads.local" + assert post_call.kwargs["data"] == {"key": "k"} + + +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +@patch("planecli.commands.attachments.get_workspace", return_value="ws") +@patch("planecli.commands.attachments.get_client") +@patch( + "planecli.commands.attachments.resolve_work_item_across_projects_async", + new_callable=AsyncMock, +) +async def test_attach_raises_when_server_does_not_confirm(mock_resolve, _client, _ws, mock_run): + from planecli.exceptions import APIError + + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_run.side_effect = _upload_side_effects( + [{"id": "asset-1", "is_uploaded": False}] # PATCH accepted but not applied + ) + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("builtins.open", MagicMock()), + pytest.raises(APIError), + ): + from planecli.commands.attachments import attach + + await attach("ABC-1", "x.png") + + +@patch("planecli.commands.attachments._guess_mime", return_value="image/png") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_attachment_cancels_on_duplicate_name(mock_run, _mime): + from planecli.commands.attachments import upload_attachment + from planecli.exceptions import ValidationError + + mock_run.side_effect = [ + [{"id": "old-1", "attributes": {"name": "x.png"}, "is_uploaded": True}], + ] + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + pytest.raises(ValidationError, match="already attached"), + ): + # not a TTY in tests -> prompt refuses -> ValidationError + await upload_attachment(MagicMock(), "ws", "p1", "i1", "x.png") + + +@patch("planecli.commands.attachments._guess_mime", return_value="image/png") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_attachment_force_skips_duplicate_check(mock_run, _mime): + from planecli.commands.attachments import upload_attachment + + mock_run.side_effect = [ + [{"id": "old-1", "attributes": {"name": "x.png"}, "is_uploaded": True}], + {"asset_id": "asset-1", "upload_data": {"url": "u", "fields": {}}}, + MagicMock(status_code=204), + None, + [{"id": "asset-1", "attributes": {"name": "x.png"}, "is_uploaded": True}], + ] + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("builtins.open", MagicMock()), + ): + result = await upload_attachment(MagicMock(), "ws", "p1", "i1", "x.png", force=True) + + assert result["id"] == "asset-1" + + +async def _run_attach(path: str) -> None: + from planecli.commands.attachments import attach + + await attach("ABC-1", path) + + +def _resp(status, json_data=None): + m = MagicMock(status_code=status) + m.json.return_value = json_data or {} + return m + + +@patch("planecli.api.client.get_config") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_embed_image_prefers_v2_endpoint(mock_run, mock_cfg): + from planecli.commands.attachments import upload_embed_image + + mock_cfg.return_value = MagicMock(base_url="http://plane.local", api_key="k") + mock_run.side_effect = [ + _resp(200, {"asset_id": "a1", "asset_url": "/api/assets/v2/x/a1/", + "upload_data": {"url": "u", "fields": {}}}), + _resp(204), # binary upload + _resp(204), # mark uploaded + _resp(200), # v1 readback confirms + ] + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("builtins.open", MagicMock()), + ): + asset_id = await upload_embed_image(None, "ws", "p1", "i1", "x.png") + + assert asset_id == "a1" + # first call hits the app (v2) endpoint with the api key, not /api/v1/ + first = mock_run.call_args_list[0] + assert "/api/assets/v2/workspaces/ws/projects/p1/" in first.args[1] + assert first.args[2] == "k" + + +@patch("planecli.commands.attachments.upload_attachment", new_callable=AsyncMock) +@patch("planecli.api.client.get_config") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_embed_image_falls_back_to_v1_on_401( + mock_run, mock_cfg, mock_upload +): + from planecli.commands.attachments import upload_embed_image + + mock_cfg.return_value = MagicMock(base_url="http://plane.local", api_key="k") + mock_run.side_effect = [_resp(401)] + mock_upload.return_value = {"id": "a9"} + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + ): + asset_id = await upload_embed_image(None, "ws", "p1", "i1", "x.png") + + assert asset_id == "a9" + mock_upload.assert_awaited_once() + + +@patch("planecli.api.client.get_config") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_embed_image_raises_on_v2_server_error(mock_run, mock_cfg): + from planecli.commands.attachments import upload_embed_image + from planecli.exceptions import APIError + + mock_cfg.return_value = MagicMock(base_url="http://plane.local", api_key="k") + mock_run.side_effect = [_resp(500)] + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + pytest.raises(APIError), + ): + await upload_embed_image(None, "ws", "p1", "i1", "x.png") + + +@patch("planecli.api.client.get_config") +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_upload_embed_image_raises_when_not_confirmed(mock_run, mock_cfg): + from planecli.commands.attachments import upload_embed_image + from planecli.exceptions import APIError + + mock_cfg.return_value = MagicMock(base_url="http://plane.local", api_key="k") + mock_run.side_effect = [ + _resp(200, {"asset_id": "a1", "asset_url": "/u", + "upload_data": {"url": "u", "fields": {}}}), + _resp(204), + _resp(204), + _resp(404), # readback: asset not visible -> write did not land + ] + + with ( + patch("os.path.isfile", return_value=True), + patch("os.path.getsize", return_value=10), + patch("builtins.open", MagicMock()), + pytest.raises(APIError), + ): + await upload_embed_image(None, "ws", "p1", "i1", "x.png") + + +# --------------------------------------------------------------------------- +# attachment get (download) +# --------------------------------------------------------------------------- + + +def _att(att_id: str, name: str) -> dict: + return {"id": att_id, "name": name, "type": "image/png"} + + +SHOTS = [_att("a1", "image.png"), _att("a2", "image.png"), _att("a3", "notes.md")] + + +def test_select_by_id_wins_over_name(): + from planecli.commands.attachments import _select_attachments + + assert _select_attachments(SHOTS, "a2", False) == [SHOTS[1]] + + +def test_select_by_unique_name(): + from planecli.commands.attachments import _select_attachments + + assert _select_attachments(SHOTS, "notes.md", False) == [SHOTS[2]] + + +def test_select_shared_name_requires_id_or_all(): + from planecli.commands.attachments import _select_attachments + from planecli.exceptions import ValidationError + + with pytest.raises(ValidationError, match="2 attachments are named") as exc: + _select_attachments(SHOTS, "image.png", False) + # the hint lists the ids to choose from + assert "a1" in exc.value.hint and "a2" in exc.value.hint + assert _select_attachments(SHOTS, "image.png", True) == SHOTS[:2] + + +def test_select_unknown_selector_lists_attachments(): + from planecli.commands.attachments import _select_attachments + from planecli.exceptions import ValidationError + + with pytest.raises(ValidationError, match="No attachment matches") as exc: + _select_attachments(SHOTS, "missing.png", False) + assert "notes.md" in exc.value.hint + + +def test_select_without_selector(): + from planecli.commands.attachments import _select_attachments + from planecli.exceptions import ValidationError + + assert _select_attachments(SHOTS[:1], None, False) == SHOTS[:1] + assert _select_attachments(SHOTS, None, True) == SHOTS + with pytest.raises(ValidationError, match="choose one"): + _select_attachments(SHOTS, None, False) + with pytest.raises(ValidationError, match="no attachments"): + _select_attachments([], None, True) + + +def test_plan_paths_suffixes_duplicates_and_existing_files(tmp_path): + from planecli.commands.attachments import _plan_paths + + (tmp_path / "notes.md").write_text("already here") + paths = _plan_paths(SHOTS, tmp_path, overwrite=False) + assert [p.name for p in paths] == ["image.png", "image-2.png", "notes-2.md"] + + +def test_plan_paths_overwrite_keeps_existing_name(tmp_path): + from planecli.commands.attachments import _plan_paths + + (tmp_path / "notes.md").write_text("already here") + paths = _plan_paths(SHOTS, tmp_path, overwrite=True) + assert [p.name for p in paths] == ["image.png", "image-2.png", "notes.md"] + + +def test_plan_paths_strips_directories_from_names(tmp_path): + from planecli.commands.attachments import _plan_paths + + paths = _plan_paths([_att("a1", "../../etc/passwd"), _att("a2", "")], tmp_path, False) + assert paths == [tmp_path / "passwd", tmp_path / "a2"] + + +def _http(status: int, headers: dict | None = None, chunks: list[bytes] | None = None): + m = MagicMock(status_code=status, headers=headers or {}) + m.is_redirect = 300 <= status < 400 + m.iter_content.return_value = chunks or [] + m.__enter__.return_value = m + return m + + +def test_download_follows_redirect_without_api_key(tmp_path): + from planecli.commands.attachments import _download_attachment + + redirect = _http(302, {"Location": "/uploads/obj?sig=1"}) + body = _http(200, chunks=[b"abc", b"de"]) + with patch("requests.get", side_effect=[redirect, body]) as mock_get: + written = _download_attachment( + "http://plane.local/api/v1/workspaces/ws/x/a1/", "secret", tmp_path / "f.png" + ) + + assert written == 5 + assert (tmp_path / "f.png").read_bytes() == b"abcde" + first, second = mock_get.call_args_list + assert first.kwargs["headers"] == {"X-Api-Key": "secret"} + assert first.kwargs["allow_redirects"] is False + # relative Location resolved against the API host; no key sent to storage + assert second.args[0] == "http://plane.local/uploads/obj?sig=1" + assert "headers" not in second.kwargs + + +def test_download_error_leaves_no_partial_file(tmp_path): + from planecli.commands.attachments import _download_attachment + from planecli.exceptions import APIError + + with patch("requests.get", return_value=_http(400)), pytest.raises(APIError): + _download_attachment("http://plane.local/a/", "k", tmp_path / "f.png") + + body = _http(200) + body.iter_content.side_effect = OSError("connection reset") + with patch("requests.get", return_value=body), pytest.raises(OSError): + _download_attachment("http://plane.local/a/", "k", tmp_path / "f.png") + assert list(tmp_path.iterdir()) == [] + + +@patch("planecli.commands.attachments.get_workspace", return_value="ws") +@patch("planecli.commands.attachments.get_client") +@patch("planecli.commands.attachments._resolve_item", new_callable=AsyncMock) +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_get_all_downloads_each_selected_attachment( + mock_run, mock_resolve, _client, _ws, tmp_path, capsys +): + import json as jsonlib + + from planecli.commands.attachments import get + + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + listed = [ + {"id": "a1", "attributes": {"name": "image.png", "type": "image/png"}}, + {"id": "a2", "attributes": {"name": "image.png", "type": "image/png"}}, + {"id": "a3", "attributes": {"name": "old.png"}, "is_deleted": True}, + ] + mock_run.side_effect = [listed, 10, 20] + + with patch( + "planecli.api.client.get_config", + return_value=MagicMock(base_url="http://plane.local", api_key="k"), + ): + await get("ABC-1", "image.png", all_=True, dir=str(tmp_path), json=True) + + out = jsonlib.loads(capsys.readouterr().out) + assert [(o["id"], o["size"]) for o in out] == [("a1", 10), ("a2", 20)] + assert [o["path"].rsplit("/", 1)[1] for o in out] == ["image.png", "image-2.png"] + url = mock_run.call_args_list[1].args[1] + assert url == ( + "http://plane.local/api/v1/workspaces/ws/projects/proj-1/" + "work-items/item-1/attachments/a1/" + ) + + +@patch("planecli.commands.attachments.get_workspace", return_value="ws") +@patch("planecli.commands.attachments.get_client") +@patch("planecli.commands.attachments._resolve_item", new_callable=AsyncMock) +@patch("planecli.commands.attachments.run_sdk", new_callable=AsyncMock) +async def test_get_output_rejects_several_attachments(mock_run, mock_resolve, _client, _ws): + from planecli.commands.attachments import get + from planecli.exceptions import ValidationError + + mock_resolve.return_value = ({"id": "item-1"}, "proj-1") + mock_run.side_effect = [ + [{"id": "a1", "attributes": {"name": "x"}}, {"id": "a2", "attributes": {"name": "y"}}] + ] + with pytest.raises(ValidationError, match="--output takes a single"): + await get("ABC-1", all_=True, output_file="out.bin") + + +async def test_get_rejects_output_with_dir(): + from planecli.commands.attachments import get + from planecli.exceptions import ValidationError + + with pytest.raises(ValidationError, match="not both"): + await get("ABC-1", output_file="a", dir=".") diff --git a/tests/test_commands/test_comments.py b/tests/test_commands/test_comments.py index 25a4f51..cc07444 100644 --- a/tests/test_commands/test_comments.py +++ b/tests/test_commands/test_comments.py @@ -7,14 +7,82 @@ import pytest from plane.errors import PlaneError -from planecli.commands.comments import _enrich_comment +from planecli.commands.comments import _body_to_html, _enrich_comment + + +def test_body_to_html_wraps_single_line_in_one_paragraph(): + assert _body_to_html("hello") == "

hello

" + + +def test_body_to_html_splits_blank_lines_into_paragraphs(): + body = "first\n\nsecond\n\n\nthird" + assert _body_to_html(body) == "

first

second

third

" + + +def test_body_to_html_converts_single_newline_to_br(): + body = "追加修复:\n1) first\n2) second" + assert _body_to_html(body) == "

追加修复:
1) first
2) second

" + + +def test_body_to_html_linkifies_bare_url(): + body = "PR https://github.com/owner/repo/pull/12" + assert ( + _body_to_html(body) == '

PR ' + "https://github.com/owner/repo/pull/12

" + ) + + +def test_body_to_html_keeps_trailing_punctuation_out_of_link(): + body = "见 https://example.com/a。下一条" + assert ( + _body_to_html(body) + == '

见 https://example.com/a。下一条

' + ) + + +def test_body_to_html_does_not_double_link_existing_anchor(): + body = 'https://example.com' + assert _body_to_html(body) == f"

{body}

" + + +def test_body_to_html_linkifies_multiple_urls_in_one_line(): + body = "Issue https://a/1\nPR https://b/2" + assert ( + _body_to_html(body) == '

Issue https://a/1
' + 'PR https://b/2

' + ) + + +def test_body_to_html_converts_inline_backticks_to_code(): + body = "分支 `feat/x`,已推送" + assert _body_to_html(body) == "

分支 feat/x,已推送

" + + +def test_body_to_html_escapes_html_inside_inline_code(): + body = "存 `

` 标签" + assert _body_to_html(body) == "

存 <p> 标签

" + + +def test_body_to_html_does_not_linkify_url_inside_code(): + body = "`https://a/1` 是内部地址" + assert _body_to_html(body) == "

https://a/1 是内部地址

" + + +def test_body_to_html_converts_fenced_block_to_pre(): + body = "前\n\n```\ncode x\n```\n\n后" + assert ( + _body_to_html(body) == "

前

code <b>x</b>

后

" + ) + + +def test_body_to_html_fenced_block_ignores_language_hint(): + body = "```python\nprint(1)\n```" + assert _body_to_html(body) == "
print(1)
" def test_enrich_comment_resolves_actor_name_from_members_map(): members_map = {"user-1": "Alice"} - result = _enrich_comment( - {"actor": "user-1", "comment_html": "

hello

"}, members_map - ) + result = _enrich_comment({"actor": "user-1", "comment_html": "

hello

"}, members_map) assert result["actor_name"] == "Alice" assert result["body_text"] == "hello" @@ -25,9 +93,7 @@ def test_enrich_comment_falls_back_to_uuid_without_map(): def test_enrich_comment_falls_back_to_uuid_when_member_missing(): - result = _enrich_comment( - {"actor": "user-x", "comment_html": ""}, {"user-1": "Alice"} - ) + result = _enrich_comment({"actor": "user-x", "comment_html": ""}, {"user-1": "Alice"}) assert result["actor_name"] == "user-x" assert result["body_text"] == "" @@ -43,10 +109,18 @@ async def test_fetch_issue_comments_sorts_and_resolves(mock_comments, mock_membe ] # Returned out of order; helper must sort oldest -> newest mock_comments.return_value = [ - {"id": "c2", "actor": "u2", "comment_html": "

later

", - "created_at": "2026-02-11T10:00:00Z"}, - {"id": "c1", "actor": "u1", "comment_html": "

earlier

", - "created_at": "2026-02-10T10:00:00Z"}, + { + "id": "c2", + "actor": "u2", + "comment_html": "

later

", + "created_at": "2026-02-11T10:00:00Z", + }, + { + "id": "c1", + "actor": "u1", + "comment_html": "

earlier

", + "created_at": "2026-02-10T10:00:00Z", + }, ] result = await fetch_issue_comments("ws", "p1", "item-1") @@ -64,8 +138,12 @@ async def test_fetch_issue_comments_returns_all(mock_comments, mock_members): mock_members.return_value = [] mock_comments.return_value = [ - {"id": f"c{i}", "actor": "u1", "comment_html": "

x

", - "created_at": f"2026-02-{i:02d}T00:00:00Z"} + { + "id": f"c{i}", + "actor": "u1", + "comment_html": "

x

", + "created_at": f"2026-02-{i:02d}T00:00:00Z", + } for i in range(1, 31) ] @@ -87,9 +165,7 @@ async def test_fetch_issue_comments_raises_on_failure(mock_comments, mock_member @patch("planecli.cache.cached_list_members", new_callable=AsyncMock) @patch("planecli.cache.cached_list_comments", new_callable=AsyncMock) -async def test_fetch_issue_comments_degrades_when_members_fail( - mock_comments, mock_members -): +async def test_fetch_issue_comments_degrades_when_members_fail(mock_comments, mock_members): """A members-list failure is a secondary-enrichment concern: it must not take down comments that already loaded successfully (names fall back to the raw actor UUID, same as the no-map case).""" @@ -97,8 +173,12 @@ async def test_fetch_issue_comments_degrades_when_members_fail( mock_members.side_effect = PlaneError("members unavailable") mock_comments.return_value = [ - {"id": "c1", "actor": "u1", "comment_html": "

hi

", - "created_at": "2026-02-10T10:00:00Z"}, + { + "id": "c1", + "actor": "u1", + "comment_html": "

hi

", + "created_at": "2026-02-10T10:00:00Z", + }, ] result = await fetch_issue_comments("ws", "p1", "item-1")