✨ Collect changelog inputs in one command

Gather milestone issues, pull requests, advisories, and changelog checks
into one JSON snapshot. Reuse it across the release workflow to avoid
repeating GitHub queries while keeping write actions separate.

AI-assisted-by: gpt-6.2-sol
This commit is contained in:
Andrey Antukh 2026-11-23 08:40:20 +00:00
parent b822b38279
commit 5e1e0bef34
5 changed files with 320 additions and 43 deletions

View File

@ -30,26 +30,32 @@ memory; it does not repeat it.
1. `mem:workflow/updating-changelog` — the canonical flow: sources of truth,
layout, entry rules, the `## Breaking change note` comment contract, the
advisory (`:lock:`) contract, pre-flight checks, anomaly types, and pitfalls.
2. `mem:scripts/changelog` — `boom`, `security`, `check-merged`, `cross-ref`,
2. `mem:scripts/changelog` — `collect`, `boom`, `security`, `check-merged`, `cross-ref`,
`dev-only-bugs`, `report`.
3. `mem:scripts/gh` — `issues`, `issue`, `comments`, `prs`, `advisories`.
## Commands
```bash
python3 scripts/gh.py issues "<VERSION>" --exclude "release blocker,no changelog"
python3 scripts/gh.py advisories --patched-version "<VERSION>"
python3 scripts/changelog.py dev-only-bugs "<VERSION>" # list bugs that never reached production
python3 scripts/changelog.py dev-only-bugs "<VERSION>" --apply # label the sure ones `no changelog`
python3 scripts/changelog.py check-merged <PR numbers...>
python3 scripts/changelog.py boom "<VERSION>" # print the :boom: section
python3 scripts/changelog.py boom "<VERSION>" --write # replace it in CHANGES.md
python3 scripts/changelog.py security "<VERSION>" # print the :lock: section
python3 scripts/changelog.py security "<VERSION>" --write # replace it in CHANGES.md
python3 scripts/changelog.py cross-ref "<VERSION>"
python3 scripts/changelog.py report "<VERSION>"
snapshot=$(mktemp)
python3 scripts/changelog.py collect "<VERSION>" > "$snapshot"
```
Review the JSON before running any of these commands:
```bash
python3 scripts/changelog.py dev-only-bugs "<VERSION>" --snapshot "$snapshot" --apply
python3 scripts/changelog.py boom "<VERSION>" --snapshot "$snapshot" --write
python3 scripts/changelog.py security "<VERSION>" --snapshot "$snapshot" --write
python3 scripts/changelog.py cross-ref "<VERSION>" --snapshot "$snapshot"
python3 scripts/changelog.py report "<VERSION>" --snapshot "$snapshot"
```
Keep the snapshot private: it can contain unpublished advisories and PR text.
Run `collect` first and use the JSON for review and
merge-state checks. Run `collect` again after any GitHub change, including
`dev-only-bugs --apply`. Use `--apply` only when there are sure cases.
## Hard Rules
- `CHANGES.md` is edited only on explicit request or during the release process.

View File

