Read a plan from the child issues of a Jira Cloud epic
CI / tests (pull_request) Failing after 2m6s

This commit is contained in:
2026-11-14 19:12:25 +01:00
parent c19f097ecd
commit 59d972cc82
22 changed files with 570 additions and 30 deletions
+213
View File
@@ -0,0 +1,213 @@
"""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
+8 -2
View File
@@ -1,6 +1,6 @@
"""The one way a tool reads or writes a project's plan: through the store its config names.
The config's `plan` setting names the backend. A path names a markdown file, todo.md, the only backend so far. An agent reads and changes the plan with `todo-item`, which works through the same store.
The config's `plan` setting names the backend. A path names a markdown file, todo.md. A Jira epic names its child issues, which `jira_epic` reads and nothing writes yet. An agent reads and changes the plan with `todo-item`, which works through the same store.
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends."""
import dataclasses
@@ -144,7 +144,13 @@ class FilePlan:
def store(config: ProjectConfig) -> PlanStore:
"""The store config names for the plan."""
return file_plan(config)
if config.epic is None:
return file_plan(config)
# Imported here, since jira_epic builds on this module's Plan and Written.
from plan_store.jira_epic import JiraPlan
# load refuses a config that names an epic and no env-file.
assert config.env_file is not None
return JiraPlan(config.epic, config.env_file)
def file_plan(config: ProjectConfig, path: pathlib.Path | None = None) -> FilePlan:
+165
View File
@@ -0,0 +1,165 @@
import base64
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from plan_store import jira_epic
from plan_store.stores import Plan
from project_config.settings import Epic
from release_plan.release import release_of
EPIC = Epic("https://acme.atlassian.net", "ABC-12")
SEARCH = "https://acme.atlassian.net/rest/api/3/search/jql"
def issue(key: str, summary: str = "Count the runs.", versions: tuple[str, ...] = ("0.1.0",), scores: dict[str, object] | None = None, blocked_by: tuple[str, ...] = (), description: object = None, blocks: tuple[str, ...] = ()) -> dict[str, object]:
links = [{"type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": {"key": blocker}} for blocker in blocked_by]
links += [{"type": {"inward": "is blocked by", "outward": "blocks"}, "outwardIssue": {"key": blocked}} for blocked in blocks]
return {
"key": key,
"fields": {"summary": summary, "description": description, "fixVersions": [{"name": name} for name in versions], "issuelinks": links},
"properties": {} if scores is None else {jira_epic.PROPERTY: scores},
}
def adf(text: str) -> dict[str, object]:
return {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]}
def text_of(document: dict[str, object]) -> str | Failure:
"""Stands in for the adf-codec shim: the text of the one paragraph adf builds."""
return document["content"][0]["content"][0]["text"] + "\n" # type: ignore[index]
class JiraPlan(unittest.TestCase):
def setUp(self) -> None:
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
self.env.chmod(0o600)
self.pages: list[object] = []
self.calls: list[tuple[str, str, str, object]] = []
def http(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url, authorization, body))
return self.pages[len(self.calls) - 1]
def store(self) -> jira_epic.JiraPlan:
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of)
def read(self, *issues: dict[str, object]) -> Plan | Failure:
self.pages, self.calls = [{"issues": list(issues)}], []
return self.store().read()
def items(self, *issues: dict[str, object]):
plan = self.read(*issues)
assert isinstance(plan, Plan), plan
return plan.items
def test_an_epic_with_no_open_child_reads_as_an_empty_plan(self):
self.assertEqual(self.read(), Plan([]))
def test_asks_for_the_epics_open_children_in_backlog_order_with_basic_auth(self):
self.read()
method, url, authorization, body = self.calls[0]
self.assertEqual((method, url), ("POST", SEARCH))
self.assertEqual(authorization, "Basic " + base64.b64encode(b"me@example.com:s3cret").decode())
self.assertEqual(body["jql"], 'parent = "ABC-12" AND statusCategory != Done ORDER BY Rank ASC') # type: ignore[index]
self.assertEqual(body["properties"], [jira_epic.PROPERTY]) # type: ignore[index]
def test_an_issue_reads_as_an_item_under_its_number(self):
scores = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "owner"}
item, = self.items(issue("ABC-34", "Count the runs.", ("0.1.0",), scores, description=adf("Why it counts.")))
self.assertEqual((item.id, item.release, item.tagline, item.detail), (34, release_of("0.1.0"), "**Count the runs.**", "Why it counts."))
self.assertEqual((item.scores, item.moves, item.exempt, item.blocked_by), ({"L": 1, "E": 2, "I": 3, "S": 1}, (("1", 9),), "owner", ()))
def test_keeps_jiras_order_whatever_the_releases_and_scores(self):
found = self.items(issue("ABC-40", versions=("0.2.0",)), issue("ABC-7", versions=("0.1.0",)), issue("ABC-21", versions=("0.3.0",)))
self.assertEqual([item.id for item in found], [40, 7, 21])
def test_an_issue_nobody_scored_reads_without_scores(self):
item, = self.items(issue("ABC-34"))
self.assertEqual((item.scores, item.moves, item.exempt, item.detail, item.likelihood), ({}, (), "", "", 0))
def test_an_issue_is_blocked_by_each_blocker_still_in_the_plan(self):
blocked, _ = self.items(issue("ABC-34", blocked_by=("ABC-35", "ABC-2", "OTHER-9"), blocks=("ABC-35",)), issue("ABC-35", blocks=("ABC-34",)))
self.assertEqual(blocked.blocked_by, (35,))
def test_the_release_is_the_earliest_fix_version_with_or_without_a_v(self):
item, = self.items(issue("ABC-34", versions=("v1.2.0", "0.9.1", "Later")))
self.assertEqual(item.release, release_of("0.9.1"))
def test_an_issue_with_no_semver_fix_version_fails_the_read_naming_it(self):
for versions in ((), ("Sprint 4",)):
failure = self.read(issue("ABC-34", versions=versions))
self.assertIsInstance(failure, Failure)
self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr]
self.assertIn("Fix Version", failure.reason) # type: ignore[union-attr]
def test_a_child_in_another_jira_project_fails_the_read_naming_it(self):
failure = self.read(issue("ABC-34"), issue("OTHER-5"))
self.assertIsInstance(failure, Failure)
self.assertIn("OTHER-5", failure.reason) # type: ignore[union-attr]
def test_scores_out_of_format_fail_the_read_naming_the_issue(self):
for scores in ({"L": 9}, {"L": "high"}, {"Moves": "everything"}, {"Exempt": "because"}, "L 3"):
failure = self.read(issue("ABC-34", scores=scores)) # type: ignore[arg-type]
self.assertIsInstance(failure, Failure, scores)
self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr]
def test_reads_every_page(self):
self.pages = [{"issues": [issue("ABC-1")], "nextPageToken": "t1"}, {"issues": [issue("ABC-2")]}]
plan = self.store().read()
self.assertEqual([item.id for item in plan.items], [1, 2]) # type: ignore[union-attr]
self.assertNotIn("nextPageToken", self.calls[0][3]) # type: ignore[operator]
self.assertEqual(self.calls[1][3]["nextPageToken"], "t1") # type: ignore[index]
def test_a_failing_request_fails_the_read(self):
self.pages = [Failure("POST /rest/api/3/search/jql answered 401: no")]
self.assertEqual(self.store().read(), Failure("https://acme.atlassian.net: POST /rest/api/3/search/jql answered 401: no"))
def test_an_answer_in_another_shape_fails_the_read(self):
for page in ([], {"issues": "none"}, {"issues": [{"key": "ABC-1"}]}, {"issues": [{"key": 7, "fields": {}}]}, {"issues": [issue("ABC-1", summary=None)]}): # type: ignore[arg-type]
self.pages, self.calls = [page], []
self.assertIsInstance(self.store().read(), Failure, page)
def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self):
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: Failure("adf-codec refused"))
self.pages = [{"issues": [issue("ABC-34", description=adf("x"))]}]
self.assertEqual(store.read(), Failure("ABC-34's description: adf-codec refused"))
def test_an_env_file_without_the_credentials_fails_before_any_request(self):
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\n")
failure = self.read()
self.assertIsInstance(failure, Failure)
self.assertIn("ATLASSIAN_API_TOKEN", failure.reason) # type: ignore[union-attr]
self.assertEqual(self.calls, [])
def test_an_env_file_others_may_read_fails_before_any_request(self):
self.env.chmod(0o644)
self.assertIsInstance(self.read(), Failure)
self.assertEqual(self.calls, [])
def test_a_missing_env_file_fails(self):
self.env.unlink()
self.assertIsInstance(self.read(), Failure)
def test_no_failure_holds_the_token(self):
self.pages = [{"issues": [issue("OTHER-5")]}]
self.assertNotIn("s3cret", self.store().read().reason) # type: ignore[union-attr]
def test_every_write_fails_since_the_store_only_reads(self):
store = self.store()
for written in (store.add({}, ""), store.edit(34, {"L": "2"}, None), store.finish(34)):
self.assertIsInstance(written, Failure)
self.assertEqual(self.calls, [])
def test_names_itself_by_the_configs_spelling_and_no_commit_holds_it(self):
self.assertEqual((self.store().label, self.store().tracked), ("jira:https://acme.atlassian.net/browse/ABC-12", None))
if __name__ == "__main__":
unittest.main()
+18
View File
@@ -7,8 +7,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic, ProjectConfig, SETTINGS
from failure import Failure
from plan_store.contract import FIRST, PlanStoreContract, SECOND
from plan_store.jira_epic import JiraPlan
from plan_store.fakes import MemoryPlan
from record_store.fakes import MemoryStore
from release_plan.todo_table import NoItemsTable
@@ -176,5 +178,21 @@ class HeldAt(unittest.TestCase):
self.assertEqual(stores.held_at("origin/main", MemoryPlan(tracked="todo.md"), "/checkout", run), Failure("no git"))
class Store(unittest.TestCase):
def config(self, **named) -> ProjectConfig:
paths = {name: pathlib.Path("/checkout", name) for name in SETTINGS[1:]}
return ProjectConfig("acme", pathlib.Path("/folder"), pathlib.Path("/checkout"), paths, **named)
def test_a_path_picks_the_markdown_file(self):
config = self.config()
picked = stores.store(dataclasses.replace(config, paths=config.paths | {"plan": pathlib.Path("/checkout/todo.md")}))
self.assertEqual((type(picked), picked.label, picked.tracked), (stores.FilePlan, "/checkout/todo.md", "todo.md"))
def test_an_epic_picks_jira_with_the_env_files_credentials(self):
epic = Epic("https://acme.atlassian.net", "ABC-12")
picked = stores.store(self.config(epic=epic, env_file=pathlib.Path("/secrets/acme.env")))
self.assertEqual(picked, JiraPlan(epic, pathlib.Path("/secrets/acme.env"), picked.http))
if __name__ == "__main__":
unittest.main()