490 lines
29 KiB
Python
490 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, but never its links. Of an issue a person filed it sets only the scores, with a comment that tells the team why."""
|
|
import dataclasses
|
|
import pathlib
|
|
import re
|
|
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, Plan, Written
|
|
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"
|
|
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 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"
|
|
# 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 {epic} before filing the item 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"
|
|
# 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 key of each issue this one "is blocked by".
|
|
blockers: tuple[str, ...]
|
|
# PROPERTY's value; an empty object where the issue holds none.
|
|
scores: object
|
|
|
|
@property
|
|
def number(self) -> int:
|
|
return number(self.key)
|
|
|
|
|
|
@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
|
|
# 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)
|
|
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
|
|
issue_fields = filing.fields
|
|
if detail.strip():
|
|
description = self.to_adf(detail)
|
|
if isinstance(description, Failure):
|
|
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}")
|
|
issue_fields = issue_fields | {"description": description}
|
|
version = self.fix_version(filing.release, authorization)
|
|
if isinstance(version, Failure):
|
|
return version
|
|
answered = children(self.epic, authorization, self.http)
|
|
if isinstance(answered, Failure):
|
|
return answered
|
|
held = {raw.get("key") for raw in answered if isinstance(raw, dict)}
|
|
# `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read.
|
|
if missing := next((blocker for blocker in filing.blockers if blocker not in held), None):
|
|
return Failure(f"{self.label} holds no item {number(missing)} to be blocked by")
|
|
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(epic=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(epic=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:
|
|
# 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.
|
|
linked = self.http("POST", f"{self.epic.site}/rest/api/3/issueLink", authorization, {"type": {"name": BLOCKS}, "inwardIssue": {"key": blocker}, "outwardIssue": {"key": key}})
|
|
if isinstance(linked, 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 := self.rank_refusal(key, before, authorization)):
|
|
notes.append(f"filed {key}, but cannot rank it before {before}: {refused}; rank it in Jira")
|
|
return tuple(notes)
|
|
|
|
def rank_refusal(self, key: str, before: str, authorization: str) -> 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 = self.http("PUT", f"{self.epic.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 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 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 the edit or none, and then posts comment on the issue. `revision_of` says what an edit may set.
|
|
|
|
A comment Jira refuses leaves the edit made, so the write counts as landed, and a note says to post the comment by hand."""
|
|
authorization = basic_auth(self.env_file)
|
|
if isinstance(authorization, Failure):
|
|
return authorization
|
|
answered = children(self.epic, authorization, self.http)
|
|
if isinstance(answered, Failure):
|
|
return answered
|
|
key = f"{project_of(self.epic.key)}-{id_}"
|
|
raw = next((raw for raw in answered if isinstance(raw, dict) and raw.get("key") == key), None)
|
|
if raw is None:
|
|
return Failure(f"{self.label} holds no item {id_}")
|
|
issue = issue_of(raw)
|
|
if isinstance(issue, Failure):
|
|
return issue
|
|
revision = revision_of(issue, cells(fields), detail, comment)
|
|
if isinstance(revision, Failure):
|
|
return revision
|
|
body = revision.body
|
|
if detail is not None:
|
|
description = self.to_adf(detail) if detail.strip() else None
|
|
if isinstance(description, Failure):
|
|
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}")
|
|
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 isinstance(edited, Failure):
|
|
return Failure(f"cannot edit {key}: {edited.reason}; {PERHAPS_EDITED.format(key=key)}")
|
|
if said is None:
|
|
return Written(id_)
|
|
posted = self.http("POST", f"{url}/comment", authorization, {"body": said})
|
|
return Written(id_, (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
|
|
answered = children(self.epic, authorization, self.http)
|
|
if isinstance(answered, Failure):
|
|
return answered
|
|
key = f"{project_of(self.epic.key)}-{id_}"
|
|
if not any(isinstance(raw, dict) and raw.get("key") == key for raw in answered):
|
|
return Failure(f"{self.label} holds no item {id_}")
|
|
url = f"{self.epic.site}/rest/api/3/issue/{key}/transitions"
|
|
offered = self.http("GET", url, authorization, None)
|
|
if isinstance(offered, Failure):
|
|
return Failure(f"cannot read {key}'s transitions: {offered.reason}")
|
|
transition = transition_of(offered, key, self.finish_by)
|
|
if isinstance(transition, Failure):
|
|
return transition
|
|
moved = self.http("POST", url, authorization, {"transition": {"id": transition}})
|
|
return Failure(f"cannot move {key} by {self.finish_by.transition!r}: {moved.reason}; {PERHAPS_MOVED.format(key=key)}") if isinstance(moved, Failure) 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 not isinstance(issue.scores, dict) or 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
|
|
|
|
|
|
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 and Fix Version of an issue a person filed are the team's, so there 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. No edit changes a link."""
|
|
held = issue.scores
|
|
if not isinstance(held, dict):
|
|
return Failure(f"{issue.key}'s issue property {PROPERTY} is not a JSON object")
|
|
if BLOCKED_BY in named:
|
|
return Failure(f"the loop doesn't change an issue's links: link {issue.key} in Jira")
|
|
own = held.get(FILED_BY[0]) == FILED_BY[1]
|
|
if not own and ("Item" in named or "Release" 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 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") if name in named}, "the item"), 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)
|
|
|
|
|
|
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 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 children(epic: Epic, authorization: str, http: Http) -> 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}")
|
|
body: dict[str, object] = {
|
|
"jql": f'parent = "{epic.key}" AND statusCategory != Done ORDER BY Rank ASC',
|
|
"fields": ["summary", "description", "fixVersions", "issuelinks"],
|
|
"properties": [PROPERTY],
|
|
"maxResults": PAGE,
|
|
}
|
|
found: list[object] = []
|
|
for _ in range(MAX_PAGES):
|
|
page = http("POST", f"{epic.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 {epic.key}'s children did not end within {MAX_PAGES} 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."""
|
|
key = raw.get("key") if isinstance(raw, dict) else None
|
|
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
|
|
return Failure("the search answered an issue without an issue key")
|
|
try:
|
|
fields = typing.cast(dict[str, typing.Any], raw)["fields"]
|
|
blockers = tuple(link["inwardIssue"]["key"] for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by")
|
|
issue = Issue(key, fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"]), blockers, typing.cast(dict[str, typing.Any], raw).get("properties", {}).get(PROPERTY, {}))
|
|
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}")
|
|
if not isinstance(issue.description, dict | None) or not all(isinstance(name, str) for name in issue.fix_versions + issue.blockers) 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 linked issue's key holds another kind of value")
|
|
return issue
|
|
|
|
|
|
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: object) -> 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."""
|
|
if not isinstance(held, dict):
|
|
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
|
|
named = {name: str(value) for name, value in held.items() if name in (*SHAPE.score_columns, MOVES, "Exempt")}
|
|
return item_fields(named, f"item {key}")
|