@ -4,6 +4,8 @@
## Subcommands
- `collect <MILESTONE> [--changes CHANGES.md]` — read-only. Prints JSON to stdout with all milestone `issues` and `prs`, `eligible_issues` (issue numbers), `related_issues` and `related_prs` resolved in batches, `breaking_notes` keyed by issue number, `advisories`, `security_prs` keyed by GHSA, `dev_only_bugs` (`auto` and `suggested`), and `comparison` against the current changelog (references, missing and ineligible issues, cross-version duplicates, unlisted merged PRs). A missing version section is valid. Keep the snapshot private; it can contain unpublished advisories and PR text. See `mem:workflow/updating-changelog` for when to refresh it.
- `boom`, `security`, `cross-ref`, `dev-only-bugs` and `report` accept `--snapshot <FILE>` to reuse GitHub data from `collect` for the same milestone. `cross-ref` and `report` still read the current changelog; `--write`, `--apply` and `report` retain their existing write behavior. Without a snapshot, commands query GitHub as before.
- `check-merged <PR...>` (`--file`, `--stdin` accepted) — warn on any non-merged PR, exit 1 when found; run before writing changelog entries.
- `boom <MILESTONE> [--changes CHANGES.md --write]` — generate `### :boom: Breaking changes & Deprecations` from the closed, non-excluded milestone issues labelled `breaking change`, sorted by issue number. Each issue becomes a `#### <issue title>` block: content = body of the issue's last `## Breaking change note` comment (whole markdown, headings demoted to `#####` outside code fences; fallback = heading plus refs with a stderr warning), refs = issue link plus merged closing PRs on their own line, with `(by @author)` for `community contribution`. `--write` replaces only that subsection of the version, inserts it after the version header when needed, and removes it when there are no entries. Print-only by default. Uses `gh.py comments`.
- `security <MILESTONE> [--changes CHANGES.md --write]` — generate `### :lock: Security fixes` from the advisories whose `patched_versions` include the version (via `gh.py advisories --patched-version`), sorted by GHSA id. Entry: `- Fix <description> (<advisory URL>) (PR: [#N](...))`; description = `Fix` + advisory summary, first word decapitalized unless it starts with an acronym; PRs = merged milestone PRs labelled `pr pt` whose body contains the GHSA id, comma-separated, and no PR is legal. Warns on stderr when a `pr pt` PR references an advisory with no matching `patched_versions`. `--write` replaces only that subsection, placed after `:rocket:` (or `:boom:`, or the version header when neither exists); empty entries remove the subsection; idempotent. Print-only by default.

View File

