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

217 lines
13 KiB
Python

"""What every reader of Jira Cloud's REST API version 3 shares: a search read page by page, the key, fields, "is blocked by" links and property of each issue it finds, checked for their shape, and the transition that finishes an issue."""
import dataclasses
import re
import typing
from failure import Failure
from project_config.settings import Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
from atlassian.client import Http
from text_files.markdown_text import listed
ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)")
PAGE = 100
# The pages one read asks for at most, so an answer that never names a last page ends the read.
MAX_PAGES = 100
# The key of the status category Jira Cloud gives every done status.
DONE = "done"
# The hierarchyLevel of the epic issue type in the issue types Jira lists.
EPIC_LEVEL = 1
# How a Failure names an answer in which a field is missing or of another type.
SHAPE = "is not in the shape Jira Cloud's REST API version 3 documents"
# What a failed create ends with: a request Jira never answered, or answered brokenly, may still have filed the issue.
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {under} before filing it again"
# What a failed move ends with, for the same reason.
PERHAPS_MOVED = "unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again"
@dataclasses.dataclass(frozen=True)
class Link:
"""One "is blocked by" link of an issue."""
# The key of the issue that blocks.
blocker: str
# The link's own id, which Jira deletes it by.
id: str
@dataclasses.dataclass(frozen=True)
class Entry:
"""The key, fields, links and property of one issue a search finds, which every reader checks alike."""
key: str
# The entry's `fields`, from which each reader takes the ones it asked for.
fields: dict[str, typing.Any]
links: tuple[Link, ...]
# The issue property the search asked for; empty where the issue has none. A reader checks that it is a JSON object.
held: object
def entry_of(raw: object, property_: str) -> Entry | Failure:
"""The Entry of one issue a search finds, or which issue is not in the shape Jira documents, and how. property_ names the issue property the search asked for."""
key = raw.get("key") if isinstance(raw, dict) else None
if not isinstance(raw, dict) or not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
return Failure("the search answered an issue without an issue key")
# Each nested field is checked as Jira documents it; one missing or of another type ends the read here, as a Failure, so no later step meets it.
fields, properties = raw.get("fields"), raw.get("properties", {})
if not isinstance(fields, dict):
return Failure(f"{key} {SHAPE}: its fields are no object")
if not isinstance(properties, dict):
return Failure(f"{key} {SHAPE}: its properties are no object")
links = blocked_by_links(fields)
if isinstance(links, Failure):
return Failure(f"{key} {SHAPE}: {links.reason}")
return Entry(key, fields, links, properties.get(property_, {}))
def unshaped(key: str, failure: Exception) -> str:
"""Why the issue named key cannot be read, for a field that is missing or of another type than Jira documents."""
return f"{key} {SHAPE}: {failure!r}"
def offer_of(raw: object) -> tuple[str, str, str, str] | None:
"""One transition Jira offers, as its ID, its name, the name of the status it leads to and the key of that status's category; None where raw holds no such transition."""
to = raw.get("to") if isinstance(raw, dict) else None
category = to.get("statusCategory") if isinstance(to, dict) else None
if not isinstance(raw, dict) or not isinstance(to, dict) or not isinstance(category, dict):
return None
id_, name, status, key = raw.get("id"), raw.get("name"), to.get("name"), category.get("key")
return (id_, name, status, key) if isinstance(id_, str) and isinstance(name, str) and isinstance(status, str) and isinstance(key, str) else None
def offers_of(offered: object, key: str) -> list[tuple[str, str, str, str]] | Failure:
"""The transitions Jira offers the issue named key from its present status, each as offer_of answers one. A Failure where offered, Jira's answer, is in another shape."""
raw = offered.get("transitions") if isinstance(offered, dict) else None
found = [offer for each in raw if (offer := offer_of(each))] if isinstance(raw, list) else []
if not isinstance(raw, list) or len(found) != len(raw):
return Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")
return found
def status_category(issue: object) -> str | Failure:
"""The key of the category of the status in Jira's answer about one issue, or how the answer is not in the shape Jira documents."""
fields = issue.get("fields") if isinstance(issue, dict) else None
status = fields.get("status") if isinstance(fields, dict) else None
category = status.get("statusCategory") if isinstance(status, dict) else None
key = category.get("key") if isinstance(category, dict) else None
return key if isinstance(key, str) else Failure("its status category has no key that is text")
def finishing_transition(site: str, key: str, finish: Finish, authorization: str, http: Http) -> str | Failure:
"""The ID of the transition finish names, as Jira offers it now for the issue named key, which is a plan item or an epic; or why none of those offered finishes it."""
offered = http("GET", f"{site}/rest/api/3/issue/{key}/transitions", authorization, None)
if isinstance(offered, Failure):
return Failure(f"cannot read {key}'s transitions: {offered.reason}")
return transition_of(offered, key, finish)
def move_refusal(site: str, key: str, transition: str, finish: Finish, authorization: str, http: Http) -> str | None:
"""Moves the issue named key by the transition with the ID transition, which finishing_transition answered for finish. Why Jira did not take the move; None where it did."""
moved = http("POST", f"{site}/rest/api/3/issue/{key}/transitions", authorization, {"transition": {"id": transition}})
return f"cannot move {key} by {finish.transition!r}: {moved.reason}" if isinstance(moved, Failure) else None
def transition_of(offered: object, key: str, finish: Finish) -> str | Failure:
"""The ID of the transition finish names, among those Jira offered for the issue named key, which are the ones its present status has; or why none of them finishes the item."""
found = offers_of(offered, key)
if isinstance(found, Failure):
return found
named = [each for each in found if each[1] == finish.transition]
if not named:
others = " and ".join(f"{name!r} to {status!r}" for _, name, status, _ in found)
return Failure(f"{key} has no transition {finish.transition!r} from its status, " + (f"only {others}: move the issue in Jira to a status that has it, or name in `{JIRA_FINISH_TRANSITION}` one that leads to a done status" if found else "nor any other the account may make"))
id_, _, status, category = next((each for each in named if each[2] == finish.status), named[0])
if status != finish.status:
return Failure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, not to {finish.status!r}, which `{JIRA_FINISH_STATUS}` names")
# `children` reads an issue as finished by its status's category, so a move to any other category would leave the item in the plan.
if category != DONE:
return Failure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, which Jira doesn't count as done, so the item would stay in the plan: name a transition to a done status")
return id_
def issue_types_of(site: str, project: str, authorization: str, http: Http) -> list[dict[str, typing.Any]] | Failure:
"""The issue types Jira lists for the project, each with a name, or why it listed none."""
answered = http("GET", f"{site}/rest/api/3/issue/createmeta/{project}/issuetypes", authorization, None)
if isinstance(answered, Failure):
return Failure(f"cannot read {project}'s issue types: {answered.reason}")
types = answered.get("issueTypes") if isinstance(answered, dict) else None
if not isinstance(types, list) or not all(isinstance(each, dict) and isinstance(each.get("name"), str) for each in types):
return Failure(f"Jira answered {project}'s issue types in a shape its REST API version 3 doesn't document")
return types
def issue_type_refusal(site: str, project: str, kind: str, setting: str, authorization: str, http: Http) -> str | None:
"""Why the project can't file a new issue under an epic as the type named kind, which the setting `setting` names; None where it can."""
types = issue_types_of(site, project, authorization, http)
if isinstance(types, Failure):
return types.reason
# An issue under an epic is a standard one: Jira refuses a sub-task there, and an epic under an epic.
names: list[str] = [each["name"] for each in types if each.get("subtask") is not True and each.get("hierarchyLevel") != EPIC_LEVEL]
if kind in names:
return None
return f"{project} has no issue type {kind!r} for an issue under an epic; " + (f"it has {listed(names, 'and')}: name one in `{setting}`" if names else "it has no other type for one")
def project_of(key: str) -> str:
"""The key of the Jira project an issue key lies in."""
return key.rpartition("-")[0]
def edit_issue(site: str, key: str, body: dict[str, typing.Any], authorization: str, http: Http) -> None | Failure:
"""Sends body, an edit of the issue named key, and returns None, or the Failure of the request that failed. An edit that holds fields or update goes in one request, with its properties. Jira refuses an edit that holds neither, so such an edit sets each property through the property's own endpoint, one request each, and stops at the first that fails."""
if "fields" in body or "update" in body:
answer = http("PUT", f"{site}/rest/api/3/issue/{key}", authorization, body)
return answer if isinstance(answer, Failure) else None
for entry in body.get("properties", []):
answer = http("PUT", f"{site}/rest/api/3/issue/{key}/properties/{entry['key']}", authorization, entry["value"])
if isinstance(answer, Failure):
return answer
return None
def rank_refusal(site: str, key: str, before: str, authorization: str, http: Http) -> str | None:
"""Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors."""
answer = http("PUT", f"{site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before})
if isinstance(answer, Failure):
return answer.reason
entries = answer.get("entries") if isinstance(answer, dict) else None
refused = [entry for entry in entries if isinstance(entry, dict) and entry.get("status") != 200] if isinstance(entries, list) else []
return "; ".join(str(error) for entry in refused for error in entry.get("errors") or [f"Jira answered {entry.get('status')}"]) or None
def searched(site: str, what: str, jql: str, asked: dict[str, object], authorization: str, http: Http, max_pages: int = MAX_PAGES) -> list[object] | Failure:
"""Every issue a JQL search on site finds, page by page, up to max_pages pages. The dict asked holds the request's `fields` and `properties` lists. The text what names the issues sought, in the Failure of a search that doesn't end."""
body: dict[str, object] = {"jql": jql, "maxResults": PAGE} | asked
found: list[object] = []
for _ in range(max_pages):
page = http("POST", f"{site}/rest/api/3/search/jql", authorization, body)
if isinstance(page, Failure):
return page
if not isinstance(page, dict) or not isinstance(page.get("issues"), list):
return Failure("the search answered something other than a page of issues")
found += page["issues"]
if not page.get("nextPageToken"):
return found
body = body | {"nextPageToken": page["nextPageToken"]}
return Failure(f"the search for {what} did not end within {max_pages} pages")
def blocked_by_links(fields: dict[str, typing.Any]) -> tuple[Link, ...] | Failure:
"""The "is blocked by" links among an issue's `issuelinks` field, or how that field is not in the shape Jira documents."""
listed = fields.get("issuelinks")
if not isinstance(listed, list):
return Failure("its issuelinks are no list")
found = []
for link in listed:
if not isinstance(link, dict):
return Failure("its issuelinks hold a link that is no object")
if "inwardIssue" not in link:
continue
kind = link.get("type")
if not isinstance(kind, dict) or not isinstance(kind.get("inward"), str):
return Failure("its issuelinks hold a link whose type names no inward text")
if kind["inward"] != "is blocked by":
continue
blocker, id_ = link["inwardIssue"], link.get("id")
if not isinstance(blocker, dict) or not isinstance(blocker.get("key"), str) or not isinstance(id_, str):
return Failure("its issuelinks hold a link whose id or whose linked issue's key is no text")
found.append(Link(blocker["key"], id_))
return tuple(found)