220 lines
11 KiB
Python
220 lines
11 KiB
Python
"""A plan kept as the child issues of one Jira Cloud epic, read 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.
|
|
|
|
The store only reads so far: every write is a Failure."""
|
|
import base64
|
|
import dataclasses
|
|
import pathlib
|
|
import re
|
|
import typing
|
|
|
|
from adf_codec.convert import adfs_to_markdown, Refused
|
|
from plan_store.markdown_edits import bold_cell
|
|
from project_config.settings import Epic
|
|
from release_plan.todo_table import EXEMPTIONS, is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE
|
|
from failure import Failure
|
|
from rest_client import json_request
|
|
from release_plan.release import parsed, Release, tagged
|
|
from plan_store.stores import Plan, Written
|
|
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 only read so far: file, edit and finish its issues in Jira"
|
|
|
|
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, 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]
|
|
|
|
|
|
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 with the credentials env_file holds."""
|
|
epic: Epic
|
|
env_file: pathlib.Path
|
|
http: Http = http_json
|
|
to_markdown: ToMarkdown = adfs_to_markdown
|
|
|
|
@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:
|
|
return Failure(READ_ONLY)
|
|
|
|
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:
|
|
return Failure(READ_ONLY)
|
|
|
|
|
|
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 = epic.key.rpartition("-")[0]
|
|
if strangers := [issue.key for issue in issues if issue.key.rpartition("-")[0] != 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 key.rpartition("-")[0] == 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
|