161 lines
9.2 KiB
Python
161 lines
9.2 KiB
Python
"""What every reader of Jira Cloud's REST API version 3 shares: a search read page by page, the head of each entry it answers, an issue's "is blocked by" links, 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
|
|
|
|
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"
|
|
# 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.
|
|
SHAPE = "is not in the shape Jira Cloud's REST API version 3 documents"
|
|
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 head of one entry of a search's answer, 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 head of one entry of a search's answer, 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 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."""
|
|
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")
|
|
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 project_of(key: str) -> str:
|
|
"""The key of the Jira project an issue key lies in."""
|
|
return key.rpartition("-")[0]
|
|
|
|
|
|
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)
|