Answer stability round 1: 0 🔴, 10 🟡 (0 misread); share one REST client and env-file reader, read each issue into a checked value, convert descriptions last, and simplify the hard places the change touched
This commit is contained in:
@@ -96,6 +96,8 @@
|
||||
!bin/release_plan/*.py
|
||||
!bin/repo_checks/
|
||||
!bin/repo_checks/*.py
|
||||
!bin/rest_client/
|
||||
!bin/rest_client/*.py
|
||||
!bin/review-replay
|
||||
!bin/review_replay/
|
||||
!bin/review_replay/*.py
|
||||
|
||||
@@ -100,10 +100,19 @@ A project's config may set four more things, each optional, as `project-config -
|
||||
|
||||
A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false.
|
||||
|
||||
A client that plans in Jira Cloud names an epic as the plan, as `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`: `jira:` and the epic's address as the browser shows it. The plan is then the epic's open child issues in Jira's backlog order, which the team sets; an issue in a done status is a finished item. An issue's number is the item's ID, so every child lies in the epic's own Jira project, and a read fails naming one that doesn't. The summary is the tagline, the description the detail, the earliest Fix Version named as a semver version the release, and an "is blocked by" link to another open child a blocker. The scores sit in the issue property `plan-item`, a JSON object such as `{"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}`; an issue without it reads as an item nobody scored yet. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account. The loop only reads such a plan so far: `todo-item add`, `edit`, `move` and `finish` fail saying so, `rank_todo.py` refuses it, and rule-hook's rank check skips it. What isn't supported for a plan outside the checkout, below, isn't for a plan in Jira either.
|
||||
|
||||
For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:<path>`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed.
|
||||
|
||||
A client that plans in Jira Cloud names an epic as its project's plan: `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`, which is `jira:` and the epic's address as the browser shows it. The plan is then the epic's open child issues, in Jira's backlog order, which the team sets. An issue in a done status is a finished item. Each part of an item comes from one part of its issue:
|
||||
|
||||
- The ID is the issue's number, so every child must be in the epic's own Jira project.
|
||||
- The tagline is the summary.
|
||||
- The detail is the description, which a docker container converts to markdown.
|
||||
- The release is the earliest Fix Version named as a semver version, such as `1.2.0`. Every open child needs one.
|
||||
- A blocker is an "is blocked by" link to another open child.
|
||||
- The scores are the issue property `plan-item`, a JSON object such as `{"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}`. An issue without it reads as an item nobody scored yet.
|
||||
|
||||
A read fails, naming the issue, where a child is in another Jira project or names no such Fix Version. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account, and only its owner may read that file: `chmod 600` it. The loop only reads such a plan so far. `todo-item add`, `edit`, `move` and `finish` fail, so file, edit and finish its issues in Jira. `rank_todo.py` doesn't rank it, since Jira's backlog does. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
|
||||
|
||||
```sh
|
||||
mkdir -p ~/.claude-projects/acme && cd ~/.claude-projects/acme
|
||||
git init
|
||||
@@ -180,11 +189,12 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
|
||||
- `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`.
|
||||
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read.
|
||||
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py` and the reader of a Jira epic's child issues in `jira_epic.py`. `contract.py` holds the tests every backend must pass, and `fakes.py` a plan in memory.
|
||||
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, and `fakes.py` a plan in memory.
|
||||
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
|
||||
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
|
||||
- `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises, and `citations.py` holds `todo.md` and `docs/decisions.md` to each other. `plan_file.py` ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py` and `rule_hook`.
|
||||
- `repo_checks/` tests the repo itself.
|
||||
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `mattermost_dm` and `plan_store`.
|
||||
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
|
||||
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
|
||||
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths.
|
||||
|
||||
@@ -8,6 +8,7 @@ from project_config.main import located
|
||||
from release_plan.goals_file import OPTED_OUT
|
||||
from plan_store.stores import Plan, PlanStore
|
||||
from plan_store import stores as plan_stores
|
||||
from project_config.settings import ProjectConfig
|
||||
from release_plan.release import Release, version
|
||||
from record_store import stores
|
||||
from larv_review.unmeasured import unmeasured_cut
|
||||
@@ -66,6 +67,13 @@ def emptied(before: list[Item], after: list[Item], shipped: list[Item], renamed:
|
||||
return sorted(named - {item.release for item in kept} - renamed)
|
||||
|
||||
|
||||
def finished_unseen(config: ProjectConfig, ids: list[int], chunk: list[Item]) -> Failure | None:
|
||||
"""Why the items under ids cannot all be read, where the plan lies outside the checkout: such a plan is read as it stands for both plans, so a finished item is in neither."""
|
||||
if config.tracked("plan") is None and (gone := sorted(set(ids) - {item.id for item in chunk})):
|
||||
return Failure(f"the plan as it stands holds no item {', '.join(map(str, gone))}, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {config.plan_label}")
|
||||
return None
|
||||
|
||||
|
||||
def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[str] | Failure:
|
||||
"""Why the plan calls a scoring run, from todo.md at ref and the checkout's, each file where the project's config puts it; empty where the project opts out of the comprehension check. ref is the default branch, or the commit where the chunk began. Where ids is None, the chunk ships each item the plan at ref holds and the checkout's does not."""
|
||||
config = located(None, home)
|
||||
@@ -98,10 +106,7 @@ def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[st
|
||||
return unmeasured
|
||||
if ids is None:
|
||||
ids = sorted({item.id for item in planned} - {item.id for item in chunk})
|
||||
# A plan outside the checkout is read as it stands for both plans, so a finished item is in neither.
|
||||
if config.tracked("plan") is None and (gone := sorted(set(ids) - {item.id for item in chunk})):
|
||||
return Failure(f"todo.md as it stands holds no item {', '.join(map(str, gone))}, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {config.plan_label}")
|
||||
return scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured)
|
||||
return finished_unseen(config, ids, chunk) or scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured)
|
||||
|
||||
|
||||
def checkout_plan(plan: PlanStore) -> Plan | Failure:
|
||||
|
||||
@@ -590,7 +590,7 @@ class LarvReviewTool(unittest.TestCase):
|
||||
(self.config.parent / "decisions.md").unlink()
|
||||
gone = plan_reasons("origin/main", [1, 7], pathlib.Path.home())
|
||||
assert isinstance(gone, Failure), gone
|
||||
self.assertEqual(gone.reason, f"todo.md as it stands holds no item 7, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {self.config.parent}/todo.md")
|
||||
self.assertEqual(gone.reason, f"the plan as it stands holds no item 7, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {self.config.parent}/todo.md")
|
||||
(self.config.parent / "todo.md").write_bytes(b"\xff")
|
||||
unreadable = plan_reasons("origin/main", [2], pathlib.Path.home())
|
||||
assert isinstance(unreadable, Failure), unreadable
|
||||
|
||||
+9
-64
@@ -1,15 +1,13 @@
|
||||
"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4."""
|
||||
import dataclasses
|
||||
import http.client
|
||||
import json
|
||||
import pathlib
|
||||
import typing
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from failure import Failure
|
||||
from rest_client import json_request
|
||||
from project_config.main import located
|
||||
from rest_client.env_file import read_env
|
||||
|
||||
KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT")
|
||||
# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly.
|
||||
@@ -19,16 +17,6 @@ TIMEOUT = 10
|
||||
Http = typing.Callable[[str, str, str, object], object]
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
"""Refuses every redirect, which Mattermost's API never sends: urllib would resend the token 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)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Config:
|
||||
url: str
|
||||
@@ -38,37 +26,15 @@ class Config:
|
||||
|
||||
def read_config(path: pathlib.Path) -> Config | Failure:
|
||||
"""The server, bot token and recipient that path's KEY=value lines hold."""
|
||||
try:
|
||||
mode = path.stat().st_mode
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return Failure(f"{path} does not exist; it needs {', '.join(KEYS[:-1])} and {KEYS[-1]}")
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"cannot read {path}: {failure}")
|
||||
if mode & 0o077:
|
||||
return Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}")
|
||||
values = parse_env(text)
|
||||
if missing := [key for key in KEYS if not values.get(key)]:
|
||||
return Failure(f"{path} lacks {' and '.join(missing)}")
|
||||
values = read_env(path, KEYS, "the bot's token")
|
||||
if isinstance(values, Failure):
|
||||
return values
|
||||
url, token, recipient = (values[key] for key in KEYS)
|
||||
if not url.startswith("https://"):
|
||||
return Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear")
|
||||
return Config(url.rstrip("/"), token, recipient)
|
||||
|
||||
|
||||
def parse_env(text: str) -> dict[str, str]:
|
||||
values = {}
|
||||
for line in text.splitlines():
|
||||
key, equals, value = line.partition("=")
|
||||
if not equals or key.lstrip().startswith("#"):
|
||||
continue
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
|
||||
value = value[1:-1]
|
||||
values[key.strip()] = value
|
||||
return values
|
||||
|
||||
|
||||
def send(config: Config, message: str, http: Http) -> Failure | None:
|
||||
api = f"{config.url}/api/v4"
|
||||
bot = id_of(http("GET", f"{api}/users/me", config.token, None), "GET /api/v4/users/me")
|
||||
@@ -92,33 +58,12 @@ def id_of(answer: object, request: str) -> str | Failure:
|
||||
|
||||
|
||||
def http_json(method: str, url: str, token: str, body: object) -> object:
|
||||
"""The JSON that url answers; a Failure naming the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON."""
|
||||
request_name = f"{method} {urllib.parse.urlsplit(url).path}"
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
request = urllib.request.Request(url, data, {"Authorization": f"Bearer {token}", "Content-Type": "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}: {error_message(failure) or failure.reason}")
|
||||
except http.client.HTTPException as failure:
|
||||
return Failure(f"{request_name} got a broken answer: {failure!r}")
|
||||
except (OSError, ValueError) as failure:
|
||||
server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", ""))
|
||||
return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}")
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except ValueError:
|
||||
return Failure(f"{request_name} answered with something other than JSON")
|
||||
"""The JSON that url answers to the bot's request, or a Failure saying why there is none."""
|
||||
return json_request.http_json(method, url, f"Bearer {token}", body, TIMEOUT, error_message)
|
||||
|
||||
|
||||
def error_message(failure: urllib.error.HTTPError) -> str:
|
||||
"""Mattermost's message in an error answer; empty where the body is cut short, breaks HTTP or holds none."""
|
||||
try:
|
||||
answer = json.loads(failure.read())
|
||||
except (http.client.HTTPException, OSError, ValueError):
|
||||
return ""
|
||||
def error_message(answer: object) -> str:
|
||||
"""Mattermost's message in the JSON of an error answer; empty where it holds none."""
|
||||
message = answer.get("message") if isinstance(answer, dict) else None
|
||||
return message if isinstance(message, str) else ""
|
||||
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import contextlib
|
||||
import http.server
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
@@ -111,97 +107,17 @@ class Send(unittest.TestCase):
|
||||
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions."))
|
||||
|
||||
|
||||
class Recorded(http.server.BaseHTTPRequestHandler):
|
||||
"""Answers each request with the server's next scripted status and body, recording what it got."""
|
||||
|
||||
def do_GET(self) -> None:
|
||||
self.answer()
|
||||
|
||||
def do_POST(self) -> None:
|
||||
self.answer()
|
||||
|
||||
def answer(self) -> None:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined]
|
||||
status, body = self.server.script.pop(0) # type: ignore[attr-defined]
|
||||
if status is None:
|
||||
# Raw bytes, as a server that breaks HTTP sends them.
|
||||
self.wfile.write(body)
|
||||
self.close_connection = True
|
||||
return
|
||||
self.send_response(status)
|
||||
if 300 <= status < 400:
|
||||
self.send_header("Location", "/elsewhere")
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, format: str, *args: object) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class HttpJson(unittest.TestCase):
|
||||
def serve(self, *script: tuple[int, bytes]) -> str:
|
||||
server = http.server.HTTPServer(("127.0.0.1", 0), Recorded)
|
||||
server.script = list(script) # type: ignore[attr-defined]
|
||||
server.got = [] # type: ignore[attr-defined]
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
self.addCleanup(server.server_close)
|
||||
self.addCleanup(server.shutdown)
|
||||
self.server = server
|
||||
return f"http://127.0.0.1:{server.server_port}"
|
||||
def test_sends_the_token_as_a_bearer_and_reads_mattermosts_message_from_an_error(self):
|
||||
with unittest.mock.patch.object(dm.json_request, "http_json", return_value={"id": "post-id"}) as sent:
|
||||
self.assertEqual(dm.http_json("POST", "https://chat.example/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"})
|
||||
sent.assert_called_once_with("POST", "https://chat.example/api/v4/posts", "Bearer secret-token", {"message": "hi"}, dm.TIMEOUT, dm.error_message)
|
||||
self.assertEqual(dm.TIMEOUT, 10)
|
||||
|
||||
def test_sends_the_token_as_a_bearer_and_the_body_as_json_and_reads_the_json_answer(self):
|
||||
base = self.serve((201, b'{"id": "post-id"}'))
|
||||
self.assertEqual(dm.http_json("POST", f"{base}/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"})
|
||||
[(method, path, headers, body)] = self.server.got # type: ignore[attr-defined]
|
||||
self.assertEqual((method, path, headers["Authorization"], headers["Content-Type"], json.loads(body)), ("POST", "/api/v4/posts", "Bearer secret-token", "application/json", {"message": "hi"}))
|
||||
|
||||
def test_names_the_request_the_status_and_mattermosts_message_on_an_error(self):
|
||||
base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}'))
|
||||
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again."))
|
||||
|
||||
def test_follows_no_redirect_so_the_token_goes_only_to_the_server_named(self):
|
||||
base = self.serve((302, b"{}"))
|
||||
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found"))
|
||||
self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined]
|
||||
|
||||
def test_sends_no_body_with_a_get(self):
|
||||
base = self.serve((200, b'{"id": "bot-id"}'))
|
||||
dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
|
||||
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
|
||||
self.assertEqual((headers.get("Content-Length"), body), (None, b""))
|
||||
|
||||
def test_fails_on_an_answer_that_breaks_http(self):
|
||||
for raw in (b"garbage\r\n\r\n", b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{}"):
|
||||
with self.subTest(raw=raw):
|
||||
base = self.serve((None, raw))
|
||||
failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
|
||||
self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith("GET /api/v4/users/me got a broken answer: "), failed)
|
||||
|
||||
def test_names_the_status_of_an_error_whose_body_is_cut_short(self):
|
||||
base = self.serve((None, b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 100\r\n\r\n{}"))
|
||||
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 500: Internal Server Error"))
|
||||
|
||||
def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self):
|
||||
silent = socket.socket()
|
||||
self.addCleanup(silent.close)
|
||||
silent.bind(("127.0.0.1", 0))
|
||||
silent.listen(1)
|
||||
base = f"http://127.0.0.1:{silent.getsockname()[1]}"
|
||||
with unittest.mock.patch.object(dm, "TIMEOUT", 0.2):
|
||||
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure(f"cannot reach {base}: timed out"))
|
||||
|
||||
def test_fails_on_an_answer_that_is_not_json(self):
|
||||
base = self.serve((200, b"<html>"))
|
||||
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON"))
|
||||
|
||||
def test_fails_naming_the_server_it_cannot_reach(self):
|
||||
base = self.serve()
|
||||
self.server.server_close()
|
||||
failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertTrue(str(getattr(failed, "reason", "")).startswith(f"cannot reach {base}: "), failed)
|
||||
def test_reads_mattermosts_message_from_an_error_answer(self):
|
||||
for answer, message in (({"message": "Invalid or expired session."}, "Invalid or expired session."), ({"message": 7}, ""), ({}, ""), (["message"], "")):
|
||||
with self.subTest(answer=answer):
|
||||
self.assertEqual(dm.error_message(answer), message)
|
||||
|
||||
|
||||
class Project(unittest.TestCase):
|
||||
|
||||
+101
-88
@@ -1,75 +1,72 @@
|
||||
"""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.
|
||||
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 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 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 release_plan.todo_table import is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE
|
||||
from mattermost_dm.dm import parse_env
|
||||
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, which one Atlassian account's API token opens both.
|
||||
# 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
|
||||
# The adf-codec containers run at once: each description is one run.
|
||||
CONVERSIONS = 8
|
||||
# The adf-codec containers run at once, each converting one description: one heavy slot's CPUs.
|
||||
CONVERSIONS = 4
|
||||
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.
|
||||
# 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[[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")
|
||||
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)
|
||||
@@ -92,13 +89,11 @@ class JiraPlan:
|
||||
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")
|
||||
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)
|
||||
@@ -111,31 +106,26 @@ class JiraPlan:
|
||||
|
||||
|
||||
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)}")
|
||||
"""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[dict[str, typing.Any]] | Failure:
|
||||
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[dict[str, typing.Any]] = []
|
||||
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):
|
||||
@@ -149,48 +139,71 @@ def children(epic: Epic, authorization: str, http: Http) -> list[dict[str, typin
|
||||
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."""
|
||||
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):
|
||||
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 is of another type")
|
||||
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 not re.fullmatch(rf"{re.escape(project)}-[0-9]+", issue["key"])]:
|
||||
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 = {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)])
|
||||
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 each costs a container run, which a read that fails doesn't need.
|
||||
texts = details(issues, 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 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 details(issues: list[Issue], to_markdown: ToMarkdown) -> dict[int, str] | Failure:
|
||||
"""Each described issue's description as markdown, under the issue's number. The first converts alone, since that run builds the codec's image where the machine has none; the rest convert CONVERSIONS at a time."""
|
||||
described = [(issue, issue.description) for issue in issues if issue.description is not None]
|
||||
texts: list[str | Failure] = [to_markdown(description) for _, description in described[:1]]
|
||||
if not any(isinstance(text, Failure) for text in texts):
|
||||
with concurrent.futures.ThreadPoolExecutor(CONVERSIONS) as pool:
|
||||
texts += pool.map(to_markdown, [description for _, description in described[1:]])
|
||||
found = {}
|
||||
for (issue, _), text in zip(described, texts):
|
||||
if isinstance(text, Failure):
|
||||
return Failure(f"{issue.key}'s description: {text.reason}")
|
||||
found[issue.number] = text.strip()
|
||||
return found
|
||||
|
||||
|
||||
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"]])
|
||||
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"{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, {}))
|
||||
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
|
||||
return Item(number(key), release, scored[2], bold_cell(fields["summary"].strip()), scored[0], scored[1], tuple(sorted(set(blockers) & ids)), text)
|
||||
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: list[str]) -> Release | None:
|
||||
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)
|
||||
@@ -209,5 +222,5 @@ def scores(key: str, held: object) -> tuple[dict[str, int], typing.Any, typing.A
|
||||
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 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
|
||||
|
||||
@@ -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. 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.
|
||||
The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues `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
|
||||
@@ -44,7 +44,7 @@ class Written:
|
||||
|
||||
|
||||
class PlanStore(typing.Protocol):
|
||||
"""A project's plan. plan_store.contract holds every backend to the same behaviour. A write that fails leaves the plan as it was."""
|
||||
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` only reads until todo.md's item 352. A write that fails leaves the plan as it was."""
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
|
||||
@@ -3,6 +3,7 @@ import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
@@ -14,6 +15,7 @@ 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"
|
||||
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
|
||||
|
||||
|
||||
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]:
|
||||
@@ -42,13 +44,24 @@ class JiraPlan(unittest.TestCase):
|
||||
self.env.chmod(0o600)
|
||||
self.pages: list[object] = []
|
||||
self.calls: list[tuple[str, str, str, object]] = []
|
||||
self.epic: object = {"key": "ABC-12"}
|
||||
self.epic_calls: list[tuple[str, str, str, object]] = []
|
||||
self.converted: list[object] = []
|
||||
|
||||
def http(self, method: str, url: str, authorization: str, body: object) -> object:
|
||||
"""Stands in for Jira: answers self.epic to the request for the epic, and the next of self.pages to each search."""
|
||||
if method == "GET":
|
||||
self.epic_calls.append((method, url, authorization, body))
|
||||
return self.epic
|
||||
self.calls.append((method, url, authorization, body))
|
||||
return self.pages[len(self.calls) - 1]
|
||||
|
||||
def to_markdown(self, document: dict[str, object]) -> str | Failure:
|
||||
self.converted.append(document)
|
||||
return text_of(document)
|
||||
|
||||
def store(self) -> jira_epic.JiraPlan:
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of)
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, self.to_markdown)
|
||||
|
||||
def read(self, *issues: dict[str, object]) -> Plan | Failure:
|
||||
self.pages, self.calls = [{"issues": list(issues)}], []
|
||||
@@ -66,7 +79,7 @@ class JiraPlan(unittest.TestCase):
|
||||
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(authorization, AUTHORIZATION)
|
||||
self.assertEqual(body, {
|
||||
"jql": 'parent = "ABC-12" AND statusCategory != Done ORDER BY Rank ASC',
|
||||
"fields": ["summary", "description", "fixVersions", "issuelinks"],
|
||||
@@ -74,6 +87,12 @@ class JiraPlan(unittest.TestCase):
|
||||
"maxResults": 100,
|
||||
})
|
||||
|
||||
def test_an_epic_that_cannot_be_read_fails_the_read_before_any_search(self):
|
||||
self.epic = Failure("GET /rest/api/3/issue/ABC-12 answered 404: Issue does not exist or you do not have permission to see it.")
|
||||
self.assertEqual(self.read(), Failure("cannot read the epic ABC-12: GET /rest/api/3/issue/ABC-12 answered 404: Issue does not exist or you do not have permission to see it."))
|
||||
self.assertEqual(self.epic_calls, [("GET", "https://acme.atlassian.net/rest/api/3/issue/ABC-12?fields=summary", AUTHORIZATION, None)])
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
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.")))
|
||||
@@ -96,15 +115,16 @@ class JiraPlan(unittest.TestCase):
|
||||
|
||||
def test_the_release_is_the_earliest_fix_version_with_or_without_a_v(self):
|
||||
for versions in (("v1.2.0", "0.9.1", "Later"), ("1.2.0", "v0.9.1")):
|
||||
item, = self.items(issue("ABC-34", versions=versions))
|
||||
self.assertEqual(item.release, release_of("0.9.1"), versions)
|
||||
with self.subTest(versions=versions):
|
||||
item, = self.items(issue("ABC-34", versions=versions))
|
||||
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]
|
||||
with self.subTest(versions=versions):
|
||||
failure = self.read(issue("ABC-33", description=adf("Why.")), issue("ABC-34", versions=versions))
|
||||
self.assertEqual(failure, Failure("ABC-34 names no Fix Version that is a semver version, such as 1.2.0; set one in Jira"))
|
||||
self.assertEqual(self.converted, [])
|
||||
|
||||
def test_a_child_in_another_jira_project_fails_the_read_naming_it(self):
|
||||
failure = self.read(issue("ABC-34"), issue("OTHER-5"))
|
||||
@@ -113,9 +133,13 @@ class JiraPlan(unittest.TestCase):
|
||||
|
||||
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]
|
||||
with self.subTest(scores=scores):
|
||||
failure = self.read(issue("ABC-34", scores=scores)) # type: ignore[arg-type]
|
||||
self.assertIsInstance(failure, Failure)
|
||||
self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr]
|
||||
|
||||
def test_an_exempt_out_of_format_fails_naming_the_reasons_it_may_hold(self):
|
||||
self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("ABC-34's issue property plan-item holds the Exempt 'because', which is not empty or one of decision, defect, owner, principle, question, security"))
|
||||
|
||||
def test_reads_every_page(self):
|
||||
self.pages = [{"issues": [issue("ABC-1")], "nextPageToken": "t1"}, {"issues": [issue("ABC-2")]}]
|
||||
@@ -126,12 +150,33 @@ class JiraPlan(unittest.TestCase):
|
||||
|
||||
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"))
|
||||
self.assertEqual(self.store().read(), Failure("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)
|
||||
for page in ([], {"issues": "none"}, {"issues": ["ABC-1"]}, {"issues": [{"key": 7, "fields": {}}]}, {"issues": [{"key": "abc", "fields": {}}]}):
|
||||
with self.subTest(page=page):
|
||||
self.pages, self.calls = [page], []
|
||||
self.assertIsInstance(self.store().read(), Failure)
|
||||
|
||||
def test_an_issue_in_another_shape_fails_the_read_naming_it(self):
|
||||
good = issue("ABC-1")
|
||||
for wrong in ({"key": "ABC-1"}, issue("ABC-1", summary=None), issue("ABC-1", description="text"), good | {"fields": good["fields"] | {"fixVersions": [{"name": 7}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": 7}}]}}, good | {"properties": None}): # type: ignore[arg-type, operator]
|
||||
with self.subTest(wrong=wrong):
|
||||
failure = self.read(wrong) # type: ignore[arg-type]
|
||||
self.assertIsInstance(failure, Failure)
|
||||
self.assertTrue(failure.reason.startswith("ABC-1 is not in the shape Jira Cloud's REST API version 3 documents: "), failure) # type: ignore[union-attr]
|
||||
|
||||
def test_converts_each_description_once_and_none_for_an_issue_without_one(self):
|
||||
found = self.items(issue("ABC-1", description=adf("One.")), issue("ABC-2"), issue("ABC-3", description=adf("Three.")), issue("ABC-4", description=adf("Four.")))
|
||||
self.assertEqual([item.detail for item in found], ["One.", "", "Three.", "Four."])
|
||||
self.assertEqual(len(self.converted), 3)
|
||||
|
||||
def test_a_first_description_the_codec_refuses_converts_no_other(self):
|
||||
calls: list[object] = []
|
||||
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: calls.append(document) or Failure("no docker")) # type: ignore[func-returns-value]
|
||||
self.pages = [{"issues": [issue("ABC-1", description=adf("One.")), issue("ABC-2", description=adf("Two."))]}]
|
||||
self.assertEqual(store.read(), Failure("ABC-1's description: no docker"))
|
||||
self.assertEqual(len(calls), 1)
|
||||
|
||||
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"))
|
||||
@@ -143,12 +188,12 @@ class JiraPlan(unittest.TestCase):
|
||||
failure = self.read()
|
||||
self.assertIsInstance(failure, Failure)
|
||||
self.assertIn("ATLASSIAN_API_TOKEN", failure.reason) # type: ignore[union-attr]
|
||||
self.assertEqual(self.calls, [])
|
||||
self.assertEqual(self.calls + self.epic_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, [])
|
||||
self.assertEqual(self.read(), Failure(f"{self.env} holds an API token, so only its owner may read it; run chmod 600 {self.env}"))
|
||||
self.assertEqual(self.calls + self.epic_calls, [])
|
||||
|
||||
def test_a_missing_env_file_fails(self):
|
||||
self.env.unlink()
|
||||
@@ -161,12 +206,32 @@ class JiraPlan(unittest.TestCase):
|
||||
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, [])
|
||||
with self.subTest(written=written):
|
||||
self.assertEqual(written, Failure("a plan in Jira is only read so far: file, edit and finish its issues in Jira"))
|
||||
self.assertEqual(self.calls + self.epic_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))
|
||||
|
||||
|
||||
class Requests(unittest.TestCase):
|
||||
def test_sends_each_request_through_the_shared_client_with_jiras_error_messages(self):
|
||||
with unittest.mock.patch.object(jira_epic.json_request, "http_json", return_value={"issues": []}) as sent:
|
||||
self.assertEqual(jira_epic.http_json("POST", SEARCH, AUTHORIZATION, {"jql": "x"}), {"issues": []})
|
||||
sent.assert_called_once_with("POST", SEARCH, AUTHORIZATION, {"jql": "x"}, 30, jira_epic.error_message)
|
||||
|
||||
def test_reads_jiras_messages_from_an_error_answer(self):
|
||||
cases = (
|
||||
({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."),
|
||||
({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."),
|
||||
({"errorMessages": "One.", "errors": ["Two."]}, ""),
|
||||
({"errorMessages": [7, "One."]}, "One."),
|
||||
(["One."], ""),
|
||||
)
|
||||
for answer, message in cases:
|
||||
with self.subTest(answer=answer):
|
||||
self.assertEqual(jira_epic.error_message(answer), message)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Reads the credentials a tool needs from an env file: KEY=value lines that only the file's owner may read."""
|
||||
import pathlib
|
||||
|
||||
from failure import Failure
|
||||
|
||||
|
||||
def read_env(path: pathlib.Path, keys: tuple[str, ...], secret: str) -> dict[str, str] | Failure:
|
||||
"""The value of each of keys in path. secret names what the file holds, such as `an API token`, for the Failure that says who may read it."""
|
||||
try:
|
||||
mode = path.stat().st_mode
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return Failure(f"{path} does not exist; it needs {', '.join(keys[:-1])} and {keys[-1]}")
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"cannot read {path}: {failure}")
|
||||
if mode & 0o077:
|
||||
return Failure(f"{path} holds {secret}, so only its owner may read it; run chmod 600 {path}")
|
||||
values = parse_env(text)
|
||||
if missing := [key for key in keys if not values.get(key)]:
|
||||
return Failure(f"{path} lacks {' and '.join(missing)}")
|
||||
return {key: values[key] for key in keys}
|
||||
|
||||
|
||||
def parse_env(text: str) -> dict[str, str]:
|
||||
values = {}
|
||||
for line in text.splitlines():
|
||||
key, equals, value = line.partition("=")
|
||||
if not equals or key.lstrip().startswith("#"):
|
||||
continue
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
|
||||
value = value[1:-1]
|
||||
values[key.strip()] = value
|
||||
return values
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Sends one request to a REST API that speaks JSON, with a credential that no redirect may carry elsewhere."""
|
||||
import http.client
|
||||
import json
|
||||
import typing
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from failure import Failure
|
||||
|
||||
# The API's own message in the JSON of an error answer; empty where it holds none.
|
||||
MessageOf = typing.Callable[[object], str]
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
"""Refuses every redirect, which a REST API doesn't send: urllib would resend the credential 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, seconds: int, message_of: MessageOf) -> object:
|
||||
"""The JSON that url answers to a request with the Authorization header given, and body as JSON where there is one. A Failure names the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON. Each connect and each read may wait that many seconds."""
|
||||
request_name = f"{method} {urllib.parse.urlsplit(url).path}"
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
request = urllib.request.Request(url, data, {"Authorization": authorization, "Content-Type": "application/json", "Accept": "application/json"}, method=method)
|
||||
try:
|
||||
with OPENER.open(request, timeout=seconds) as response:
|
||||
raw = response.read()
|
||||
except urllib.error.HTTPError as failure:
|
||||
with failure:
|
||||
return Failure(f"{request_name} answered {failure.code}: {error_message(failure, message_of) or failure.reason}")
|
||||
except http.client.HTTPException as failure:
|
||||
return Failure(f"{request_name} got a broken answer: {failure!r}")
|
||||
except (OSError, ValueError) as failure:
|
||||
server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", ""))
|
||||
return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}")
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except ValueError:
|
||||
return Failure(f"{request_name} answered with something other than JSON")
|
||||
|
||||
|
||||
def error_message(failure: urllib.error.HTTPError, message_of: MessageOf) -> str:
|
||||
"""The API's message in an error answer; empty where the body is cut short, breaks HTTP or holds none."""
|
||||
try:
|
||||
return message_of(json.loads(failure.read()))
|
||||
except (http.client.HTTPException, OSError, ValueError):
|
||||
return ""
|
||||
@@ -0,0 +1,50 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from rest_client.env_file import parse_env, read_env
|
||||
|
||||
KEYS = ("SITE", "USER", "TOKEN")
|
||||
|
||||
|
||||
class ReadEnv(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.path = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / ".env"
|
||||
|
||||
def write(self, text: str, mode: int = 0o600) -> None:
|
||||
self.path.write_text(text)
|
||||
self.path.chmod(mode)
|
||||
|
||||
def test_reads_the_keys_asked_for_and_no_other(self):
|
||||
self.write("SITE=https://a.example\nUSER=me\nTOKEN=s3cret\nOTHER=x\n")
|
||||
self.assertEqual(read_env(self.path, KEYS, "a token"), {"SITE": "https://a.example", "USER": "me", "TOKEN": "s3cret"})
|
||||
|
||||
def test_a_missing_file_fails_naming_every_key_it_needs(self):
|
||||
self.assertEqual(read_env(self.path, KEYS, "a token"), Failure(f"{self.path} does not exist; it needs SITE, USER and TOKEN"))
|
||||
|
||||
def test_a_file_lacking_keys_or_holding_empty_ones_fails_naming_them(self):
|
||||
self.write("SITE=https://a.example\nUSER=\n")
|
||||
self.assertEqual(read_env(self.path, KEYS, "a token"), Failure(f"{self.path} lacks USER and TOKEN"))
|
||||
|
||||
def test_a_file_that_group_or_others_may_read_fails_naming_the_secret(self):
|
||||
for mode in (0o640, 0o604, 0o610):
|
||||
with self.subTest(mode=oct(mode)):
|
||||
self.write("SITE=a\nUSER=b\nTOKEN=c\n", mode)
|
||||
self.assertEqual(read_env(self.path, KEYS, "a token"), Failure(f"{self.path} holds a token, so only its owner may read it; run chmod 600 {self.path}"))
|
||||
|
||||
def test_a_file_that_cannot_be_read_as_text_fails(self):
|
||||
self.path.write_bytes(b"TOKEN=\xff\n")
|
||||
self.path.chmod(0o600)
|
||||
failed = read_env(self.path, KEYS, "a token")
|
||||
self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith(f"cannot read {self.path}: "), failed)
|
||||
|
||||
def test_parses_quotes_comments_and_spaces(self):
|
||||
self.assertEqual(parse_env("# note\nA = 1 \nB=\"two words\"\nC='3'\nnot a pair\n#D=4\nE=a=b\n"), {"A": "1", "B": "two words", "C": "3", "E": "a=b"})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,120 @@
|
||||
import http.server
|
||||
import json
|
||||
import pathlib
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from rest_client import json_request
|
||||
|
||||
|
||||
def message(answer: object) -> str:
|
||||
return answer.get("message", "") if isinstance(answer, dict) else ""
|
||||
|
||||
|
||||
def send(method: str, url: str, token: str, body: object, seconds: float = 5) -> object:
|
||||
return json_request.http_json(method, url, f"Bearer {token}", body, seconds, message) # type: ignore[arg-type]
|
||||
|
||||
|
||||
class Recorded(http.server.BaseHTTPRequestHandler):
|
||||
"""Answers each request with the server's next scripted status and body, recording what it got."""
|
||||
|
||||
def do_GET(self) -> None:
|
||||
self.answer()
|
||||
|
||||
def do_POST(self) -> None:
|
||||
self.answer()
|
||||
|
||||
def answer(self) -> None:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined]
|
||||
status, body = self.server.script.pop(0) # type: ignore[attr-defined]
|
||||
if status is None:
|
||||
# Raw bytes, as a server that breaks HTTP sends them.
|
||||
self.wfile.write(body)
|
||||
self.close_connection = True
|
||||
return
|
||||
self.send_response(status)
|
||||
if 300 <= status < 400:
|
||||
self.send_header("Location", "/elsewhere")
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, format: str, *args: object) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class HttpJson(unittest.TestCase):
|
||||
def serve(self, *script: tuple[int, bytes]) -> str:
|
||||
server = http.server.HTTPServer(("127.0.0.1", 0), Recorded)
|
||||
server.script = list(script) # type: ignore[attr-defined]
|
||||
server.got = [] # type: ignore[attr-defined]
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
self.addCleanup(server.server_close)
|
||||
self.addCleanup(server.shutdown)
|
||||
self.server = server
|
||||
return f"http://127.0.0.1:{server.server_port}"
|
||||
|
||||
def test_sends_the_authorization_and_the_body_as_json_and_reads_the_json_answer(self):
|
||||
base = self.serve((201, b'{"id": "post-id"}'))
|
||||
self.assertEqual(send("POST", f"{base}/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"})
|
||||
[(method, path, headers, body)] = self.server.got # type: ignore[attr-defined]
|
||||
self.assertEqual((method, path, headers["Authorization"], headers["Content-Type"], headers["Accept"], json.loads(body)), ("POST", "/api/v4/posts", "Bearer secret-token", "application/json", "application/json", {"message": "hi"}))
|
||||
|
||||
def test_names_the_request_the_status_and_the_apis_message_on_an_error(self):
|
||||
base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}'))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again."))
|
||||
|
||||
def test_follows_no_redirect_so_the_token_goes_only_to_the_server_named(self):
|
||||
base = self.serve((302, b"{}"))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found"))
|
||||
self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined]
|
||||
|
||||
def test_sends_no_body_with_a_get(self):
|
||||
base = self.serve((200, b'{"id": "bot-id"}'))
|
||||
send("GET", f"{base}/api/v4/users/me", "t", None)
|
||||
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
|
||||
self.assertEqual((headers.get("Content-Length"), body), (None, b""))
|
||||
|
||||
def test_fails_on_an_answer_that_breaks_http(self):
|
||||
for raw in (b"garbage\r\n\r\n", b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{}"):
|
||||
with self.subTest(raw=raw):
|
||||
base = self.serve((None, raw))
|
||||
failed = send("GET", f"{base}/api/v4/users/me", "t", None)
|
||||
self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith("GET /api/v4/users/me got a broken answer: "), failed)
|
||||
|
||||
def test_names_the_status_of_an_error_whose_body_is_cut_short(self):
|
||||
base = self.serve((None, b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 100\r\n\r\n{}"))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 500: Internal Server Error"))
|
||||
|
||||
def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self):
|
||||
silent = socket.socket()
|
||||
self.addCleanup(silent.close)
|
||||
silent.bind(("127.0.0.1", 0))
|
||||
silent.listen(1)
|
||||
base = f"http://127.0.0.1:{silent.getsockname()[1]}"
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None, 0.2), Failure(f"cannot reach {base}: timed out"))
|
||||
|
||||
def test_fails_on_an_answer_that_is_not_json(self):
|
||||
base = self.serve((200, b"<html>"))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON"))
|
||||
|
||||
def test_fails_naming_the_server_it_cannot_reach(self):
|
||||
base = self.serve()
|
||||
self.server.server_close()
|
||||
failed = send("GET", f"{base}/api/v4/users/me", "t", None)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertTrue(str(getattr(failed, "reason", "")).startswith(f"cannot reach {base}: "), failed)
|
||||
|
||||
def test_an_error_whose_body_is_not_json_names_the_status_alone(self):
|
||||
base = self.serve((403, b"<html>"))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 403: Forbidden"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -33,8 +33,11 @@ def todo_breaches(directory: str, home: pathlib.Path, own: pathlib.Path = OWN) -
|
||||
unconfigured = pathlib.Path(top) / "todo.md"
|
||||
return [Breach("todo-rank-check", config.reason, top)] if unconfigured.is_file() and changed(top, unconfigured, "todo.md") else []
|
||||
todo, tracked = config.plan_file, config.tracked("plan")
|
||||
# A plan outside the checkout has no commit in the checkout to differ from, so it is checked on every call. A plan in Jira is no file, and Jira's backlog ranks it.
|
||||
if todo is None or not todo.is_file() or (tracked is not None and not changed(top, todo, tracked)):
|
||||
# A plan in Jira is no file, and Jira's backlog ranks it.
|
||||
if todo is None or not todo.is_file():
|
||||
return []
|
||||
# A plan outside the checkout has no commit in the checkout to differ from, so it is checked on every call.
|
||||
if tracked is not None and not changed(top, todo, tracked):
|
||||
return []
|
||||
return [Breach("todo-rank-check", line, top) for line in check_failures(top, todo, config, own)]
|
||||
|
||||
@@ -43,8 +46,10 @@ def folder_breaches(top: str, config: ProjectConfig | Failure, own: pathlib.Path
|
||||
"""Why the plan kept in top, a config's folder, is not ranked, where the plan has changed in that folder's repo; ranked as for a commit in the project's checkout.
|
||||
|
||||
A config that fails to load doesn't block anything here, so that the commit that fixes it goes through."""
|
||||
todo = None if isinstance(config, Failure) else config.plan_file
|
||||
if isinstance(config, Failure) or todo is None or not todo.is_relative_to(config.folder):
|
||||
if isinstance(config, Failure):
|
||||
return []
|
||||
todo = config.plan_file
|
||||
if todo is None or not todo.is_relative_to(config.folder):
|
||||
return []
|
||||
if not todo.is_file() or not changed(str(config.folder), todo, todo.relative_to(config.folder).as_posix()):
|
||||
return []
|
||||
|
||||
@@ -10,14 +10,15 @@ usage: todo-item list [--release <version>]
|
||||
todo-item finish <ID> [--changelog <bullet> | --no-changelog]
|
||||
|
||||
Run inside a checkout. Every command works on the plan the project's config names, which
|
||||
`project-config plan` prints. The commands work the same whatever holds the plan.
|
||||
Today a markdown file, todo.md, holds it. Each command that changes the file ranks it as rank_todo.py
|
||||
does, and so reads the goals file, docs/decisions.md and the comprehension history, each where the
|
||||
config puts it.
|
||||
`project-config plan` prints: a markdown file, todo.md, or a Jira epic. A plan in a Jira epic is
|
||||
only read so far: list and show work, and add, edit, move and finish fail. Each command that changes
|
||||
a todo.md ranks it as rank_todo.py does, and so reads the goals file, docs/decisions.md and the
|
||||
comprehension history, each where the config puts it.
|
||||
The cells take the format rank_todo.py --help states; the letter flags take upper case too, as --L.
|
||||
|
||||
list prints `From <plan>, in its order:`, then the table's header and divider and one row per item,
|
||||
without details: first the earliest release, and within a release the item to take first.
|
||||
A plan in a Jira epic lists in Jira's backlog order instead.
|
||||
--release prints one release's items. Where no item fits, it prints `<plan> holds no item.`
|
||||
|
||||
show prints `From <plan>:`, then the table's header and divider, item <ID>'s row, and its detail under
|
||||
|
||||
Reference in New Issue
Block a user