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
7 changes: 5 additions & 2 deletions museoncli/domains/_writes.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,16 @@
Notes = tuple[Any, list[str], list[str]]


def uuid_arg(value: Any, *, flag: str) -> str:
_UUID_LOOKUP = "Look the ID up first with the matching +list or +get command."


def uuid_arg(value: Any, *, flag: str, lookup: str | None = None) -> str:
try:
return str(UUID(str(value)))
except (TypeError, ValueError):
raise ValueError(
f"{flag} must be a canonical UUID (e.g. 72defd40-39ad-40d3-8105-8f23a9a016da), "
f"got {value!r}. Look the ID up first with the matching +list or +get command."
f"got {value!r}. {lookup or _UUID_LOOKUP}"
) from None


Expand Down
56 changes: 44 additions & 12 deletions museoncli/domains/html_documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,41 @@ def _library(organization_id: str) -> str:
return f"/organizations/{organization_id}/html-documents"


def _id_lookup_hint() -> str:
"""Name only the list/get shortcuts this domain actually registers."""
present = {
spec.shortcut
for spec in specs()
if spec.resource is None and spec.shortcut in {"+list", "+get"}
}
names = [name for name in ("+list", "+get") if name in present]
which = " or ".join(names) if names else "+list"
return f"Look the ID up first with the matching {which} command."


def _blank_query() -> None:
from museoncli.main import UsageError

raise UsageError("--q must be 1-200 characters.", command="html-documents.list")


def _folder_argument(value: str) -> str:
"""``root`` in any case, or a folder id. Anything else says ``root`` is valid."""
if value.lower() == "root":
return "root"
try:
return uuid_arg(value, flag="--folder", lookup=_id_lookup_hint())
except ValueError:
raise ValueError(
"--folder must be the literal root or a canonical UUID "
f"(e.g. {_FOLDER}), got {value!r}. {_id_lookup_hint()}"
) from None


def _folder_id_argument(value: str) -> str:
return uuid_arg(value, flag="--folder-id", lookup=_id_lookup_hint())


# -- executors ---------------------------------------------------------------


Expand All @@ -143,8 +178,8 @@ async def _execute_upload(ctx: CommandContext) -> Any:
async def _execute_list(ctx: CommandContext) -> Any:
arguments = ctx.arguments
folder = arguments.get("folder")
if isinstance(folder, str) and folder != "root":
folder = uuid_arg(folder, flag="--folder")
if isinstance(folder, str) and folder.strip():
folder = _folder_argument(folder.strip())
params: dict[str, Any] = {}
if arguments.get("q"):
params["q"] = arguments["q"]
Expand Down Expand Up @@ -209,7 +244,7 @@ def _build_upload_arguments(args: argparse.Namespace) -> dict[str, Any]:
else:
payload["filename"] = resolved
if payload.get("folder_id"):
payload["folder_id"] = uuid_arg(payload["folder_id"], flag="--folder-id")
payload["folder_id"] = _folder_id_argument(str(payload["folder_id"]))
else:
payload.pop("folder_id", None)
_read_html(Path(str(payload["file"])).expanduser())
Expand All @@ -229,21 +264,18 @@ def _build_list_arguments(args: argparse.Namespace) -> dict[str, Any]:
query = payload.get("q")
if isinstance(query, str):
query = query.strip()
if query:
if len(query) > 200:
raise ValueError("--q must be at most 200 characters.")
payload["q"] = query
else:
payload.pop("q", None)
if not query:
_blank_query()
if len(query) > 200:
raise ValueError("--q must be at most 200 characters.")
payload["q"] = query
folder = payload.get("folder")
if isinstance(folder, str):
folder = folder.strip()
if not folder:
payload.pop("folder", None)
elif folder != "root":
payload["folder"] = uuid_arg(folder, flag="--folder")
else:
payload["folder"] = folder
payload["folder"] = _folder_argument(folder)
return payload


Expand Down
79 changes: 75 additions & 4 deletions museoncli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,27 @@ def cli_outdated_error(response: httpx.Response) -> CliOutdatedError:
)


