486 lines
29 KiB
Python
486 lines
29 KiB
Python
"""A plan kept as the child issues of one Jira Cloud epic, read, filed into, edited and finished over Jira's REST API.
|
|
|
|
An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a person filed holds none, and reads as an item without scores.
|
|
|
|
`add` files an item as a new child issue, marked with FILED_BY, and ranks it among the issues the loop filed, by the score the config's formula gives, as `placing` says. `finish` moves an item's issue to a done status. `edit` changes an issue the loop filed, and its links to the epic's other open items. Of an issue a person filed it sets only the scores, with a comment that tells the team why."""
|
|
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.todo_table import BLOCKED_BY, Item, item_fields, ItemFields, MOVES, SHAPE
|
|
from plan_store.markdown_edits import bold_cell, plain, unfit_text
|
|
from plan_store.plans import cells, no_item, Plan, Written
|
|
from atlassian.jira import entry_of, finishing_transition, ISSUE_KEY, Link, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped
|
|
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
|
|
from failure import Failure
|
|
from plan.release import parsed, Release, tagged
|
|
from plan import ranking
|
|
|
|
# The issue property that holds an item's scores, as a JSON object such as {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}.
|
|
PROPERTY = "plan-item"
|
|
# The key in PROPERTY's value that marks an issue the loop filed, and its value. An edit of an issue without it, which a person filed, writes only PROPERTY and a comment.
|
|
FILED_BY = ("Filed by", "loop")
|
|
# The issue type of an issue the loop files, which Jira Software's project templates all have; a project without it refuses the issue, saying so.
|
|
ISSUE_TYPE = "Task"
|
|
# The name of the link type whose inward side reads "is blocked by", as Jira Cloud ships it.
|
|
BLOCKS = "Blocks"
|
|
SECURITY = "security"
|
|
# What a failed edit ends with, for the same reason.
|
|
PERHAPS_EDITED = "unless Jira refused the request, the issue may have changed: look at {key} before editing the item again"
|
|
# The scores a caller sets, L, E, I and S; R is worked out from them.
|
|
SET_SCORES = tuple(name for name in SHAPE.score_columns if name not in SHAPE.derived)
|
|
# The fields of PROPERTY's value that an edit may set.
|
|
SCORED = (*SET_SCORES, MOVES, "Exempt")
|
|
|
|
|
|
class ReadsScoring(typing.Protocol):
|
|
def read(self) -> ranking.Scoring | Failure:
|
|
"""The scoring `add` scores an item by: the config's formula and bar, with the goal weights that the goals file, the decision log and the comprehension history give."""
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Issue:
|
|
"""A child issue as Jira answered it, checked to hold what an item is read from."""
|
|
key: str
|
|
summary: str
|
|
description: dict[str, typing.Any] | None
|
|
fix_versions: tuple[str, ...]
|
|
# The issue's "is blocked by" links, one per blocker unless Jira holds a link twice.
|
|
links: tuple[Link, ...]
|
|
# PROPERTY's value; an empty object where the issue holds none.
|
|
scores: dict[str, typing.Any]
|
|
|
|
@property
|
|
def number(self) -> int:
|
|
return number(self.key)
|
|
|
|
@property
|
|
def blockers(self) -> tuple[str, ...]:
|
|
return tuple(link.blocker for link in self.links)
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class JiraPlan:
|
|
"""The plan under epic, read and written 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
|
|
# How a finished item moves; None where the config doesn't say, and then `finish` is a Failure.
|
|
finish_by: Finish | None = None
|
|
# The pages a search may take before the read fails.
|
|
max_pages: int = MAX_PAGES
|
|
# How add scores an item: by the config's formula and bar, with the goal weights the project's records give.
|
|
scoring: ReadsScoring = dataclasses.field(kw_only=True)
|
|
|
|
@property
|
|
def label(self) -> str:
|
|
return self.epic.spelling
|
|
|
|
@property
|
|
def tracked(self) -> str | None:
|
|
return None
|
|
|
|
def read(self) -> Plan | Failure:
|
|
authorization = basic_auth(self.env_file)
|
|
if isinstance(authorization, Failure):
|
|
return authorization
|
|
answered = children(self.epic, authorization, self.http, self.max_pages)
|
|
if isinstance(answered, Failure):
|
|
return answered
|
|
issues = [issue_of(raw) for raw in answered]
|
|
return next((issue for issue in issues if isinstance(issue, Failure)), None) or plan_of([issue for issue in issues if isinstance(issue, Issue)], self.epic, self.to_markdown)
|
|
|
|
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
|
|
"""Files the item as a child issue, where it scores at the config's bar or above or is exempt, and ranks it as `placing` says.
|
|
|
|
Jira takes the links and the rank after the issue. One it refuses leaves the issue filed, so the write counts as landed, and a note says what to do by hand."""
|
|
filing = filing_of(fields, detail, self.epic)
|
|
if isinstance(filing, Failure):
|
|
return filing
|
|
scoring = self.scoring.read()
|
|
if isinstance(scoring, Failure):
|
|
return Failure(f"cannot score the item to file: {scoring.reason}")
|
|
value = filed_score(filing.item, scoring)
|
|
if isinstance(value, Failure):
|
|
return value
|
|
authorization = basic_auth(self.env_file)
|
|
if isinstance(authorization, Failure):
|
|
return authorization
|
|
description = self.description_of(detail)
|
|
if isinstance(description, Failure):
|
|
return description
|
|
issue_fields = filing.fields | ({"description": description} if description else {})
|
|
version = self.fix_version(filing.release, authorization)
|
|
if isinstance(version, Failure):
|
|
return version
|
|
answered = children(self.epic, authorization, self.http, self.max_pages)
|
|
if isinstance(answered, Failure):
|
|
return answered
|
|
if missing := missing_blocker(filing.blockers, keys_of(answered), self.label):
|
|
return missing
|
|
before = placing(answered, filing.item, value, scoring)
|
|
created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": issue_fields | {"fixVersions": [{"name": version}]}, "properties": [{"key": PROPERTY, "value": filing.scores}]})
|
|
if isinstance(created, Failure):
|
|
return Failure(f"cannot file the item under {self.epic.key}: {created.reason}; {PERHAPS_FILED.format(under=self.epic.key)}")
|
|
key = created.get("key") if isinstance(created, dict) else None
|
|
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key) or project_of(key) != project_of(self.epic.key):
|
|
return Failure(f"Jira answered the new issue without an issue key in {project_of(self.epic.key)}; {PERHAPS_FILED.format(under=self.epic.key)}")
|
|
return Written(number(key), self.linked_and_ranked(key, filing.blockers, before, authorization))
|
|
|
|
def linked_and_ranked(self, key: str, blockers: tuple[str, ...], before: str | None | Failure, authorization: str) -> tuple[str, ...]:
|
|
"""Links the filed issue named key as blocked by each of blockers, and ranks it just before the issue named before; a note for each Jira refuses."""
|
|
notes = []
|
|
for blocker in blockers:
|
|
if isinstance(linked := self.link(key, blocker, authorization), Failure):
|
|
notes.append(f"filed {key}, but cannot link it as blocked by {blocker}: {linked.reason}; link it in Jira")
|
|
if isinstance(before, Failure):
|
|
notes.append(f"filed {key}, but cannot rank it: {before.reason}; rank it in Jira")
|
|
elif before is not None and (refused := rank_refusal(self.epic.site, key, before, authorization, self.http)):
|
|
notes.append(f"filed {key}, but cannot rank it before {before}: {refused}; rank it in Jira")
|
|
return tuple(notes)
|
|
|
|
def link(self, key: str, blocker: str, authorization: str) -> object:
|
|
"""Links the issue named key as blocked by the issue named blocker; a Failure where Jira refuses."""
|
|
# Jira names the two ends by the link type's sides: the inward issue blocks the outward one, which then reads "is blocked by" it.
|
|
return self.http("POST", f"{self.epic.site}/rest/api/3/issueLink", authorization, {"type": {"name": BLOCKS}, "inwardIssue": {"key": blocker}, "outwardIssue": {"key": key}})
|
|
|
|
def relinked(self, issue: Issue, wanted: tuple[str, ...] | None, open_keys: set[object], authorization: str) -> tuple[str, ...]:
|
|
"""Makes issue blocked by exactly the open children named in wanted: a link for each that it lacks, and a deletion of each link to an open child that wanted drops. A link to any other issue stays, since the team may have made it. None for wanted leaves every link as it is. A note for each request Jira refuses."""
|
|
if wanted is None:
|
|
return ()
|
|
notes = []
|
|
for blocker in (blocker for blocker in wanted if blocker not in issue.blockers):
|
|
if isinstance(linked := self.link(issue.key, blocker, authorization), Failure):
|
|
notes.append(f"edited {issue.key}, but cannot link it as blocked by {blocker}: {linked.reason}; link it in Jira")
|
|
for link in (link for link in issue.links if link.blocker in open_keys and link.blocker not in wanted):
|
|
if isinstance(deleted := self.http("DELETE", f"{self.epic.site}/rest/api/3/issueLink/{link.id}", authorization, None), Failure):
|
|
notes.append(f"edited {issue.key}, but cannot delete the link that makes it blocked by {link.blocker}: {deleted.reason}; delete it in Jira")
|
|
return tuple(notes)
|
|
|
|
def fix_version(self, release: str, authorization: str) -> str | Failure:
|
|
"""The name of the Jira project's Fix Version for release, which a project may spell with a leading v, as `earliest_release` reads it."""
|
|
project = project_of(self.epic.key)
|
|
versions = self.http("GET", f"{self.epic.site}/rest/api/3/project/{project}/versions", authorization, None)
|
|
if isinstance(versions, Failure):
|
|
return Failure(f"cannot read {project}'s Fix Versions: {versions.reason}")
|
|
names = {name for version in versions if isinstance(version, dict) and isinstance(name := version.get("name"), str)} if isinstance(versions, list) else set()
|
|
return next((name for name in (release, f"v{release}") if name in names), None) or Failure(f"the Jira project {project} has no Fix Version {release} or v{release}; create it in Jira, or name a release it has")
|
|
|
|
def child(self, id_: int, authorization: str) -> dict[str, typing.Any] | Failure:
|
|
"""Item id_'s issue, as the epic's open children answer it; a Failure where none of them is item id_."""
|
|
answered = children(self.epic, authorization, self.http, self.max_pages)
|
|
return answered if isinstance(answered, Failure) else self.child_in(answered, id_)
|
|
|
|
def child_in(self, answered: list[object], id_: int) -> dict[str, typing.Any] | Failure:
|
|
"""Item id_'s issue among the epic's open children; a Failure where none of them is item id_."""
|
|
key = f"{project_of(self.epic.key)}-{id_}"
|
|
found = next((raw for raw in answered if isinstance(raw, dict) and raw.get("key") == key), None)
|
|
return Failure(no_item(self.label, id_)) if found is None else found
|
|
|
|
def description_of(self, detail: str) -> dict[str, typing.Any] | None | Failure:
|
|
"""The Jira description that holds detail, as ADF; None for a blank detail, which leaves an issue without one."""
|
|
if not detail.strip():
|
|
return None
|
|
description = self.to_adf(detail)
|
|
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}") if isinstance(description, Failure) else description
|
|
|
|
def shows(self, issue: Issue, detail: str) -> bool:
|
|
"""Whether detail is the issue's description as a read shows it. An edit leaves such a description as Jira holds it, since converting the markdown back would drop each block's localId and Jira's spacing paragraphs."""
|
|
if issue.description is None:
|
|
return not detail.strip()
|
|
texts = self.to_markdown([issue.description])
|
|
return isinstance(texts, list) and texts[0].strip() == detail.strip()
|
|
|
|
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
|
|
"""Sets the fields and the detail in one request, so Jira takes all of those or none, then changes the issue's links one request at a time, and then posts comment on the issue. `revision_of` says what an edit may set.
|
|
|
|
A link change or a comment Jira refuses leaves the edit made, so the write counts as landed, and a note says what to do by hand."""
|
|
authorization = basic_auth(self.env_file)
|
|
if isinstance(authorization, Failure):
|
|
return authorization
|
|
answered = children(self.epic, authorization, self.http, self.max_pages)
|
|
if isinstance(answered, Failure):
|
|
return answered
|
|
raw = self.child_in(answered, id_)
|
|
if isinstance(raw, Failure):
|
|
return raw
|
|
issue = issue_of(raw)
|
|
if isinstance(issue, Failure):
|
|
return issue
|
|
key = issue.key
|
|
revision = revision_of(issue, cells(fields), detail, comment)
|
|
if isinstance(revision, Failure):
|
|
return revision
|
|
open_keys = keys_of(answered)
|
|
if revision.blockers is not None and (missing := missing_blocker(revision.blockers, open_keys, self.label)):
|
|
return missing
|
|
if revision.blockers is not None and (looped := blocking_loop(answered, issue, revision.blockers, self.label)):
|
|
return looped
|
|
body = revision.body
|
|
if detail is not None and not self.shows(issue, detail):
|
|
description = self.description_of(detail)
|
|
if isinstance(description, Failure):
|
|
return description
|
|
body = body | {"fields": body.get("fields", {}) | {"description": description}}
|
|
said = self.to_adf(comment) if comment and comment.strip() else None
|
|
if isinstance(said, Failure):
|
|
return Failure(f"cannot convert the comment to a Jira comment: {said.reason}")
|
|
if revision.release is not None:
|
|
version = self.fix_version(revision.release, authorization)
|
|
if isinstance(version, Failure):
|
|
return version
|
|
body = body | {"fields": body.get("fields", {}) | {"fixVersions": [{"name": version}]}}
|
|
url = f"{self.epic.site}/rest/api/3/issue/{key}"
|
|
edited = self.http("PUT", url, authorization, body) if body else None
|
|
if isinstance(edited, Failure):
|
|
return Failure(f"cannot edit {key}: {edited.reason}; {PERHAPS_EDITED.format(key=key)}")
|
|
notes = self.relinked(issue, revision.blockers, open_keys, authorization)
|
|
if said is None:
|
|
return Written(id_, notes)
|
|
posted = self.http("POST", f"{url}/comment", authorization, {"body": said})
|
|
return Written(id_, notes + ((f"edited {key}, but cannot post the comment: {posted.reason}; post it in Jira",) if isinstance(posted, Failure) else ()))
|
|
|
|
def finish(self, id_: int) -> Written | Failure:
|
|
"""Moves item id_'s issue by the transition that the config names, to the status it names. Any open child of the epic may move, whoever filed it."""
|
|
if self.finish_by is None:
|
|
return Failure(f"the config names no transition to finish an item by: set `{JIRA_FINISH_TRANSITION}` and `{JIRA_FINISH_STATUS}`, as `project-config --help` shows")
|
|
authorization = basic_auth(self.env_file)
|
|
if isinstance(authorization, Failure):
|
|
return authorization
|
|
raw = self.child(id_, authorization)
|
|
if isinstance(raw, Failure):
|
|
return raw
|
|
key = f"{project_of(self.epic.key)}-{id_}"
|
|
transition = finishing_transition(self.epic.site, key, self.finish_by, authorization, self.http)
|
|
if isinstance(transition, Failure):
|
|
return transition
|
|
refused = move_refusal(self.epic.site, key, transition, self.finish_by, authorization, self.http)
|
|
return Failure(f"{refused}; {PERHAPS_MOVED.format(key=key)}") if refused else Written(id_)
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Filing:
|
|
"""An item checked and ready to file."""
|
|
# The new issue's fields, without its description and its Fix Version.
|
|
fields: dict[str, typing.Any]
|
|
release: str
|
|
# PROPERTY's value.
|
|
scores: dict[str, typing.Any]
|
|
# The key of each issue the item is blocked by.
|
|
blockers: tuple[str, ...]
|
|
# The item as ranking scores it, under the ID 0, since Jira numbers it once filed.
|
|
item: Item
|
|
|
|
|
|
def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failure:
|
|
"""The issue to file for an item with these fields under epic, or why a field cannot be filed."""
|
|
named = cells(fields)
|
|
summary = plain(named.get("Item", "")).strip()
|
|
if not summary:
|
|
return Failure("the item has no tagline")
|
|
if unfit := unfit_text(summary, detail):
|
|
return unfit
|
|
release = named.get("Release", "")
|
|
checked = item_fields(named | {"Release": release}, "the item to file")
|
|
if isinstance(checked, Failure):
|
|
return checked
|
|
assert checked.release is not None, "item_fields refuses an empty Release"
|
|
project = project_of(epic.key)
|
|
issue_fields: dict[str, typing.Any] = {"project": {"key": project}, "parent": {"key": epic.key}, "issuetype": {"name": ISSUE_TYPE}, "summary": summary}
|
|
if checked.exempt == SECURITY:
|
|
issue_fields["labels"] = [SECURITY]
|
|
value = checked.scores | {MOVES: named.get(MOVES, ""), "Exempt": checked.exempt, FILED_BY[0]: FILED_BY[1]}
|
|
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in checked.blocked_by), Item(0, checked.release, checked.exempt, summary, checked.scores, checked.moves, checked.blocked_by))
|
|
|
|
|
|
def filed_score(item: Item, scoring: ranking.Scoring) -> float | Failure:
|
|
"""The item's score, or why it may not be filed: it lacks a score the formula may use, names a goal it may not, or scores under the bar without being exempt."""
|
|
if missing := next((name for name in SET_SCORES if name not in item.scores), None):
|
|
return Failure(f"the item to file has no {missing}: score it on {', '.join(SET_SCORES[:-1])} and {SET_SCORES[-1]}")
|
|
value = ranking.item_score(item, scoring, "the item to file")
|
|
if not isinstance(value, Failure) and ranking.falls_under(item, value, scoring.bar):
|
|
return Failure(f"the item to file scores {value:.1f}, under the bar {scoring.bar:g}; don't file it, or mark it with a reason the bar doesn't apply")
|
|
return value
|
|
|
|
|
|
def placing(answered: list[object], new: Item, value: float, scoring: ranking.Scoring) -> str | None | Failure:
|
|
"""The key of the issue to rank the new item, which scores value, just before; None where it stays last, where Jira files it. answered is the epic's open children in backlog order.
|
|
|
|
Only the issues the loop filed count, so the team's rank of every other issue stays as it is. The new item goes before the first of them that ranks after it as todo.md orders a release's items, blockers aside: a question first, then a security finding, as ranking.FIRST orders them, then the higher score. A tie goes after the older issue. Release doesn't count, as docs/decisions.md records."""
|
|
place = (ranking.FIRST.get(new.exempt, len(ranking.FIRST)), -value)
|
|
for raw in answered:
|
|
issue = issue_of(raw)
|
|
if isinstance(issue, Failure):
|
|
return issue
|
|
if issue.scores.get(FILED_BY[0]) != FILED_BY[1]:
|
|
continue
|
|
scored = scores(issue.key, issue.scores)
|
|
if isinstance(scored, Failure):
|
|
return scored
|
|
if missing := next((name for name in SET_SCORES if name not in scored.scores), None):
|
|
return Failure(f"{issue.key} holds no {missing}")
|
|
# Only the scores and the moves change a score.
|
|
other = ranking.item_score(dataclasses.replace(new, scores=scored.scores, moves=scored.moves), scoring, issue.key)
|
|
if isinstance(other, Failure):
|
|
return other
|
|
if (ranking.FIRST.get(scored.exempt, len(ranking.FIRST)), -other) > place:
|
|
return issue.key
|
|
return None
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Revision:
|
|
"""An edit checked as far as the issue and the flags allow. The description, the comment and the Fix Version's name still need the codec or a request."""
|
|
# The body of the request that edits the issue, without its description and its Fix Version.
|
|
body: dict[str, typing.Any]
|
|
# The release to move the issue to; None where the edit names none.
|
|
release: str | None
|
|
# The key of each issue the edit makes the issue blocked by; None where the edit names no Blocked by.
|
|
blockers: tuple[str, ...] | None
|
|
|
|
|
|
def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment: str | None) -> Revision | Failure:
|
|
"""The edit of issue that sets the cells in named, and the detail unless None, or why it cannot be made.
|
|
|
|
The summary, description, Fix Version and links of an issue a person filed are the team's, so of such an issue an edit may set only SCORED. Jira's screens don't show PROPERTY, so such an edit needs a comment, which tells the team. L, E, I and S are set together, so no issue is left partly scored. An issue the loop filed also keeps the label SECURITY in step with its Exempt. Only an edit of an issue the loop filed may name the blockers, whose links `JiraPlan.relinked` changes; each must be an open child, which the caller checks."""
|
|
held = issue.scores
|
|
own = held.get(FILED_BY[0]) == FILED_BY[1]
|
|
if not own and ("Item" in named or "Release" in named or BLOCKED_BY in named or detail is not None):
|
|
return Failure(f"a person filed {issue.key}, so the loop sets only its scores: change its summary, description, links and Fix Version in Jira")
|
|
if not own and not (comment and comment.strip()):
|
|
return Failure(f"a person filed {issue.key}, and Jira doesn't show its team the scores: pass a comment saying that it is scored, and why")
|
|
body: dict[str, typing.Any] = {}
|
|
if "Item" in named:
|
|
summary = plain(named["Item"]).strip()
|
|
if not summary:
|
|
return Failure("the item has no tagline")
|
|
body["fields"] = {"summary": summary}
|
|
if unfit := unfit_text(named.get("Item", ""), detail or ""):
|
|
return unfit
|
|
release = named.get("Release")
|
|
if isinstance(checked := item_fields({name: named[name] for name in ("Release", "Exempt", BLOCKED_BY) if name in named}, f"item {issue.key}", id_=issue.number), Failure):
|
|
return checked
|
|
if any(name in named for name in SCORED):
|
|
texts = {name: str(value) for name, value in held.items()} | {name: named[name] for name in SCORED if name in named}
|
|
scored = scores(issue.key, texts)
|
|
if isinstance(scored, Failure):
|
|
return scored
|
|
if scored.scores and any(name not in scored.scores for name in SET_SCORES):
|
|
return Failure(f"{issue.key} would hold some of {', '.join(SET_SCORES)} and not the rest: set them together")
|
|
value = held | scored.scores | {MOVES: texts.get(MOVES, ""), "Exempt": scored.exempt}
|
|
body["properties"] = [{"key": PROPERTY, "value": value}]
|
|
if own and (scored.exempt == SECURITY) != (held.get("Exempt") == SECURITY):
|
|
body["update"] = {"labels": [{"add" if scored.exempt == SECURITY else "remove": SECURITY}]}
|
|
return Revision(body, release, tuple(dict.fromkeys(f"{project_of(issue.key)}-{blocker}" for blocker in checked.blocked_by)) if BLOCKED_BY in named else None)
|
|
|
|
|
|
def children(epic: Epic, authorization: str, http: Http, max_pages: int) -> list[object] | Failure:
|
|
"""The epic's open child issues in backlog order, which the team ranks, apart from where add ranks an issue it files. An issue in a done status is a finished item, so it is no longer in the plan."""
|
|
# The search answers no issues for an epic the account cannot see, as for one whose children are all done; asking for the epic itself tells them apart.
|
|
seen = http("GET", f"{epic.site}/rest/api/3/issue/{epic.key}?fields=summary", authorization, None)
|
|
if isinstance(seen, Failure):
|
|
return Failure(f"cannot read the epic {epic.key}: {seen.reason}")
|
|
return searched(epic.site, f"{epic.key}'s children", f'parent = "{epic.key}" AND statusCategory != Done ORDER BY Rank ASC', {"fields": ["summary", "description", "fixVersions", "issuelinks"], "properties": [PROPERTY]}, authorization, http, max_pages)
|
|
|
|
|
|
def issue_of(raw: object) -> Issue | Failure:
|
|
"""The issue in one entry of the search's answer, or which issue is not in the shape Jira documents, and how."""
|
|
entry = entry_of(raw, PROPERTY)
|
|
if isinstance(entry, Failure):
|
|
return entry
|
|
key, fields, links, held = entry.key, entry.fields, entry.links, entry.held
|
|
try:
|
|
summary, description, versions = fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"])
|
|
except (AttributeError, KeyError, TypeError) as failure:
|
|
return Failure(unshaped(key, failure))
|
|
if not isinstance(held, dict):
|
|
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
|
|
issue = Issue(key, summary, description, versions, links, held)
|
|
if not isinstance(issue.description, dict | None) or not all(isinstance(name, str) for name in issue.fix_versions + issue.blockers) or not all(isinstance(link.id, str) for link in links) or not all(ISSUE_KEY.fullmatch(blocker) for blocker in issue.blockers):
|
|
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its description, a Fix Version's name or a link's id or linked issue's key holds another kind of value")
|
|
return issue
|
|
|
|
|
|
def keys_of(answered: list[object]) -> set[object]:
|
|
"""The key of each issue in the search's answer."""
|
|
return {raw.get("key") for raw in answered if isinstance(raw, dict)}
|
|
|
|
|
|
def missing_blocker(blockers: tuple[str, ...], held: set[object], label: str) -> Failure | None:
|
|
"""None where each of blockers is among the keys held, the plan's open children, else a Failure naming the first that isn't. `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read."""
|
|
missing = next((blocker for blocker in blockers if blocker not in held), None)
|
|
return None if missing is None else Failure(f"{label} holds no item {number(missing)} to be blocked by")
|
|
|
|
|
|
def blocking_loop(answered: list[object], issue: Issue, blockers: tuple[str, ...], label: str) -> Failure | None:
|
|
"""A Failure where issue, once blocked by blockers, which the caller has checked are open children, would block itself through the items its blockers wait for, and none of them could be taken; None otherwise. A loop the plan already holds without issue isn't this edit's."""
|
|
issues = {found.key: found for raw in answered if isinstance(found := issue_of(raw), Issue)}
|
|
waits_for = {found.key: found.blockers for found in issues.values()} | {issue.key: blockers}
|
|
reached: set[str] = set()
|
|
frontier = set(blockers)
|
|
while frontier:
|
|
reached |= frontier
|
|
frontier = {blocker for key in frontier for blocker in waits_for[key] if blocker in issues} - reached
|
|
return Failure(f"{label}: item {issue.number} would be blocked by itself through {', '.join(str(number(key)) for key in sorted(reached - {issue.key}, key=number))}; drop one of the blockers") if issue.key in reached else None
|
|
|
|
|
|
def plan_of(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure:
|
|
"""The plan the issues hold, in their order."""
|
|
project = project_of(epic.key)
|
|
if strangers := [issue.key for issue in issues if project_of(issue.key) != project]:
|
|
return Failure(f"{strangers[0]} is a child of {epic.key} in another Jira project, and an item's ID is its number in {project}; move it into {project} or out of the epic")
|
|
ids = {issue.number for issue in issues}
|
|
items = [item(issue, project, ids) for issue in issues]
|
|
if failed := next((found for found in items if isinstance(found, Failure)), None):
|
|
return failed
|
|
# The descriptions convert last, since that costs a container run, which a read that fails doesn't need.
|
|
texts = details(issues, epic, to_markdown)
|
|
if isinstance(texts, Failure):
|
|
return texts
|
|
return Plan([dataclasses.replace(found, detail=texts.get(found.id, "")) for found in items if isinstance(found, Item)])
|
|
|
|
|
|
def number(key: str) -> int:
|
|
return int(key.rpartition("-")[2])
|
|
|
|
|
|
def details(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> dict[int, str] | Failure:
|
|
"""Each described issue's description as markdown, under the issue's number, all converted at once."""
|
|
described = [(issue, issue.description) for issue in issues if issue.description is not None]
|
|
texts = to_markdown([description for _, description in described])
|
|
if isinstance(texts, Refused):
|
|
return Failure(f"{described[texts.index][0].key}'s description: {texts.failure.reason}")
|
|
if isinstance(texts, Failure):
|
|
return Failure(f"cannot convert the descriptions of {epic.key}'s children to markdown: {texts.reason}")
|
|
return {issue.number: text.strip() for (issue, _), text in zip(described, texts)}
|
|
|
|
|
|
def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure:
|
|
"""The item an issue holds, without its detail. It is blocked by each of its blockers among ids, the plan's items: a blocker that is done or lies outside the epic doesn't make the item wait."""
|
|
release = earliest_release(issue.fix_versions)
|
|
if release is None:
|
|
return Failure(f"{issue.key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira")
|
|
scored = scores(issue.key, issue.scores)
|
|
if isinstance(scored, Failure):
|
|
return scored
|
|
blockers = {number(key) for key in issue.blockers if project_of(key) == project}
|
|
return Item(issue.number, release, scored.exempt, bold_cell(issue.summary), scored.scores, scored.moves, tuple(sorted(blockers & ids)), "")
|
|
|
|
|
|
def earliest_release(names: tuple[str, ...]) -> Release | None:
|
|
"""The earliest release among Fix Versions named as a semver version, with a leading v or without; None where none is."""
|
|
releases = [release for name in names if (release := parsed(name) or tagged(name))]
|
|
return min(releases, default=None)
|
|
|
|
|
|
def scores(key: str, held: dict[str, typing.Any]) -> ItemFields | Failure:
|
|
"""The scores, Moves and Exempt that an issue's PROPERTY value holds, each in the format the items table of a todo.md takes."""
|
|
named = {name: str(value) for name, value in held.items() if name in (*SHAPE.score_columns, MOVES, "Exempt")}
|
|
checked = item_fields(named, f"item {key}")
|
|
# Jira's screens don't show PROPERTY, so the message says where the value is.
|
|
return Failure(f"{checked.reason}; {key} holds it in its issue property {PROPERTY}") if isinstance(checked, Failure) else checked
|