381 lines
21 KiB
Python
381 lines
21 KiB
Python
"""A plan kept as the child issues of one Jira Cloud epic, read and filed into 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 teammate filed holds none, and reads as an item without scores.
|
|
|
|
`add` files an item as a new child issue, marked with FILED_BY, and `finish` moves an item's issue to a done status. edit is a Failure until todo.md's item 382."""
|
|
import base64
|
|
import dataclasses
|
|
import pathlib
|
|
import re
|
|
import typing
|
|
|
|
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
|
|
from release_plan.todo_table import BLOCKED_BY, EXEMPTIONS, is_exempt, Item, MOVES, parse_ids, parse_moves, parse_scores, SHAPE
|
|
from plan_store.markdown_edits import bold_cell, plain, unfit_text
|
|
from plan_store.stores import cells, Plan, Written
|
|
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
|
|
from failure import Failure
|
|
from rest_client import json_request
|
|
from release_plan.release import parsed, Release, tagged
|
|
from rest_client.env_file import read_env
|
|
|
|
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
|
|
KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN")
|
|
# 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]+)")
|
|
# Seconds each connect and each read may wait.
|
|
TIMEOUT = 30
|
|
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
|
|
READ_ONLY = "a plan in Jira is read, filed into and finished so far: edit its issues in Jira"
|
|
# The key in PROPERTY's value that marks an issue the loop filed, and its value. The loop never edits the summary or description of an issue without it, which a person filed.
|
|
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"
|
|
|
|
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
|
|
Http = typing.Callable[[str, str, str, object], object]
|
|
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
|
|
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
|
|
|
|
|
|
def http_json(method: str, url: str, authorization: str, body: object) -> object:
|
|
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
|
|
|
|
|
|
def error_message(answer: object) -> str:
|
|
"""Jira's messages in the JSON of an error answer; empty where it holds none."""
|
|
if not isinstance(answer, dict):
|
|
return ""
|
|
messages, errors = answer.get("errorMessages"), answer.get("errors")
|
|
found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])]
|
|
return "; ".join(text for text in found if isinstance(text, str))
|
|
|
|
|
|
@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 = http_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
|
|
|
|
@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, which Jira ranks last in the backlog. No bar applies and the goals file isn't read, since a plan in Jira has no place for a formula or a bar yet (todo.md's item 384).
|
|
|
|
Jira takes the links after the issue. A link it refuses leaves the issue filed, so the write counts as landed, and a note names each link to make by hand."""
|
|
filing = filing_of(fields, detail, self.epic)
|
|
if isinstance(filing, Failure):
|
|
return filing
|
|
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
|
|
if filing.blockers and (missing := self.missing_blocker(filing.blockers, authorization)):
|
|
return missing
|
|
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)}")
|
|
notes = []
|
|
for blocker in filing.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")
|
|
return Written(number(key), 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 file the item under a release it has")
|
|
|
|
def missing_blocker(self, blockers: tuple[str, ...], authorization: str) -> Failure | None:
|
|
"""A Failure naming the first of blockers that is no open child of the epic. `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read."""
|
|
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)}
|
|
return next((Failure(f"{self.label} holds no item {number(blocker)} to be blocked by") for blocker in blockers if blocker not in held), None)
|
|
|
|
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
|
|
return Failure(READ_ONLY)
|
|
|
|
def finish(self, id_: int) -> Written | Failure:
|
|
"""Moves item id_'s issue by the transition, and to the status, that the config names, since each Jira workflow differs. 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}") 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, ...]
|
|
|
|
|
|
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", "")
|
|
if parsed(release) is None:
|
|
return Failure(f"the item's Release {release!r} is not a version such as 1.2.0")
|
|
# Named so the shared messages read "item to file's L": they open with "item" and an ID, which this item has none of yet.
|
|
levels = parse_scores("to file", named, SHAPE.score_columns)
|
|
if isinstance(levels, Failure):
|
|
return levels
|
|
moves, exempt = named.get(MOVES, ""), named.get("Exempt", "")
|
|
if isinstance(unfit_moves := parse_moves("to file", moves), Failure):
|
|
return unfit_moves
|
|
if not is_exempt(exempt):
|
|
return Failure(f"the item's Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
|
blockers = parse_ids(named.get(BLOCKED_BY, ""))
|
|
if blockers is None:
|
|
return Failure(f"the item's {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"")
|
|
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 exempt == SECURITY:
|
|
issue_fields["labels"] = [SECURITY]
|
|
value = levels | {MOVES: moves, "Exempt": exempt, FILED_BY[0]: FILED_BY[1]}
|
|
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers))
|
|
|
|
|
|
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 offers for the issue key in its present status; 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}: set `{JIRA_FINISH_TRANSITION}` to one of them" 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 basic_auth(env_file: pathlib.Path) -> str | Failure:
|
|
"""The Authorization header for the email and API token that env_file holds."""
|
|
values = read_env(env_file, KEYS, "an API token")
|
|
if isinstance(values, Failure):
|
|
return values
|
|
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
|
|
|
|
|
|
def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure:
|
|
"""The epic's open child issues in backlog order, which is the order the team ranks them in. 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:
|
|
# Until a project can tie its releases to something other than semver versions, an item with no release cannot be placed in the plan.
|
|
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[2], bold_cell(issue.summary), scored[0], scored[1], 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) -> tuple[dict[str, int], typing.Any, typing.Any] | 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()}
|
|
levels = parse_scores(key, named, SHAPE.score_columns)
|
|
if isinstance(levels, Failure):
|
|
return levels
|
|
moves = parse_moves(key, named.get(MOVES, ""))
|
|
if isinstance(moves, Failure):
|
|
return moves
|
|
exempt = named.get("Exempt", "")
|
|
if not is_exempt(exempt):
|
|
return Failure(f"{key}'s issue property {PROPERTY} holds the Exempt {exempt!r}, which is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
|
return levels, moves, exempt
|