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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<p></p>` 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 `&lt;` as text

## [0.5.1] - 2026-07-03

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
```

Expand Down
5 changes: 5 additions & 0 deletions docs/guides/plane-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
2 changes: 2 additions & 0 deletions skills/references/command-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
Expand Down
40 changes: 32 additions & 8 deletions src/planecli/commands/documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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"<br\s*/?>", "\n", desc_html)
text = re.sub(r"</(?:p|pre)>", "\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_(
*,
Expand Down Expand Up @@ -163,8 +180,12 @@ async def create(
client = get_client()
workspace = get_workspace()

description_html = f"<p>{content}</p>" if content is not None else "<p></p>"
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 "<p></p>",
)

if project:
proj = await resolve_project_async(project, client, workspace)
Expand Down Expand Up @@ -216,8 +237,8 @@ async def update(
update_payload: dict = {}
if title:
update_payload["name"] = title
if content:
update_payload["description_html"] = f"<p>{content}</p>"
if content is not None:
update_payload["description_html"] = body_to_html(content)

if project:
proj = await resolve_project_async(project, client, workspace)
Expand Down Expand Up @@ -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
----------
Expand Down Expand Up @@ -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)

Expand Down
71 changes: 71 additions & 0 deletions src/planecli/utils/body_html.py
Original file line number Diff line number Diff line change
@@ -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'<a href="{url}">{url}</a>{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"<code>{html.escape(part)}</code>" if i % 2 else _linkify(part)
for i, part in enumerate(parts)
)
return converted.replace("\n", "<br/>")


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"<pre><code>{code}</code></pre>")
continue
for p in re.split(r"\n\s*\n", segment):
if p.strip():
parts.append(f"<p>{_inline(p.strip())}</p>")
return "".join(parts) or "<p></p>"
Loading
Loading