"""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 plan_store.jira_epic import BLOCKS, FILED_BY, scores as held_scores, PROPERTY from project_config.settings import DEFAULT_ISSUE_TYPE, Epic, Finish, JIRA_FINDING_TYPE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_REVIEW_TYPE from atlassian.jira import DONE, edit_issue, entry_of, finishing_transition, ISSUE_KEY, issue_type_refusal, issue_types_of, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, SHAPE, status_category, unshaped from do_epic.backend.protocol import EpicIssue, no_blocker, no_child, no_parent, no_scores, no_words, unfit, unfit_label from failure import Failure from do_epic.backend.jira_status import moved_by, moved_to from plan.todo_table import MOVES from do_epic.repo_pick import REVIEW_LABEL from do_epic.backend.jira_start import Start, started FIELDS = ["summary", "description", "labels", "assignee", "status", "parent", "issuelinks"] # How many child issues one search for sub-tasks names, which keeps its JQL well inside the length Jira takes. PARENTS_PER_SEARCH = 50 NO_FINISH = "do-epic's settings name no transition to {to} by: set `{transition}` and `{status}` in ~/.claude-projects/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"" @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. finish says how the epic itself closes; None where the machine's settings don't say.""" epic: Epic env_file: pathlib.Path http: Http = jira_json to_markdown: ToMarkdown = adfs_to_markdown to_adf: ToAdf = markdown_to_adf finish: Finish | None = None # The pages a search may take before the read fails. max_pages: int = MAX_PAGES # The issue types that a finding, and a release review (an issue labelled REVIEW_LABEL), are filed as. finding_type: str = DEFAULT_ISSUE_TYPE review_type: str = DEFAULT_ISSUE_TYPE start: Start = Start() @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, ...], blocked_by: str | None = None) -> 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) or (self.not_a_blocker(blocked_by, authorization) if blocked_by is not None else None): return refused fields: dict[str, typing.Any] = {"project": {"key": project_of(parent)}, "parent": {"key": parent}, "summary": summary, "labels": list(labels)} # Marks the issue as the loop's, as plan_store marks the items it files. properties = [{"key": PROPERTY, "value": {FILED_BY[0]: FILED_BY[1]}}] kind = self.child_type(project_of(parent), REVIEW_LABEL in labels, authorization) 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 body: dict[str, typing.Any] = {"fields": fields | {"issuetype": kind}, "properties": properties} if blocked_by is not None: # Linked as it is created, so no issue is left filed and unblocked. The inward issue blocks the new one. body["update"] = {"issuelinks": [{"add": {"type": {"name": BLOCKS}, "inwardIssue": {"key": blocked_by}}}]} created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, body) if isinstance(created, Failure): return Failure(f"cannot file the issue under {parent}: {created.reason}; {PERHAPS_FILED.format(under=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(under=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, "labelled") 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 rank(self, key: str, before: str) -> None | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization refused = rank_refusal(self.epic.site, key, before, authorization, self.http) return Failure(refused) if refused else None def comment(self, key: str, text: str) -> None | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization if refused := no_words(text): return refused above = self.parent_of(key, authorization, "to comment on it") if isinstance(above, Failure): return above if above != self.epic_key: return no_child(self.epic_key, key, "commented on") body = self.to_adf(text) if isinstance(body, Failure): return Failure(f"cannot convert the comment to a Jira comment: {body.reason}") posted = self.http("POST", f"{self.epic.site}/rest/api/3/issue/{key}/comment", authorization, {"body": body}) return Failure(f"cannot comment on {key}: {posted.reason}") if isinstance(posted, Failure) else None def closed(self) -> bool | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{self.epic_key}?fields=status", authorization, None) if isinstance(answered, Failure): return Failure(f"cannot read {self.epic_key}'s status: {answered.reason}") category = status_category(answered) if isinstance(category, Failure): return Failure(f"{self.epic_key}'s status {SHAPE}: {category.reason}") return category == DONE def close(self, summary: str) -> None | Failure: if self.finish is None: return Failure(NO_FINISH.format(to="close an epic", transition=JIRA_FINISH_TRANSITION, status=JIRA_FINISH_STATUS)) authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization if refused := no_words(summary): return refused body = self.to_adf(summary) if isinstance(body, Failure): return Failure(f"cannot convert the summary to a Jira comment: {body.reason}") # The transition is read before the comment is posted, so an epic that cannot move gets no summary. transition = finishing_transition(self.epic.site, self.epic_key, self.finish, authorization, self.http) if isinstance(transition, Failure): return transition posted = self.http("POST", f"{self.epic.site}/rest/api/3/issue/{self.epic_key}/comment", authorization, {"body": body}) if isinstance(posted, Failure): return Failure(f"cannot comment on {self.epic_key}: {posted.reason}") refused_move = move_refusal(self.epic.site, self.epic_key, transition, self.finish, authorization, self.http) return Failure(f"posted the summary on {self.epic_key}, but {refused_move}; close the epic in Jira rather than posting the summary again") if refused_move else None def set_scores(self, key: str, scores: dict[str, int], moves: str, comment: str) -> None | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization if refused := no_words(comment): return refused if not ISSUE_KEY.fullmatch(key): return no_child(self.epic_key, key, "scored") answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{key}?fields=parent&properties={PROPERTY}", authorization, None) if isinstance(answered, Failure): return Failure(f"cannot read {key} to score it: {answered.reason}") found = held_of(key, answered) if isinstance(found, Failure): return found above, held = found # A sub-task is no child of the epic but its parent is, so a sub-task's parent is read too. grand = self.parent_of(above, authorization, "to score its sub-task") if above not in (None, self.epic_key) else None if isinstance(grand, Failure): return grand if above is None or (above != self.epic_key and grand != self.epic_key): return no_child(self.epic_key, key, "scored") read = held_scores(key, held) fields = read if isinstance(read, Failure) else no_scores(key, scores, moves, read.scores) body = fields if isinstance(fields, Failure) else self.to_adf(comment) if isinstance(body, Failure): return Failure(f"cannot score {key}: {body.reason}") # The comment goes first: an issue that holds scores is never scored again, so scores set without it would leave the team untold for good. posted = self.http("POST", f"{self.epic.site}/rest/api/3/issue/{key}/comment", authorization, {"body": body}) if isinstance(posted, Failure): return Failure(f"cannot comment on {key} to tell its team the scores: {posted.reason}") put = edit_issue(self.epic.site, key, {"properties": [{"key": PROPERTY, "value": held | scores | {MOVES: moves}}]}, authorization, self.http) return Failure(f"the comment on {key} tells its team the scores, but they could not be set, so the next run scores it again: {put.reason}") if isinstance(put, Failure) else None def start_issue(self, key: str) -> str | None | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization within = self.within(key, authorization, "start", "started") if isinstance(within, Failure): return within # Jira keeps a sub-task in its parent's sprint, so the parent joins the sprint in its place. return started(self.epic.site, key, key if within[0] == self.epic_key else within[0], self.start, authorization, self.http) def move_issue(self, key: str, status: str) -> None | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization within = self.within(key, authorization, "move", "moved") return within if isinstance(within, Failure) else moved_to(self.epic.site, key, status, authorization, self.http) def move_issue_by(self, key: str, transition: str, to: tuple[str, ...]) -> str | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization within = self.within(key, authorization, "move", "moved") return within if isinstance(within, Failure) else moved_by(self.epic.site, key, transition, to, authorization, self.http) def finish_issue(self, key: str) -> None | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization within = self.within(key, authorization, "finish", "finished") if isinstance(within, Failure): return within if within[1]: return None if self.finish is None: return Failure(NO_FINISH.format(to="finish an issue", transition=JIRA_FINISH_TRANSITION, status=JIRA_FINISH_STATUS)) transition = finishing_transition(self.epic.site, key, self.finish, authorization, self.http) if isinstance(transition, Failure): return transition refused = move_refusal(self.epic.site, key, transition, self.finish, authorization, self.http) return Failure(f"{refused}; {PERHAPS_MOVED.format(key=key)}") if refused else None def within(self, key: str, authorization: str, do: str, done_to_it: str) -> tuple[str, bool] | Failure: """The key of key's parent and whether key's status is a done one, where key names a child issue of the epic or a sub-task of one; any other key is refused. do and done_to_it say what was asked of key, such as "finish" and "finished".""" placed = self.placed(key, authorization, f"to {do} it") if isinstance(placed, Failure): return placed above, done = placed # A sub-task is no child of the epic but its parent is, so a sub-task's parent is read too. grand = self.parent_of(above, authorization, f"to {do} its sub-task") if above not in (None, self.epic_key) else None if isinstance(grand, Failure): return grand if above is None or (above != self.epic_key and grand != self.epic_key): return no_child(self.epic_key, key, done_to_it) return above, done 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 not_a_blocker(self, blocker: str, authorization: str) -> Failure | None: """Why nothing can be filed blocked by blocker; None where it is a child issue of the epic or a sub-task of one.""" above = self.parent_of(blocker, authorization, "to file blocked by it") if isinstance(above, Failure): return above if above == self.epic_key: return None grand = None if above is None else self.parent_of(above, authorization, "to file blocked by it") return grand if isinstance(grand, Failure) else None if grand == self.epic_key else no_blocker(self.epic_key, blocker) 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 ".""" placed = self.placed(key, authorization, why) return placed if isinstance(placed, Failure) else placed[0] def placed(self, key: str, authorization: str, why: str) -> tuple[str | None, bool] | Failure: """The key of key's parent issue, None where key isn't an issue key or has no parent, and whether key's own status is a done one. A failed read says "cannot read ".""" if not ISSUE_KEY.fullmatch(key): return None, False # 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,status", 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 status = fields.get("status") if isinstance(fields, dict) else None category = status.get("statusCategory") if isinstance(status, dict) else None return (above.get("key") if isinstance(above, dict) and isinstance(above.get("key"), str) else None), isinstance(category, dict) and category.get("key") == DONE 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, "properties": [PROPERTY]}, authorization, self.http, self.max_pages) 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 child_type(self, project: str, review: bool, authorization: str) -> dict[str, str] | Failure: """The issue type of a new child of the epic, which is the type of a release review where review is true, else of a finding; or why the project can't file that type.""" name = self.review_type if review else self.finding_type refused = issue_type_refusal(self.epic.site, project, name, JIRA_REVIEW_TYPE if review else JIRA_FINDING_TYPE, authorization, self.http) return Failure(refused) if refused else {"name": name} 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.""" types = issue_types_of(self.epic.site, project, authorization, self.http) if isinstance(types, Failure): return types found = next((kind["id"] for kind in types if 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 held_of(key: str, answered: object) -> tuple[str | None, dict[str, typing.Any]] | Failure: """The key of the parent, None where it has none, and the value of PROPERTY, empty where it holds none, in Jira's answer for the issue named key.""" fields = answered.get("fields") if isinstance(answered, dict) else None properties = answered.get("properties") if isinstance(answered, dict) else None above = fields.get("parent") if isinstance(fields, dict) else None held = properties.get(PROPERTY, {}) if isinstance(properties, dict) else {} if not isinstance(held, dict): return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object") return (above.get("key") if isinstance(above, dict) and isinstance(above.get("key"), str) else None), held 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.""" entry = entry_of(raw, PROPERTY) if isinstance(entry, Failure): return entry key, fields, held = entry.key, entry.fields, entry.held blockers = tuple(link.blocker for link in entry.links) try: 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(unshaped(key, failure)) texts = (summary, *labels, state, parent, *blockers) 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 all(ISSUE_KEY.fullmatch(each) for each in (parent, *blockers)) 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, description or a linked issue's key holds another kind of value") if not isinstance(held, dict): return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object") read = held_scores(key, held) if isinstance(read, Failure): return read return Found(EpicIssue(key, summary.strip(), "", tuple(sorted(labels)), name, state, done, parent, read.scores, read.moves, read.exempt, blockers, held.get(FILED_BY[0]) == FILED_BY[1]), description)