diff --git a/CHANGELOG.md b/CHANGELOG.md index e85ba28..fa1d9c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Fixed - `project create` without `-i` now derives the identifier from the first 5 ASCII letters of the name (accents folded, digits and symbols dropped), instead of the first 3 raw characters, which could include spaces and punctuation. Names with no usable letters fail with a validation error asking for `-i`, and a 409 on a derived identifier names the value and suggests `-i`. Thanks to Omar Adel (#8) - `document create` no longer crashes before the API call: `CreatePage` now receives the required `description_html` at construction (`

` when `--content` is omitted) +- `doc create` and `doc update` convert `--content` to HTML: blank lines separate paragraphs, single newlines become line breaks, bare URLs become links, and backticks and fences become code. Before, the text went into one paragraph and lost its line breaks. `doc update --content ""` clears the content. Thanks to Liewzheng (#21) +- `doc delete` reports an HTTP error with exit code 4 (2 for a 401) instead of a traceback. Some self-hosted servers answer 405 to page deletes +- `doc show`, `create`, `update` and `list` keep line and paragraph breaks in the `Content` field (`content_text` in `--json`) and show entities such as `<` as text ## [0.5.1] - 2026-07-03 diff --git a/README.md b/README.md index d729aff..b711520 100644 --- a/README.md +++ b/README.md @@ -220,7 +220,7 @@ planecli doc create --title "API Spec" --content "## Endpoints..." -p "Frontend" # Update a document planecli doc update "API Spec" --content "Updated content" -p "Frontend" -# Delete a document +# Delete a document (permanent) planecli doc delete "API Spec" -p "Frontend" ``` diff --git a/docs/guides/plane-api.md b/docs/guides/plane-api.md index 793a238..6a13faa 100644 --- a/docs/guides/plane-api.md +++ b/docs/guides/plane-api.md @@ -14,6 +14,11 @@ See [ADR-0003](../adr/0003-sdk-escape-hatches.md) for the reasoning. A `200` is not always a write. Some endpoints accept a mutation and ignore it: the intake `PATCH` returns `200` with the record unchanged when the caller is not a project Admin. Where that is known, read the raw response and compare the field you meant to change *before* enriching it for display, then raise `APIError`. See [ADR-0007](../adr/0007-verify-writes-the-api-can-silently-ignore.md). +## Documents + +- Page writes depend on the server. On a self-hosted Community Edition server (version not recorded), checked on 2026-11-06, the page URL allowed only `GET`: `PATCH` and `DELETE` answered `405`, and `POST .../archive/` answered `404`. So `doc update` and `doc delete` cannot work there, while `doc create` did. The v1 reference documents archiving as `POST .../archive/` and says deleting an active page returns `400`; neither is verified on a server yet. +- The API stores `description_html` verbatim and does not parse markdown, so `--content` goes through `utils/body_html.py::body_to_html` first. Text outside code is not escaped yet. + ## Intake Intake mutations take the work item UUID, not the intake wrapper `id`: use the `Issue ID` column of `intake ls`. `intake delete` also deletes the underlying work item for any status other than `accepted`. diff --git a/skills/references/command-reference.md b/skills/references/command-reference.md index f4ea235..adab9be 100644 --- a/skills/references/command-reference.md +++ b/skills/references/command-reference.md @@ -278,6 +278,8 @@ planecli doc update TITLE --content CONTENT -p PROJECT planecli doc delete TITLE -p PROJECT ``` +`doc delete` is permanent. Some self-hosted servers answer 405 to `doc update` and `doc delete`. `--content` is plain text: blank lines split paragraphs, newlines become line breaks, URLs become links, and backticks and fences become code. + ## Comments Command group: `planecli comment` (alias: `comments`) diff --git a/src/planecli/commands/documents.py b/src/planecli/commands/documents.py index 81aaa68..e1f998d 100644 --- a/src/planecli/commands/documents.py +++ b/src/planecli/commands/documents.py @@ -11,7 +11,9 @@ 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, AuthenticationError, PlaneCLIError from planecli.formatters import output, output_single +from planecli.utils.body_html import body_to_html from planecli.utils.resolve import resolve_project_async doc_app = cyclopts.App( @@ -39,14 +41,29 @@ def _enrich_doc(data: dict) -> dict: """Add convenience fields to a document dict.""" desc_html = data.get("description_html") or "" if desc_html: + import html import re - data["content_text"] = re.sub(r"<[^>]+>", "", desc_html).strip() + # Turn line and block breaks back into newlines before dropping tags, + # so lines and paragraphs do not run together. + text = re.sub(r"", "\n", desc_html) + text = re.sub(r"", "\n\n", text) + data["content_text"] = html.unescape(re.sub(r"<[^>]+>", "", text)).strip() else: data["content_text"] = "" return data +def _http_error(err: Exception, message: str) -> PlaneCLIError: + """Translate a requests failure into the CLI's exit-code contract.""" + response = getattr(err, "response", None) + # A 4xx/5xx Response is falsy, so compare with None. + status = response.status_code if response is not None else None + if status == 401: + return AuthenticationError() + return APIError(f"{message}: {err}", status_code=status) + + @doc_app.command(name="list", alias="ls") async def list_( *, @@ -163,8 +180,12 @@ async def create( client = get_client() workspace = get_workspace() - description_html = f"

{content}

" if content is not None else "

" - page_data = CreatePage(name=title, description_html=description_html) + # description_html is a required SDK field — omitting it crashes + # CreatePage construction even for an empty body. + page_data = CreatePage( + name=title, + description_html=body_to_html(content) if content is not None else "

", + ) if project: proj = await resolve_project_async(project, client, workspace) @@ -216,8 +237,8 @@ async def update( update_payload: dict = {} if title: update_payload["name"] = title - if content: - update_payload["description_html"] = f"

{content}

" + if content is not None: + update_payload["description_html"] = body_to_html(content) if project: proj = await resolve_project_async(project, client, workspace) @@ -245,7 +266,7 @@ async def delete( *, project: Annotated[str | None, Parameter(alias="-p")] = None, ) -> None: - """Delete (trash) a document. + """Permanently delete a document. Parameters ---------- @@ -276,8 +297,11 @@ async def delete( url = f"{config.base_url}/api/v1/workspaces/{workspace}/pages/{document}/" headers = {"X-Api-Key": config.api_key} - resp = await asyncio.to_thread(requests.delete, url, headers=headers, timeout=30) - resp.raise_for_status() + try: + resp = await asyncio.to_thread(requests.delete, url, headers=headers, timeout=30) + resp.raise_for_status() + except requests.RequestException as e: + raise _http_error(e, "the document was not deleted") from e except PlaneError as e: raise handle_api_error(e) diff --git a/src/planecli/utils/body_html.py b/src/planecli/utils/body_html.py new file mode 100644 index 0000000..a9995bf --- /dev/null +++ b/src/planecli/utils/body_html.py @@ -0,0 +1,71 @@ +"""Convert plain user-authored text to the HTML Plane's editor stores. + +The Plane API stores HTML verbatim and does not parse markdown or auto-link +URLs — only the web editor does — so text written via the CLI must arrive +already converted. Used by document write commands. +""" + +from __future__ import annotations + +import html +import re + +_URL_RE = re.compile(r"(?=])(https?://[A-Za-z0-9\-._~:/?#\[\]@!$&()*+,;=%]+)") +# Trailing punctuation that belongs to the sentence, not the URL. +_URL_TRAIL = ".,;:!?)]}。,;:!?)】、" +# A fenced block: an opening ``` line with an optional info string (py, c++, +# shell-session...), the body, and a closing ``` line. +_FENCE_RE = re.compile(r"^[ \t]*```[^\n`]*\n(.*?)^[ \t]*```[ \t]*$", re.DOTALL | re.MULTILINE) + + +def _linkify(text: str) -> str: + """Turn bare http(s) URLs into anchors. + + URLs already inside an href attribute are left alone (the regex excludes + matches preceded by a quote or angle bracket from an attribute context). + """ + + def _sub(m: re.Match[str]) -> str: + raw = m.group(1) + url = raw.rstrip(_URL_TRAIL) + # Keep a closing paren that balances one inside the URL: .../Foo_(bar) + while raw[len(url) :].startswith(")") and url.count("(") > url.count(")"): + url += ")" + return f'{url}{raw[len(url) :]}' + + return _URL_RE.sub(_sub, text) + + +def _inline(text: str) -> str: + """Convert one paragraph: code spans, bare URLs, and line breaks.""" + # Odd slots of the split are code-span contents, so URLs inside them are + # never linkified. + parts = re.split(r"`([^`\n]+)`", text) + converted = "".join( + f"{html.escape(part)}" if i % 2 else _linkify(part) + for i, part in enumerate(parts) + ) + return converted.replace("\n", "
") + + +def body_to_html(body: str) -> str: + """Convert plain 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). Empty input gives an empty paragraph. + """ + parts: list[str] = [] + # Odd slots of the split are fence bodies, so a block never lands inside + # a paragraph. + for i, segment in enumerate(_FENCE_RE.split(body.replace("\r\n", "\n").strip())): + if i % 2: + code = html.escape(segment.strip("\n")) + parts.append(f"
{code}
") + continue + for p in re.split(r"\n\s*\n", segment): + if p.strip(): + parts.append(f"

{_inline(p.strip())}

") + return "".join(parts) or "

" diff --git a/tests/test_commands/test_documents.py b/tests/test_commands/test_documents.py index 1b26864..b6bdfe1 100644 --- a/tests/test_commands/test_documents.py +++ b/tests/test_commands/test_documents.py @@ -1,12 +1,14 @@ -"""Tests for document / page commands.""" +"""Tests for document (page) commands.""" from __future__ import annotations from unittest.mock import AsyncMock, MagicMock, patch +import pytest from plane.models.pages import CreatePage -from planecli.commands.documents import DOC_FIELDS, create +from planecli.commands.documents import DOC_FIELDS, _enrich_doc, create +from planecli.utils.body_html import body_to_html def _page_model(**overrides) -> MagicMock: @@ -24,6 +26,92 @@ def _page_model(**overrides) -> MagicMock: return m +def test_enrich_doc_strips_html_to_text(): + data = _enrich_doc({"id": "p1", "name": "Doc", "description_html": "

hi
there

"}) + assert data["content_text"] == "hi\nthere" + + +def test_enrich_doc_round_trips_converted_body(): + body = "line one\nline two\n\nuse `Vec` here" + data = _enrich_doc({"id": "p1", "description_html": body_to_html(body)}) + assert data["content_text"] == body.replace("`", "") + + +def test_enrich_doc_empty_description(): + data = _enrich_doc({"id": "p1", "name": "Doc", "description_html": None}) + assert data["content_text"] == "" + + +def test_body_to_html_blank_lines_split_paragraphs(): + assert body_to_html("one\n\n\ntwo") == "

one

two

" + + +def test_body_to_html_single_newline_becomes_br(): + assert body_to_html("one\ntwo") == "

one
two

" + + +def test_body_to_html_linkifies_bare_urls(): + html = body_to_html("see https://example.com/a, ok") + assert html == '

see https://example.com/a, ok

' + + +def test_body_to_html_linkify_keeps_trailing_punctuation_outside_anchor(): + html = body_to_html("visit https://plane.so.") + assert html == '

visit https://plane.so.

' + + +def test_body_to_html_backticks_become_code(): + assert body_to_html("run `make test` now") == "

run make test now

" + + +def test_body_to_html_inline_code_is_escaped_and_not_linkified(): + html = body_to_html("use `https://x.io ` here") + assert html == "

use https://x.io <b> here

" + + +def test_body_to_html_fenced_block_becomes_pre_code(): + html = body_to_html("before\n\n```py\nprint('')\n```\n\nafter") + assert html == "

before

print('<x>')

after

" + + +def test_body_to_html_url_mid_code_span_is_not_linkified(): + assert body_to_html("`see https://x.io now`") == "

see https://x.io now

" + assert body_to_html('`curl "https://x.io/a"`') == ( + "

curl "https://x.io/a"

" + ) + + +def test_body_to_html_fence_glued_to_text_stays_out_of_paragraph(): + assert body_to_html("Run:\n```\nls\n```\ndone") == ( + "

Run:

ls

done

" + ) + + +def test_body_to_html_adjacent_fences(): + assert body_to_html("```\na\n```\n```\nb\n```") == ( + "
a
b
" + ) + + +def test_body_to_html_fence_info_string_and_crlf(): + assert body_to_html("```c++\r\n#include \r\n```") == ( + "
#include <vector>
" + ) + + +def test_body_to_html_url_keeps_balanced_closing_paren(): + url = "https://en.wikipedia.org/wiki/Foo_(bar)" + assert body_to_html(url) == f'

{url}

' + assert body_to_html("(see https://x.io/a)") == ( + '

(see https://x.io/a)

' + ) + + +@pytest.mark.parametrize("body", ["", " \n "]) +def test_body_to_html_empty_input_gives_empty_paragraph(body): + assert body_to_html(body) == "

" + + @patch("planecli.commands.documents.output_single") @patch("planecli.commands.documents.run_sdk", new_callable=AsyncMock) @patch("planecli.commands.documents.resolve_project_async", new_callable=AsyncMock) @@ -86,3 +174,139 @@ async def test_create_without_project_creates_workspace_page( assert args[0] is mock_client.return_value.pages.create_workspace_page assert args[1] == "ws" assert args[2].description_html == "

hello

" + + +@patch("planecli.commands.documents.output_single") +@patch("planecli.commands.documents.run_sdk", new_callable=AsyncMock) +@patch("planecli.commands.documents.resolve_project_async", new_callable=AsyncMock) +@patch("planecli.commands.documents.get_workspace", return_value="ws") +@patch("planecli.commands.documents.get_client") +async def test_doc_create_converts_content_to_html( + mock_client, mock_ws, mock_resolve, mock_run_sdk, mock_output +): + mock_resolve.return_value = {"id": "proj-1"} + mock_run_sdk.return_value = _page_model(description_html="") + + await create( + title="Doc", + content="line one\nline two\n\nsee https://plane.so and `make check`", + project="Frontend", + ) + + page_data = mock_run_sdk.call_args[0][3] + assert page_data.description_html == ( + "

line one
line two

" + '

see https://plane.so' + " and make check

" + ) + + +def _mock_config(): + config = MagicMock() + config.base_url = "https://plane.example.com" + config.api_key = "key" + return config + + +@patch("planecli.commands.documents.output_single") +@patch("requests.patch") +@patch("planecli.api.client.get_config", return_value=_mock_config()) +@patch("planecli.commands.documents.resolve_project_async", new_callable=AsyncMock) +@patch("planecli.commands.documents.get_workspace", return_value="ws") +@patch("planecli.commands.documents.get_client") +async def test_doc_update_converts_content( + mock_client, mock_ws, mock_resolve, mock_config, mock_patch, mock_output +): + from planecli.commands.documents import update + + mock_resolve.return_value = {"id": "proj-1"} + resp = MagicMock() + resp.json.return_value = {"id": "p1", "name": "Doc", "description_html": ""} + mock_patch.return_value = resp + + await update("doc-uuid", title="Doc", content="a\nb", project="Frontend") + + url = mock_patch.call_args[0][0] + assert url == ("https://plane.example.com/api/v1/workspaces/ws/projects/proj-1/pages/doc-uuid/") + payload = mock_patch.call_args.kwargs["json"] + assert payload == {"name": "Doc", "description_html": "

a
b

"} + + +@patch("planecli.commands.documents.output_single") +@patch("requests.patch") +@patch("planecli.api.client.get_config", return_value=_mock_config()) +@patch("planecli.commands.documents.get_workspace", return_value="ws") +@patch("planecli.commands.documents.get_client") +async def test_doc_update_workspace_page_url( + mock_client, mock_ws, mock_config, mock_patch, mock_output +): + from planecli.commands.documents import update + + resp = MagicMock() + resp.json.return_value = {"id": "p1", "name": "Doc", "description_html": ""} + mock_patch.return_value = resp + + await update("doc-uuid", content="x") + + url = mock_patch.call_args[0][0] + assert url == "https://plane.example.com/api/v1/workspaces/ws/pages/doc-uuid/" + + +def _http_error_response(status: int) -> MagicMock: + import requests + + resp = MagicMock() + resp.status_code = status + resp.raise_for_status.side_effect = requests.HTTPError(f"{status} Error", response=resp) + return resp + + +@patch("requests.delete") +@patch("planecli.api.client.get_config", return_value=_mock_config()) +@patch("planecli.commands.documents.get_workspace", return_value="ws") +@patch("planecli.commands.documents.get_client") +async def test_doc_delete_workspace_page_url(mock_client, mock_ws, mock_config, mock_delete): + from planecli.commands.documents import delete + + await delete("doc-uuid") + + url = mock_delete.call_args[0][0] + assert url == "https://plane.example.com/api/v1/workspaces/ws/pages/doc-uuid/" + + +@patch("requests.delete") +@patch("planecli.api.client.get_config", return_value=_mock_config()) +@patch("planecli.commands.documents.resolve_project_async", new_callable=AsyncMock) +@patch("planecli.commands.documents.get_workspace", return_value="ws") +@patch("planecli.commands.documents.get_client") +async def test_doc_delete_project_page_url( + mock_client, mock_ws, mock_resolve, mock_config, mock_delete +): + from planecli.commands.documents import delete + + mock_resolve.return_value = {"id": "proj-1"} + + await delete("doc-uuid", project="Frontend") + + url = mock_delete.call_args[0][0] + assert url == "https://plane.example.com/api/v1/workspaces/ws/projects/proj-1/pages/doc-uuid/" + + +@pytest.mark.parametrize(("status", "exit_code"), [(400, 4), (401, 2), (404, 4), (405, 4)]) +@patch("requests.delete") +@patch("planecli.api.client.get_config", return_value=_mock_config()) +@patch("planecli.commands.documents.get_workspace", return_value="ws") +@patch("planecli.commands.documents.get_client") +async def test_doc_delete_http_error_maps_to_exit_code( + mock_client, mock_ws, mock_config, mock_delete, status, exit_code +): + """Some self-hosted servers answer 405 to page deletes: report it, no traceback.""" + from planecli.commands.documents import delete + from planecli.exceptions import PlaneCLIError + + mock_delete.return_value = _http_error_response(status) + + with pytest.raises(PlaneCLIError, match="not deleted|Authentication") as exc_info: + await delete("doc-uuid") + + assert exc_info.value.exit_code == exit_code