@ -158,23 +158,23 @@ Generated from the advisories that declare the version in `patched_versions`; ne
## 8. Flow
1. **Confirm the version** (a semver string such as `2.19.0`) with the user when it is not obvious.
2. **Fetch the milestone issues**: `python3 scripts/gh.py issues "<VERSION>" --exclude "no changelog"` (closed by default; add `--state all` only to inspect open issues). `gh.py` already drops `Task` and `Rejected`; pass `--include-tasks` / `--include-rejected` only to inspect them. To find what is missing from an existing section, add `--compare CHANGES.md`.
3. **Keep out bugs that never reached production**: `python3 scripts/changelog.py dev-only-bugs "<VERSION>"` lists them; add `--apply` to label the sure ones `no changelog` on GitHub, then re-fetch step 2. The label puts the decision on the issue, so it survives a regeneration.
2. **Collect the release inputs**: `python3 scripts/changelog.py collect "<VERSION>" > "$snapshot"`. Use a private temporary file because the JSON can contain unpublished advisories and PR text. It contains the milestone issues and PRs, batched related records, generated-section inputs, dev-only bug candidates and a comparison with the current changelog. Use `eligible_issues` for changelog candidates and `comparison` for pre-flight. Collection does not write to the changelog or GitHub.
3. **Keep out bugs that never reached production**: review `dev_only_bugs` in the snapshot. If `auto` has entries, run `python3 scripts/changelog.py dev-only-bugs "<VERSION>" --snapshot "$snapshot" --apply` to label the sure ones `no changelog` on GitHub, then repeat step 2. The label puts the decision on the issue, so it survives a regeneration.
- **Sure**: a bug whose parent issue is a `Feature` or `Enhancement` of the same milestone. `--apply` labels these.
- **Candidates**: a bug whose parent is an epic of the same milestone, that carries the `regression` label, or whose "Affected versions" / "Environment" field names only hourly, develop, staging, PRE or the milestone version itself. `regression` also marks regressions users hit in production, and the field says where the bug was seen, not since when it exists, so never label these yourself: show them to the user, who labels the ones they confirm. The anomaly report lists them too (section 10).
4. **Fetch PR details when needed**: `python3 scripts/gh.py prs <numbers...>` (also `--milestone`). Use it for the PR author, labels and merge state.
4. **Resolve PR links** using `prs` and `related_prs` in the snapshot. Look up a PR separately only if you discover a candidate not already in the snapshot.
5. **Categorize** by Issue Type and the two labels (section 2), and **build the descriptions** (section 4).
6. **Verify PR merge status** before writing: `python3 scripts/changelog.py check-merged <PR numbers...>`. Only merged PRs go in the changelog; if a closing PR was closed unmerged, look for the PR that superseded it.
6. **Verify PR merge status** before writing: only include PRs with state `MERGED` in the snapshot or verified by `check-merged` if looked up separately. If a closing PR was closed unmerged, look for the PR that superseded it.
7. **Reconcile the existing text** (section 9).
8. **Generate `:boom:`**: `python3 scripts/changelog.py boom "<VERSION>"` prints the section; add `--write` to replace it in `CHANGES.md`. The write replaces only that subsection, inserts it after the version header when missing, keeps the heading when there are no entries, and is idempotent.
8. **Generate `:boom:`**: `python3 scripts/changelog.py boom "<VERSION>" --snapshot "$snapshot"` prints the section; add `--write` to update just that subsection in `CHANGES.md`. If there are no entries, `--write` removes the subsection or leaves it absent.
9. **Generate `:rocket:`** from the `release highlight` label (section 6).
10. **Generate `:lock:`**: `python3 scripts/changelog.py security "<VERSION>"` prints the section; add `--write` to replace it in `CHANGES.md`. The contract lives in section 7.
11. **Cross-check PRs**: `python3 scripts/changelog.py cross-ref "<VERSION>"`. It lists merged milestone PRs missing from the section and warns about closed (unmerged) PRs. PRs linked from `:lock:` count as referenced; an advisory with no PR is invisible here by design.
12. **Generate the anomaly report**: `python3 scripts/changelog.py report "<VERSION>"`. It overwrites `CHANGES-ISSUES.md` with the current state (section 10).
10. **Generate `:lock:`**: `python3 scripts/changelog.py security "<VERSION>" --snapshot "$snapshot"` prints the section; add `--write` to replace it in `CHANGES.md`. The contract lives in section 7.
11. **Cross-check PRs**: `python3 scripts/changelog.py cross-ref "<VERSION>" --snapshot "$snapshot"`. It compares the snapshot against the updated changelog, lists missing merged PRs and warns about closed (unmerged) PRs. PRs linked from `:lock:` count as referenced; an advisory with no PR is invisible here by design.
12. **Generate the anomaly report**: `python3 scripts/changelog.py report "<VERSION>" --snapshot "$snapshot"`. It reads the updated changelog and overwrites `CHANGES-ISSUES.md` (section 10). If you need the report to resolve a new reference not known to the snapshot, collect again first.
## 9. Pre-flight: reconcile before writing
Re-fetch the milestone (do not trust cached data) and fix these in `CHANGES.md` before adding the new section:
Start from a fresh `collect` snapshot. Refresh it if GitHub changes during review (labels, notes, advisories, or PRs). Fix these in `CHANGES.md` before adding the new section:
1. **Duplicate across versions** → remove it from the current section; the earlier version wins for backports.
2. **Stale milestone assignment** (the issue moved out of this milestone) → remove the entry.
@ -214,6 +214,6 @@ Anything else is a rule violation, not a report item: fix it in the pre-flight a
## 12. Where the code is
- `scripts/gh.py`: `issues`, `issue`, `comments`, `prs`, `link-issue`, `advisories` (with `--patched-version`). Details: `mem:scripts/gh`.
- `scripts/changelog.py`: `check-merged`, `boom`, `security`, `cross-ref`, `dev-only-bugs`, `report`. Details: `mem:scripts/changelog`.
- `scripts/changelog.py`: `collect`, `check-merged`, `boom`, `security`, `cross-ref`, `dev-only-bugs`, `report`. Details: `mem:scripts/changelog`.
- Tests: `scripts/test_gh.py`, `scripts/test_changelog.py`.
- The note contract for issue authors: `mem:workflow/creating-issues`, section **Breaking changes**.

View File

