Files
claude-config/bin/atlassian/client.py
T

52 lines
2.4 KiB
Python

"""What the Jira and Confluence backends share: one Atlassian account's credentials, the request they send through, and each service's error messages."""
import base64
import pathlib
import typing
from failure import Failure
from rest_client import json_request
from rest_client.env_file import read_env
from adf_codec.convert import Refused
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN")
# Seconds each connect and each read may wait.
TIMEOUT = 30
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
Http = typing.Callable[[str, str, str, object], object]
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
def basic_auth(env_file: pathlib.Path) -> str | Failure:
"""The Authorization header for the email and API token that env_file holds."""
values = read_env(env_file, KEYS, "an API token")
if isinstance(values, Failure):
return values
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
def jira_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, jira_errors)
def jira_errors(answer: object) -> str:
"""Jira's messages in the JSON of an error answer; empty where it holds none."""
if not isinstance(answer, dict):
return ""
messages, errors = answer.get("errorMessages"), answer.get("errors")
found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])]
return "; ".join(text for text in found if isinstance(text, str))
def confluence_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, confluence_errors)
def confluence_errors(answer: object) -> str:
"""Confluence's messages in the JSON of an error answer; empty where it holds none."""
errors = answer.get("errors") if isinstance(answer, dict) else None
found = [error.get("title") for error in errors if isinstance(error, dict)] if isinstance(errors, list) else [answer.get("message")] if isinstance(answer, dict) else []
return "; ".join(text for text in found if isinstance(text, str))