"""An epic's plan kept as a Jira Cloud epic's child issues and their sub-tasks, read and filed over Jira's REST API version 3.""" import dataclasses import pathlib import typing from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown from project_config.settings import Epic from do_epic.backend.protocol import EpicIssue, no_child, no_parent, unfit, unfit_label from failure import Failure from plan_store.jira_epic import ISSUE_KEY, ISSUE_TYPE, project_of, searched FIELDS = ["summary", "description", "labels", "assignee", "status", "parent"] # How many child issues one search for sub-tasks names, which keeps its JQL well inside the length Jira takes. PARENTS_PER_SEARCH = 50 PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {parent} before filing it again" @dataclasses.dataclass(frozen=True) class Found: """An issue as Jira answered it, its description still in Jira's document format.""" issue: EpicIssue description: dict[str, typing.Any] | None @dataclasses.dataclass(frozen=True) class JiraEpic: """The issues of a Jira epic, read and filed with the credentials env_file holds.""" epic: Epic env_file: pathlib.Path http: Http = jira_json to_markdown: ToMarkdown = adfs_to_markdown to_adf: ToAdf = markdown_to_adf @property def epic_key(self) -> str: return self.epic.key def read(self) -> list[EpicIssue] | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization found = self.found(authorization) if isinstance(found, Failure): return found # A container run converts every description at once. It comes after every other check, since a read that fails doesn't need it. described = [each for each in found if each.description is not None] texts = self.to_markdown([each.description for each in described if each.description is not None]) if isinstance(texts, Refused): return Failure(f"{described[texts.index].issue.key}'s description: {texts.failure.reason}") if isinstance(texts, Failure): return Failure(f"cannot convert the descriptions of {self.epic_key}'s issues to markdown: {texts.reason}") details = {each.issue.key: text.strip() for each, text in zip(described, texts)} return [dataclasses.replace(each.issue, detail=details.get(each.issue.key, "")) for each in found] def file(self, parent: str, summary: str, detail: str, labels: tuple[str, ...]) -> str | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization if refused := unfit(summary, labels) or self.not_a_parent(parent, authorization): return refused fields: dict[str, typing.Any] = {"project": {"key": project_of(parent)}, "parent": {"key": parent}, "summary": summary, "labels": list(labels)} kind = {"name": ISSUE_TYPE} if parent == self.epic_key else self.sub_task_type(project_of(parent), authorization) if isinstance(kind, Failure): return kind if detail.strip(): description = self.to_adf(detail) if isinstance(description, Failure): return Failure(f"cannot convert the detail to a Jira description: {description.reason}") fields["description"] = description created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": fields | {"issuetype": kind}}) if isinstance(created, Failure): return Failure(f"cannot file the issue under {parent}: {created.reason}; {PERHAPS_FILED.format(parent=parent)}") key = created.get("key") if isinstance(created, dict) else None if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key): return Failure(f"Jira answered the new issue without an issue key; {PERHAPS_FILED.format(parent=parent)}") return key def add_label(self, key: str, label: str) -> None | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization if refused := unfit_label(label): return refused above = self.parent_of(key, authorization, "to label it") if isinstance(above, Failure): return above if above != self.epic_key: return no_child(self.epic_key, key) edited = self.http("PUT", f"{self.epic.site}/rest/api/3/issue/{key}", authorization, {"update": {"labels": [{"add": label}]}}) return Failure(f"cannot label {key}: {edited.reason}") if isinstance(edited, Failure) else None def not_a_parent(self, parent: str, authorization: str) -> Failure | None: """Why nothing can be filed under parent; None where it is the epic or one of its child issues.""" if parent == self.epic_key: return None above = self.parent_of(parent, authorization, "to file under it") return above if isinstance(above, Failure) else None if above == self.epic_key else no_parent(self.epic_key, parent) def parent_of(self, key: str, authorization: str, why: str) -> str | None | Failure: """The key of key's parent issue; None where key isn't an issue key or has no parent. A failed read says "cannot read ".""" if not ISSUE_KEY.fullmatch(key): return None # A search may not show an issue filed a moment ago, so the issue is asked for by its key. answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{key}?fields=parent", authorization, None) if isinstance(answered, Failure): return Failure(f"cannot read {key} {why}: {answered.reason}") fields = answered.get("fields") if isinstance(answered, dict) else None above = fields.get("parent") if isinstance(fields, dict) else None return above.get("key") if isinstance(above, dict) and isinstance(above.get("key"), str) else None def found(self, authorization: str) -> list[Found] | Failure: """Each child issue, each followed by its sub-tasks.""" # The search answers no issues for an epic the account cannot see; asking for the epic itself tells that from an epic without children. seen = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{self.epic_key}?fields=summary", authorization, None) if isinstance(seen, Failure): return Failure(f"cannot read the epic {self.epic_key}: {seen.reason}") children = self.searched(f"{self.epic_key}'s child issues", (self.epic_key,), authorization) if isinstance(children, Failure): return children keys = [each.issue.key for each in children] tasks: list[Found] = [] for start in range(0, len(keys), PARENTS_PER_SEARCH): batch = self.searched(f"the sub-tasks of {self.epic_key}'s child issues", tuple(keys[start:start + PARENTS_PER_SEARCH]), authorization) if isinstance(batch, Failure): return batch tasks += batch return [each for child in children for each in (child, *(task for task in tasks if task.issue.parent == child.issue.key))] def searched(self, what: str, parents: tuple[str, ...], authorization: str) -> list[Found] | Failure: """The issues whose parent is one of parents, in rank order.""" named = ", ".join(f'"{key}"' for key in parents) answered = searched(self.epic.site, what, f"parent in ({named}) ORDER BY Rank ASC", {"fields": FIELDS}, authorization, self.http) if isinstance(answered, Failure): return answered found = [found_of(raw) for raw in answered] return next((each for each in found if isinstance(each, Failure)), None) or [each for each in found if isinstance(each, Found)] def sub_task_type(self, project: str, authorization: str) -> dict[str, str] | Failure: """The project's sub-task issue type, by id, since sites name it differently, such as Subtask or Sub-task.""" answered = self.http("GET", f"{self.epic.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): return Failure(f"Jira answered {project}'s issue types in a shape its REST API version 3 doesn't document") found = next((kind["id"] for kind in types if isinstance(kind, dict) and kind.get("subtask") is True and isinstance(kind.get("id"), str)), None) return Failure(f"{project} has no sub-task issue type; turn sub-tasks on in Jira") if found is None else {"id": found} def found_of(raw: object) -> Found | Failure: """The issue in one entry of a search's answer, or which issue is not in the shape Jira documents.""" 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") # The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here. try: fields = raw["fields"] summary, labels, assignee, status, parent, description = fields["summary"], fields["labels"], fields["assignee"], fields["status"], fields["parent"]["key"], fields["description"] name = assignee["displayName"] if assignee is not None else None state, done = status["name"], status["statusCategory"]["key"] == "done" except (AttributeError, KeyError, TypeError) as failure: return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}") texts = (summary, *labels, state, parent) if isinstance(labels, list) else () if not texts or not all(isinstance(text, str) for text in texts) or not isinstance(name, str | None) or not ISSUE_KEY.fullmatch(parent) or not isinstance(description, dict | None): return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its summary, labels, assignee, status, parent or description holds another kind of value") return Found(EpicIssue(key, summary.strip(), "", tuple(sorted(labels)), name, state, done, parent), description)