# The HTML document API answers with {"code": "..."} and no message text.
_HTML_DOCUMENT_CODE_MESSAGES = {
"folder_not_found": "Folder not found",
"folder_name_taken": "A folder with this name already exists",
"document_not_found": "Document not found",
"folder_not_empty": "Move or delete the documents in this folder first.",
"html_too_large": "This HTML file is too large.",
"invalid_filename": "Use a single HTML filename, without a folder path.",
"invalid_html": "The file has no HTML to store.",
"invalid_title": "Enter a title.",
"invalid_folder": "Folder must be root or a folder id.",
"invalid_folder_name": "Enter a folder name.",
"invalid_slug": "Slug is not valid.",
"slug_taken": "A document with this slug already exists.",
"invalid_document": "Document could not be saved.",
}

# Messages for server codes whose body carries no readable text of its own.
_SERVER_CODE_MESSAGES = {
"organization_workspace_mismatch": ORGANIZATION_WORKSPACE_MISMATCH_MESSAGE,
**_HTML_DOCUMENT_CODE_MESSAGES,
}


Expand Down Expand Up @@ -225,6 +243,13 @@ def main(*, update: dict[str, Any] | None = None) -> None:
_ACTIVE_UPDATE.set(update)
try:
result = asyncio.run(dispatch(args))
except UsageError as exc:
# Argument checks inside a command (not argparse) are usage errors too.
payload, code = error_envelope(exc, command=exc.command or command)
if deprecations:
payload["warnings"] = deprecations
emit(with_notice(payload, args, update))
raise SystemExit(code) from None
except KeyboardInterrupt:
emit(
{
Expand Down Expand Up @@ -1171,23 +1196,69 @@ def exception_detail(exc: Exception) -> Any:
return exc.detail if isinstance(exc, ApiRequestError) else str(exc)


def _coded_body(value: Any) -> dict[str, Any] | None:
"""A business error ``{"code": ...}``, or one JSON encoding of that object."""
if isinstance(value, str):
text = value.strip()
if len(text) > 2000 or not (text.startswith("{") and text.endswith("}")):
return None
try:
value = json.loads(text)
except json.JSONDecodeError:
return None
if isinstance(value, dict):
code = value.get("code")
if isinstance(code, str) and code:
return value
return None


def _server_business_error(detail: Any) -> dict[str, Any] | None:
"""The coded object in an API failure, including one nested encoding of it."""
coded = _coded_body(detail)
if coded is not None:
return coded
if isinstance(detail, dict):
for key in ("message", "detail", "error"):
coded = _coded_body(detail.get(key))
if coded is not None:
return coded
return None


def error_envelope(exc: Exception, *, command: str | None) -> tuple[dict[str, Any], int]:
"""Render one failure as the JSON error contract and its exit code.

``reason`` and ``detail`` keep their released meaning; ``error`` adds a stable
shape: ``code`` (the same category as ``reason``), a readable ``message``, the
server's own ``server_code`` when it sent one, ``http_status`` and ``retryable``.

A body that is only ``{"code": "..."}`` — or one JSON encoding of that object,
which used to be copied into ``message`` — sets ``server_code``. A code with a
known sentence uses that sentence. A body that already has its own message is
left alone.
"""
reason = reason_from_exception(exc)
detail = exception_detail(exc)
message = _error_message(detail)
error: dict[str, Any] = {"code": reason, "message": message.removeprefix(f"{reason}: ")}
if isinstance(exc, ApiRequestError):
error["http_status"] = exc.status_code
if isinstance(detail, dict) and isinstance(detail.get("code"), str) and detail["code"]:
error["server_code"] = detail["code"]
if detail["code"] in _SERVER_CODE_MESSAGES and not detail.get("message"):
error["message"] = _SERVER_CODE_MESSAGES[detail["code"]]
coded = _server_business_error(detail)
if coded is not None:
error["server_code"] = coded["code"]
own = coded.get("message")
if isinstance(detail, dict) and detail is not coded:
own = detail.get("message", own)
human_own = isinstance(own, str) and bool(own) and _coded_body(own) is None
# Blank, or a message that is itself the encoded code object. A non-string
# message (validation fields) is neither, so the dumped text stays.
missing_text = own in (None, "") or (isinstance(own, str) and not human_own)
mapped = _SERVER_CODE_MESSAGES.get(coded["code"])
if human_own and isinstance(detail, str):
error["message"] = own
elif mapped is not None and missing_text:
error["message"] = mapped
if isinstance(exc, CliOutdatedError):
error["hint"] = exc.detail.get("install_hint")
if isinstance(exc, RemovedCommandError):
Expand Down
Loading
Loading