@ -6,6 +6,7 @@ Uses ``scripts/gh.py`` (via subprocess) and the local ``CHANGES.md`` so the
flow memory (`mem:workflow/updating-changelog`) stays free of inline programs.
Subcommands:
collect Collect the release inputs and changelog comparison as JSON
check-merged Verify that every given PR is merged (warns otherwise)
boom Generate the :boom: section from `breaking change` issues
security Generate the :lock: section from advisories fixed in a version
@ -14,6 +15,7 @@ Subcommands:
report Generate the anomaly report (CHANGES-ISSUES.md)
Usage:
python3 scripts/changelog.py collect "2.19.0"
python3 scripts/changelog.py check-merged 9179 9204 9311
cat prs.txt | python3 scripts/changelog.py check-merged --stdin
python3 scripts/changelog.py boom "2.19.0"
@ -111,6 +113,19 @@ def fetch_milestone_prs(milestone: str, state: str) -> list[dict]:
return json.loads(stdout)
def load_snapshot(args: argparse.Namespace) -> dict | None:
path = getattr(args, "snapshot", None)
if path is None:
return None
try:
snapshot = json.loads(Path(path).read_text(encoding="utf-8"))
if snapshot["milestone"] != args.milestone:
raise ValueError(f"expected milestone {args.milestone}")
except (OSError, ValueError, KeyError, TypeError) as err:
sys.exit(f"ERROR: invalid changelog snapshot {path}: {err}")
return snapshot
def extract_version_section(content: str, milestone: str) -> str:
"""Return the changelog body of a ``## <VERSION>`` section (or "")."""
match = re.search(
@ -351,24 +366,30 @@ def fetch_breaking_notes(issues: list[dict]) -> dict[int, str]:
return notes
def cmd_boom(args: argparse.Namespace) -> None:
"""Generate the ``:boom:`` section from ``breaking change`` issues."""
all_issues = json.loads(run_gh_py("issues", args.milestone, "--state", "all"))
labelled = sorted(
def breaking_issues(issues: list[dict]) -> list[dict]:
return sorted(
(
issue
for issue in all_issues
if BREAKING_LABEL in issue.get("labels", [])
and not issue_excluded(issue)
for issue in issues
if BREAKING_LABEL in issue.get("labels", []) and not issue_excluded(issue)
),
key=lambda issue: issue["number"],
)
notes: dict[int, str] = {}
prs: dict[int, dict] = {}
if labelled:
def cmd_boom(args: argparse.Namespace) -> None:
"""Generate the ``:boom:`` section from ``breaking change`` issues."""
snapshot = load_snapshot(args)
if snapshot is None:
labelled = breaking_issues(
json.loads(run_gh_py("issues", args.milestone, "--state", "all"))
)
notes = fetch_breaking_notes(labelled)
prs = fetch_prs_by_issue(labelled)
else:
labelled = breaking_issues(snapshot["issues"])
notes = {int(n): note for n, note in snapshot["breaking_notes"].items()}
prs = {pr["number"]: pr for pr in snapshot["prs"] + snapshot["related_prs"]}
entries: list[str] = []
for issue in labelled:
@ -462,8 +483,12 @@ def fetch_security_advisories(milestone: str) -> list[dict]:
def fetch_security_prs(milestone: str) -> dict[str, list[int]]:
"""Map each GHSA id to the merged ``pr pt`` PRs in a milestone referencing it."""
return security_prs_by_advisory(fetch_milestone_prs(milestone, "all"))
def security_prs_by_advisory(prs: list[dict]) -> dict[str, list[int]]:
by_ghsa: dict[str, list[int]] = {}
for pr in fetch_milestone_prs(milestone, "all"):
for pr in prs:
if pr.get("state") != "MERGED":
continue
if SECURITY_PR_LABEL not in pr.get("labels", []):
@ -541,8 +566,13 @@ def replace_security_section(
def cmd_security(args: argparse.Namespace) -> None:
"""Generate the ``:lock:`` section from advisories fixed in the version."""
milestone = args.milestone
advisories = fetch_security_advisories(milestone)
prs_by_ghsa = fetch_security_prs(milestone)
snapshot = load_snapshot(args)
if snapshot is None:
advisories = fetch_security_advisories(milestone)
prs_by_ghsa = fetch_security_prs(milestone)
else:
advisories = snapshot["advisories"]
prs_by_ghsa = snapshot["security_prs"]
matched = {
advisory["ghsa_id"].upper()
@ -606,7 +636,12 @@ def cmd_cross_ref(args: argparse.Namespace) -> None:
sys.exit(1)
changelog_refs = collect_changelog_prs(section)
milestone_prs = fetch_milestone_prs(args.milestone, "all")
snapshot = load_snapshot(args)
milestone_prs = (
fetch_milestone_prs(args.milestone, "all")
if snapshot is None
else snapshot["prs"]
)
merged = {pr["number"] for pr in milestone_prs if pr.get("state") == "MERGED"}
closed = [pr for pr in milestone_prs if pr.get("state") == "CLOSED"]
@ -712,7 +747,14 @@ def fetch_milestone_bugs(milestone: str) -> list[dict]:
def cmd_dev_only_bugs(args: argparse.Namespace) -> None:
"""List bugs that never reached production; --apply labels the sure ones."""
auto, suggested = find_dev_only_bugs(args.milestone, fetch_milestone_bugs(args.milestone))
snapshot = load_snapshot(args)
if snapshot is None:
auto, suggested = find_dev_only_bugs(
args.milestone, fetch_milestone_bugs(args.milestone)
)
else:
auto = snapshot["dev_only_bugs"]["auto"]
suggested = snapshot["dev_only_bugs"]["suggested"]
print(f"Label `no changelog` ({len(auto)}):")
for e in auto:
@ -731,6 +773,94 @@ def cmd_dev_only_bugs(args: argparse.Namespace) -> None:
print(f"Labelled {len(auto)} issues `no changelog`", file=sys.stderr)
def cmd_collect(args: argparse.Namespace) -> None:
"""Collect release inputs without changing the changelog or GitHub."""
milestone = args.milestone
content = Path(args.changes).read_text(encoding="utf-8")
section = extract_version_section(content, milestone)
issue_refs = collect_changelog_issues(section)
pr_refs = collect_changelog_prs(section)
issues = json.loads(
run_gh_py(
"issues",
milestone,
"--state",
"all",
"--include-tasks",
"--include-rejected",
)
)
prs = fetch_milestone_prs(milestone, "all")
eligible = {issue["number"] for issue in issues if not issue_excluded(issue)}
issue_numbers = {issue["number"] for issue in issues}
pr_numbers = {pr["number"] for pr in prs}
bugs = {
issue["number"]
for issue in issues
if issue["number"] in eligible and issue.get("issue_type") == "Bug"
}
related_issue_numbers = (
issue_refs | {n for pr in prs for n in pr.get("closing_issues", [])}
) - issue_numbers
detail_numbers = sorted(bugs | related_issue_numbers)
details = (
json.loads(run_gh_py("issue", *map(str, detail_numbers)))
if detail_numbers
else []
)
related_pr_numbers = (
pr_refs | {n for issue in issues for n in closing_pr_numbers(issue)}
) - pr_numbers
related_prs = (
fetch_prs_by_numbers(sorted(related_pr_numbers)) if related_pr_numbers else []
)
auto, suggested = find_dev_only_bugs(
milestone, [issue for issue in details if issue["number"] in bugs]
)
notes = fetch_breaking_notes(breaking_issues(issues))
advisories = fetch_security_advisories(milestone)
other_versions: dict[int, list[str]] = {}
for version_section in re.split(r"(?m)(?=^## \d+\.\d+\.\d+)", content):
header = re.match(r"^## (\d+\.\d+\.\d+)\b", version_section)
if header is None or header[1] == milestone:
continue
for number in sorted(
collect_changelog_issues(version_section) & (eligible | issue_refs)
):
other_versions.setdefault(number, []).append(header[1])
snapshot = {
"milestone": milestone,
"issues": issues,
"eligible_issues": sorted(eligible),
"prs": prs,
"related_issues": [
issue for issue in details if issue["number"] in related_issue_numbers
],
"related_prs": related_prs,
"breaking_notes": notes,
"advisories": advisories,
"security_prs": security_prs_by_advisory(prs),
"dev_only_bugs": {"auto": auto, "suggested": suggested},
"comparison": {
"section_exists": version_section_bounds(content, milestone) is not None,
"issue_refs": sorted(issue_refs),
"pr_refs": sorted(pr_refs),
"missing_issues": sorted(eligible - issue_refs - other_versions.keys()),
"ineligible_references": sorted(issue_refs - eligible),
"issues_in_other_versions": other_versions,
"unlisted_merged_prs": sorted(
pr["number"]
for pr in prs
if pr.get("state") == "MERGED" and pr["number"] not in pr_refs
),
},
}
print(json.dumps(snapshot, indent=2))
# ─────────────────────────────────────────────
# Subcommand: report
# ─────────────────────────────────────────────
@ -770,10 +900,14 @@ def cmd_report(args: argparse.Namespace) -> None:
"""Generate the changelog anomaly report and write it to a file."""
milestone = args.milestone
all_issues = json.loads(run_gh_py("issues", milestone, "--state", "all"))
snapshot = load_snapshot(args)
if snapshot is None:
all_issues = json.loads(run_gh_py("issues", milestone, "--state", "all"))
all_prs = fetch_milestone_prs(milestone, "all")
else:
all_issues = snapshot["issues"]
all_prs = snapshot["prs"]
issue_by_num = {i["number"]: i for i in all_issues}
all_prs = fetch_milestone_prs(milestone, "all")
pr_by_num = {p["number"]: p for p in all_prs}
with open(args.changes) as f:
@ -792,7 +926,10 @@ def cmd_report(args: argparse.Namespace) -> None:
for issue in issue_by_num.values():
unknown_prs.update(issue.get("closing_prs", []))
unknown_prs -= set(pr_milestone_cache)
if unknown_prs:
if snapshot is not None:
for pr in snapshot["related_prs"]:
pr_milestone_cache[pr["number"]] = pr.get("milestone")
elif unknown_prs:
print(
f"Resolving milestones for {len(unknown_prs)} PRs outside {milestone}...",
file=sys.stderr,
@ -807,7 +944,12 @@ def cmd_report(args: argparse.Namespace) -> None:
unknown_issues |= collect_changelog_issues(extract_subsection(section, r"### :rocket:"))
unknown_issues -= set(issue_milestone_cache)
external_issues: dict[int, dict] = {}
if unknown_issues:
if snapshot is not None:
for issue in snapshot["related_issues"]:
issue_milestone_cache[issue["number"]] = issue.get("milestone")
if "error" not in issue:
external_issues[issue["number"]] = issue
elif unknown_issues:
print(
f"Resolving milestones for {len(unknown_issues)} issues outside {milestone}...",
file=sys.stderr,
@ -989,7 +1131,13 @@ def cmd_report(args: argparse.Namespace) -> None:
anomalies_d.append({"version": ver, "line": line[:100]})
# Bugs that may never have reached production: warnings, not anomalies.
dev_auto, dev_suggested = find_dev_only_bugs(milestone, fetch_milestone_bugs(milestone))
if snapshot is None:
dev_auto, dev_suggested = find_dev_only_bugs(
milestone, fetch_milestone_bugs(milestone)
)
else:
dev_auto = snapshot["dev_only_bugs"]["auto"]
dev_suggested = snapshot["dev_only_bugs"]["suggested"]
def fmt_ms(ms: str | None) -> str:
return ms if ms else "_none_"
@ -1199,6 +1347,13 @@ def main() -> None:
)
sub = parser.add_subparsers(dest="command", required=True, title="subcommands")
p_collect = sub.add_parser("collect", help="Collect changelog inputs as JSON")
p_collect.add_argument("milestone", help="Milestone title (e.g. '2.19.0')")
p_collect.add_argument(
"--changes", default="CHANGES.md", help="Path to the changelog"
)
p_collect.set_defaults(func=cmd_collect)
p_check = sub.add_parser(
"check-merged", help="Verify that every given PR is merged"
)
@ -1258,6 +1413,11 @@ def main() -> None:
help="Report output path (default: CHANGES-ISSUES.md)")
p_report.set_defaults(func=cmd_report)
for command in (p_boom, p_security, p_cross, p_dev, p_report):
command.add_argument(
"--snapshot", help="Use JSON from collect instead of GitHub"
)
args = parser.parse_args()
args.func(args)

View File

@ -335,6 +335,115 @@ class CmdBoomTests(unittest.TestCase):
self.assertIn("Deploy the new service.", out)
class CollectTests(unittest.TestCase):
def test_collect_batches_extra_details_and_reuses_them_for_local_checks(self):
issues = [
{
"number": 1,
"state": "CLOSED",
"issue_type": "Bug",
"title": "Change a default",
"labels": ["breaking change"],
"closing_prs": [10, 11],
},
{"number": 2, "state": "OPEN", "issue_type": "Task"},
]
prs = [
{
"number": 10,
"title": "Change a default",
"state": "MERGED",
"closing_issues": [1, 3],
}
]
responses = {
(
"issues",
"2.19.0",
"--state",
"all",
"--include-tasks",
"--include-rejected",
): issues,
("prs", "--milestone", "2.19.0", "--state", "all"): prs,
("issue", "1", "3", "4"): [
{**issues[0], "body": "", "parent": None},
{"number": 3, "milestone": "2.18.0"},
{"number": 4, "error": "not_found"},
],
("prs", "11"): [{"number": 11, "state": "OPEN"}],
("comments", "1"): [
{"issue": 1, "body": "## Breaking change note\n\nNote."}
],
("advisories", "--patched-version", "2.19.0"): [],
}
content = (
"## 2.19.0\n\n[#4](https://github.com/penpot/penpot/issues/4)\n\n"
"## 2.18.0\n\n[#1](https://github.com/penpot/penpot/issues/1)\n"
)
with tempfile.TemporaryDirectory() as tmp:
changes = pathlib.Path(tmp) / "CHANGES.md"
changes.write_text(content)
snapshot_path = pathlib.Path(tmp) / "snapshot.json"
args = argparse.Namespace(milestone="2.19.0", changes=str(changes))
out = io.StringIO()
with (
patch.object(
ch, "run_gh_py", side_effect=lambda *a: json.dumps(responses[a])
) as gh,
contextlib.redirect_stdout(out),
):
ch.cmd_collect(args)
snapshot = json.loads(out.getvalue())
self.assertCountEqual([call.args for call in gh.call_args_list], responses)
self.assertEqual(changes.read_text(), content)
self.assertEqual(snapshot["eligible_issues"], [1])
self.assertEqual(snapshot["comparison"]["missing_issues"], [])
self.assertEqual(
snapshot["comparison"]["issues_in_other_versions"], {"1": ["2.18.0"]}
)
self.assertEqual(snapshot["comparison"]["ineligible_references"], [4])
self.assertEqual(snapshot["comparison"]["unlisted_merged_prs"], [10])
snapshot_path.write_text(out.getvalue())
changes.write_text(
content.replace(
"## 2.19.0\n\n",
"## 2.19.0\n\n[#10](https://github.com/penpot/penpot/pull/10)\n\n",
)
)
args.snapshot = str(snapshot_path)
args.write = False
args.output = str(pathlib.Path(tmp) / "report.md")
out = io.StringIO()
with (
patch.object(
ch,
"run_gh_py",
side_effect=AssertionError("unexpected GitHub lookup"),
),
contextlib.redirect_stdout(out),
):
ch.cmd_boom(args)
ch.cmd_security(args)
ch.cmd_dev_only_bugs(argparse.Namespace(**vars(args), apply=False))
ch.cmd_cross_ref(args)
ch.cmd_report(args)
self.assertIn("Note.", out.getvalue())
self.assertIn("pull/10", out.getvalue())
self.assertNotIn("pull/11", out.getvalue())
self.assertIn("PRs in milestone but NOT in changelog: 0", out.getvalue())
self.assertTrue(pathlib.Path(args.output).is_file())
def test_snapshot_for_another_milestone_is_rejected(self):
with tempfile.TemporaryDirectory() as tmp:
snapshot = pathlib.Path(tmp) / "snapshot.json"
snapshot.write_text('{"milestone": "2.18.0"}')
args = argparse.Namespace(milestone="2.19.0", snapshot=str(snapshot))
with self.assertRaisesRegex(SystemExit, "expected milestone 2.19.0"):
ch.load_snapshot(args)
class ReportTests(unittest.TestCase):
"""Focused check of the `:boom:` sync anomaly (type G) in the report."""