Files
claude-config/bin/plan_store/jira_epic.py
T
2026-11-14 19:12:25 +01:00

214 lines
10 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 the epic's children all lie 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 concurrent.futures
import dataclasses
import http.client
import json
import pathlib
import re
import typing
import urllib.error
import urllib.parse
import urllib.request
from adf_codec.convert import adf_to_markdown
from failure import Failure
from mattermost_dm.dm import parse_env
from plan_store.markdown_edits import bold_cell
from plan_store.stores import Plan, Written
from project_config.settings import Epic
from release_plan.release import parsed, Release, tagged
from release_plan.todo_table import is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE
# One pair of keys for Jira and Confluence, which 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"
# 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
# The adf-codec containers run at once: each description is one run.
CONVERSIONS = 8
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, and returns the JSON answer, or a Failure saying why there is none.
Http = typing.Callable[[str, str, str, object], object]
ToMarkdown = typing.Callable[[dict[str, typing.Any]], str | Failure]
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""Refuses every redirect, which Jira's API never sends: urllib would resend the credentials to the new location, even one off https."""
def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None:
return None
OPENER = urllib.request.build_opener(NoRedirect)
def http_json(method: str, url: str, authorization: str, body: object) -> object:
"""The JSON that url answers; a Failure naming the request where it answers an error, breaks HTTP or answers something other than JSON, and saying so where the site cannot be reached."""
request_name = f"{method} {urllib.parse.urlsplit(url).path}"
request = urllib.request.Request(url, json.dumps(body).encode(), {"Authorization": authorization, "Content-Type": "application/json", "Accept": "application/json"}, method=method)
try:
with OPENER.open(request, timeout=TIMEOUT) as response:
raw = response.read()
except urllib.error.HTTPError as failure:
with failure:
return Failure(f"{request_name} answered {failure.code}: {failure.reason}")
except http.client.HTTPException as failure:
return Failure(f"{request_name} got a broken answer: {failure!r}")
except (OSError, ValueError) as failure:
return Failure(f"cannot be reached: {getattr(failure, 'reason', failure)}")
try:
return json.loads(raw)
except ValueError:
return Failure(f"{request_name} answered with something other than JSON")
@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 = adf_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
issues = children(self.epic, authorization, self.http)
if isinstance(issues, Failure):
return Failure(f"{self.epic.site}: {issues.reason}")
try:
return plan_of(issues, self.epic, self.to_markdown)
except (AttributeError, KeyError, TypeError):
return Failure(f"{self.epic.site} answered issues in another shape than Jira Cloud's REST API version 3 documents")
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's KEY=value lines hold."""
try:
mode = env_file.stat().st_mode
text = env_file.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{env_file} does not exist; it needs {' and '.join(KEYS)}")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"cannot read {env_file}: {failure}")
if mode & 0o077:
return Failure(f"{env_file} holds an API token, so only its owner may read it; run chmod 600 {env_file}")
values = parse_env(text)
if missing := [key for key in KEYS if not values.get(key)]:
return Failure(f"{env_file} lacks {' and '.join(missing)}")
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
def children(epic: Epic, authorization: str, http: Http) -> list[dict[str, typing.Any]] | 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."""
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[dict[str, typing.Any]] = []
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 plan_of(issues: list[dict[str, typing.Any]], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure:
"""The plan the issues hold, in their order. Raises AttributeError, KeyError or TypeError where an issue is not in the shape Jira documents."""
project = epic.key.rpartition("-")[0]
if strangers := [issue["key"] for issue in issues if not re.fullmatch(rf"{re.escape(project)}-[0-9]+", issue["key"])]:
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 = {number(issue["key"]) for issue in issues}
with concurrent.futures.ThreadPoolExecutor(CONVERSIONS) as pool:
details = list(pool.map(lambda issue: detail(issue, to_markdown), issues))
items = [item(issue, ids, text) for issue, text in zip(issues, details)]
return next((found for found in items if isinstance(found, Failure)), None) or Plan([found for found in items if isinstance(found, Item)])
def number(key: str) -> int:
return int(key.rpartition("-")[2])
def detail(issue: dict[str, typing.Any], to_markdown: ToMarkdown) -> str | Failure:
"""The issue's description as markdown; empty where it has none."""
description = issue["fields"]["description"]
if description is None:
return ""
text = to_markdown(description)
return Failure(f"{issue['key']}'s description: {text.reason}") if isinstance(text, Failure) else text.strip()
def item(issue: dict[str, typing.Any], ids: set[int], text: str | Failure) -> Item | Failure:
"""The item an issue holds, 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."""
if isinstance(text, Failure):
return text
key, fields = issue["key"], issue["fields"]
release = earliest_release([version["name"] for version in fields["fixVersions"]])
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"{key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira")
blockers = [number(link["inwardIssue"]["key"]) for link in fields["issuelinks"] if link["type"]["inward"] == "is blocked by" and "inwardIssue" in link and link["inwardIssue"]["key"].rpartition("-")[0] == key.rpartition("-")[0]]
scored = scores(key, issue.get("properties", {}).get(PROPERTY, {}))
if isinstance(scored, Failure):
return scored
return Item(number(key), release, scored[2], bold_cell(fields["summary"].strip()), scored[0], scored[1], tuple(sorted(set(blockers) & ids)), text)
def earliest_release(names: list[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"item {key}'s Exempt {exempt!r} is not one a todo.md's items table takes")
return levels, moves, exempt