mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 13:30:43 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67e6565fc2 | ||
|
|
aac0f31b93 | ||
|
|
ef0e472d5d | ||
|
|
fa55066699 |
No files matched your search
@@ -46,6 +46,8 @@ jobs:
|
||||
run: |
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
|
||||
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
|
||||
- name: Test pull request template check
|
||||
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
|
||||
- name: Check formatting and lint
|
||||
run: |
|
||||
cargo fmt --all -- --check
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
name: PR template
|
||||
|
||||
# Fails when a pull request description does not follow
|
||||
# .github/PULL_REQUEST_TEMPLATE.md: every section present and filled in, a
|
||||
# linked issue ("Closes #N" or "No linked issue: <reason>"), and the
|
||||
# claimed-first and DCO checkboxes ticked. Runs again whenever the description
|
||||
# is edited; comments never start it. Runs on the base branch: pull request
|
||||
# code is never checked out or executed, and the description is read as data.
|
||||
#
|
||||
# To make it blocking, mark the "PR template / description" check as required
|
||||
# in the branch protection rule for main.
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, edited, reopened, synchronize]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
description:
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check the description against the template
|
||||
run: |
|
||||
set -u
|
||||
status=0
|
||||
python3 scripts/pr_template_check.py --event "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/result.txt" || status=$?
|
||||
cat "$RUNNER_TEMP/result.txt"
|
||||
{ echo '## PR template'; cat "$RUNNER_TEMP/result.txt"; } >> "$GITHUB_STEP_SUMMARY"
|
||||
if [ "$status" -ne 0 ]; then
|
||||
echo "::error title=PR description does not follow the template::$(tail -n +2 "$RUNNER_TEMP/result.txt" | head -n -1 | tr '\n' ' ')"
|
||||
fi
|
||||
exit "$status"
|
||||
@@ -11,7 +11,6 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added `scripts/audit/test_inventory.py`, which lists the Cargo test inventory of two commits in temporary detached worktrees and reports removed, added, newly ignored and newly un-ignored tests, failing on any loss not explained in an `--allow` file. Run against the old PR #166 head 5450612 and main 951189c, it reports the 12 BC texture tests that head was missing (exit 1); the same commit against itself reports no change. Default features only; see `docs/testing/test-inventory.md`.
|
||||
- Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,465 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it.
|
||||
- Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: 25 forms have semantic decoding.
|
||||
- Added `xenora shaders coverage [--json]` and `xenora shaders inspect <file>` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. Each instruction is decoded at its stream offset and branch targets are checked against the whole stream's boundaries, so supported branches are no longer misreported as unsupported operands. `xenora_decoder::decode_at` decodes a single instruction for such callers.
|
||||
|
||||
@@ -44,6 +44,7 @@ Before incorporating third-party code, verify per-file license compatibility wit
|
||||
## Pull requests
|
||||
|
||||
- Branch from the current main branch, keep commits focused, and link relevant issues.
|
||||
- Fill in every section of the pull request template, keep `Closes #<number>` (or write `No linked issue: <reason>`), and tick the claimed-first and DCO checkboxes. The *PR template* check fails until the description does, and runs again each time you edit it.
|
||||
- Include a clear explanation, tests and any documentation/status updates. Separate unverified work from supported behavior.
|
||||
- Disclose material AI assistance and personally review generated changes. AI output is not an authoritative source, test oracle or substitute for independent review.
|
||||
- Never include secrets, personal paths, credentials or private data in patches or logs.
|
||||
|
||||
@@ -327,6 +327,10 @@ Compiling a shader is not equivalent to proving its GPU output is correct.
|
||||
|
||||
---
|
||||
|
||||
### Contributors
|
||||
|
||||
[](https://github.com/ranveersoni98/Xenora/graphs/contributors)
|
||||
|
||||
## License
|
||||
|
||||
Xenora is licensed under the [GNU General Public License v3 or later](LICENSE).
|
||||
|
||||
@@ -32,7 +32,6 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
## Testing, validation, and benchmarks
|
||||
|
||||
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
|
||||
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
|
||||
|
||||
- [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings.
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
# Compare test inventories across commits
|
||||
|
||||
Run this check from a Xenora checkout with Python 3.11 or later and the
|
||||
native ARM64 Rust toolchain. Choose the base commit whose tests the candidate
|
||||
should preserve. Comparing against `main` can catch tests missing from a
|
||||
branch that predates their merge.
|
||||
|
||||
```sh
|
||||
python3 scripts/audit/test_inventory.py main HEAD
|
||||
python3 scripts/audit/test_inventory.py main HEAD --allow intended-losses.tsv
|
||||
python3 scripts/audit/test_inventory.py --self-test
|
||||
```
|
||||
|
||||
The script resolves both refs to commits, then uses a temporary detached Git
|
||||
worktree for each commit. It builds the workspace with the lockfile and
|
||||
default features in offline mode, using Cargo's cached dependencies. It lists
|
||||
tests and then lists ignored tests using the same build. It removes each
|
||||
temporary worktree after listing, including when a build fails. Git needs
|
||||
permission to update its worktree registry.
|
||||
|
||||
Each test is identified by `package/kind:target/test_name`. The report shows
|
||||
removed, added, newly ignored and newly un-ignored tests. Renames appear as a
|
||||
removal and an addition. Exit code 1 means at least one unexplained removal or
|
||||
newly ignored test. Exit code 0 means every loss was explained or there were
|
||||
no losses. Exit code 2 means the check could not complete, for example because
|
||||
a ref did not resolve or Cargo could not build it.
|
||||
|
||||
To explain an intended removal or a newly ignored test, copy its exact key
|
||||
from the report into a UTF-8 file, followed by a literal tab and a reason.
|
||||
Use one entry per line. Blank lines and lines starting with `#` are allowed.
|
||||
|
||||
```text
|
||||
xenora-texture/test:bc_formats/old_case Replaced by new_case, which covers both endpoint orders.
|
||||
```
|
||||
|
||||
The report still shows explained losses. Keep the reasons specific enough for
|
||||
a reviewer to verify.
|
||||
|
||||
The inventory covers Cargo's default workspace test targets for the host and
|
||||
build configuration. Feature-gated targets such as those requiring
|
||||
`gpu-tests` are outside that inventory. The check lists tests without
|
||||
running their bodies or verifying CPU or GPU behavior. Benchmarks are
|
||||
excluded. Rustdoc includes source positions in doctest names, so moving a
|
||||
doctest can appear as a removal and an addition.
|
||||
@@ -1,247 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare Cargo test inventories at two Git commits."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
RUNNING = re.compile(r"Running (?:unittests )?.+ \((.+)\)")
|
||||
DOCTEST = re.compile(r"Doc-tests (\S+)")
|
||||
TEST = re.compile(r"(.+): test")
|
||||
|
||||
|
||||
def parse_list(output, metadata, checkout):
|
||||
"""Return (package, kind:target, test name) keys from a merged Cargo log."""
|
||||
packages = {p["id"]: p["name"] for p in metadata["packages"]}
|
||||
doctests = {}
|
||||
for package in metadata["packages"]:
|
||||
for target in package["targets"]:
|
||||
if target["doctest"]:
|
||||
name = target["name"].replace("-", "_")
|
||||
doctests.setdefault(name, set()).add(
|
||||
(package["name"], f'doc:{target["name"]}')
|
||||
)
|
||||
|
||||
executables = {}
|
||||
suites = set()
|
||||
tests = set()
|
||||
suite = None
|
||||
for line in output.splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith('{"reason":'):
|
||||
message = json.loads(line)
|
||||
if message["reason"] == "compiler-artifact":
|
||||
executable = message["executable"]
|
||||
package = packages.get(message["package_id"])
|
||||
if executable and package:
|
||||
target = message["target"]
|
||||
kind = target["kind"][0]
|
||||
executables[Path(executable)] = (package, f'{kind}:{target["name"]}')
|
||||
elif match := RUNNING.fullmatch(line):
|
||||
executable = checkout / match[1]
|
||||
suite = executables.get(executable)
|
||||
if suite is None:
|
||||
raise ValueError(f"no Cargo artifact for {line}")
|
||||
suites.add(suite)
|
||||
elif match := DOCTEST.fullmatch(line):
|
||||
matches = doctests.get(match[1], set())
|
||||
if len(matches) != 1:
|
||||
raise ValueError(f"cannot identify package for {line}")
|
||||
suite = next(iter(matches))
|
||||
suites.add(suite)
|
||||
elif match := TEST.fullmatch(line):
|
||||
if suite is None:
|
||||
raise ValueError(f"test listed before its target: {line}")
|
||||
tests.add((*suite, match[1]))
|
||||
|
||||
if not suites:
|
||||
raise ValueError("Cargo listed no test targets")
|
||||
return suites, tests
|
||||
|
||||
|
||||
def run(args, cwd, *, merge=False):
|
||||
result = subprocess.run(
|
||||
args, cwd=cwd, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT if merge else subprocess.PIPE,
|
||||
text=True, encoding="utf-8",
|
||||
env={**os.environ, "CARGO_TERM_COLOR": "never", "GIT_NO_LAZY_FETCH": "1"},
|
||||
)
|
||||
if result.returncode:
|
||||
detail = "\n".join((result.stderr or result.stdout).strip().splitlines()[-25:])
|
||||
raise RuntimeError(f"{' '.join(map(str, args))} exited {result.returncode}\n{detail}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def inventory(all_output, ignored_output, metadata, checkout):
|
||||
suites, tests = parse_list(all_output, metadata, checkout)
|
||||
ignored_suites, ignored = parse_list(ignored_output, metadata, checkout)
|
||||
if suites != ignored_suites or not ignored <= tests:
|
||||
raise ValueError("Cargo's full and ignored listings disagree")
|
||||
return tests, ignored
|
||||
|
||||
|
||||
def collect(repo, commit, checkout):
|
||||
run(["git", "worktree", "add", "--detach", str(checkout), commit], repo)
|
||||
try:
|
||||
metadata = json.loads(run([
|
||||
"cargo", "metadata", "--offline", "--locked", "--no-deps", "--format-version", "1",
|
||||
], checkout))
|
||||
cargo = [
|
||||
"cargo", "test", "--offline", "--locked", "--workspace",
|
||||
"--target-dir", str(checkout / "target"),
|
||||
"--jobs", "2", "--message-format=json", "--", "--list", "--format", "terse",
|
||||
]
|
||||
return inventory(
|
||||
run(cargo, checkout, merge=True),
|
||||
run([*cargo, "--ignored"], checkout, merge=True),
|
||||
metadata,
|
||||
checkout,
|
||||
)
|
||||
finally:
|
||||
run(["git", "worktree", "remove", "--force", str(checkout)], repo)
|
||||
|
||||
|
||||
def read_allow(path):
|
||||
"""Read tab-separated inventory keys and reasons."""
|
||||
allowed = {}
|
||||
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
key, _, reason = line.partition("\t")
|
||||
parts = key.split("/", 2)
|
||||
if len(parts) != 3 or not all(parts) or not reason.strip() or key in allowed:
|
||||
raise ValueError(f"{path}:{number}: expected a unique test key and a tab-separated reason")
|
||||
allowed[key] = reason.strip()
|
||||
return allowed
|
||||
|
||||
|
||||
def report(base, candidate, allowed):
|
||||
before, before_ignored = base
|
||||
after, after_ignored = candidate
|
||||
common = before & after
|
||||
changes = (
|
||||
("Removed", before - after, True),
|
||||
("Added", after - before, False),
|
||||
("Newly ignored", (after_ignored - before_ignored) & common, True),
|
||||
("Newly un-ignored", (before_ignored - after_ignored) & common, False),
|
||||
)
|
||||
blocked = 0
|
||||
for label, tests, is_loss in changes:
|
||||
print(f"{label}: {len(tests)}")
|
||||
for test in sorted(tests):
|
||||
key = "/".join(test)
|
||||
reason = allowed.get(key) if is_loss else None
|
||||
print(f" {key}" + (f" (allowed: {reason})" if reason else ""))
|
||||
blocked += is_loss and reason is None
|
||||
print(f"Unapproved losses: {blocked}")
|
||||
return int(blocked != 0)
|
||||
|
||||
|
||||
def main(argv):
|
||||
if argv == ["--self-test"]:
|
||||
program = unittest.main(argv=[sys.argv[0]], exit=False)
|
||||
return int(not program.result.wasSuccessful())
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("base", help="base commit (normally main)")
|
||||
parser.add_argument("candidate", help="candidate commit")
|
||||
parser.add_argument("--allow", type=Path, metavar="FILE", help="explained test losses")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
allowed = read_allow(args.allow) if args.allow else {}
|
||||
repo = Path(run(["git", "rev-parse", "--show-toplevel"], Path.cwd()).strip())
|
||||
commits = [
|
||||
run(["git", "rev-parse", "--verify", "--end-of-options", f"{ref}^{{commit}}"], repo).strip()
|
||||
for ref in (args.base, args.candidate)
|
||||
]
|
||||
print(f"Default Cargo features. Base {commits[0]}, candidate {commits[1]}", flush=True)
|
||||
with tempfile.TemporaryDirectory(prefix="xenora-test-inventory-") as tmp:
|
||||
root = Path(tmp).resolve()
|
||||
base = collect(repo, commits[0], root / "base")
|
||||
candidate = collect(repo, commits[1], root / "candidate")
|
||||
print(f"Base tests: {len(base[0])}; candidate tests: {len(candidate[0])}")
|
||||
return report(base, candidate, allowed)
|
||||
except (OSError, RuntimeError, ValueError) as error:
|
||||
print(f"test inventory: {error}", file=sys.stderr)
|
||||
return 2
|
||||
except KeyboardInterrupt:
|
||||
print("test inventory: interrupted", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
class ParseListTests(unittest.TestCase):
|
||||
checkout = Path("/checkout")
|
||||
metadata = {"packages": [
|
||||
{"id": package, "name": package, "targets": [{"name": package, "doctest": True}]}
|
||||
for package in ("one", "two")
|
||||
]}
|
||||
|
||||
def listing(self, package, cases):
|
||||
executable = f"/checkout/target/{package}/shared-testhash"
|
||||
message = {
|
||||
"reason": "compiler-artifact", "package_id": package,
|
||||
"executable": executable, "target": {"name": "shared", "kind": ["test"]},
|
||||
}
|
||||
return f"{json.dumps(message)}\n Running tests/shared.rs ({executable})\n{cases}\n"
|
||||
|
||||
def test_packages_with_same_target_and_test_names(self):
|
||||
output = self.listing("one", "module::case: test\nspeed: benchmark")
|
||||
output += self.listing("two", "module::case: test")
|
||||
output += " Doc-tests two\nsrc/lib.rs - run (line 12): test\n"
|
||||
suites, tests = parse_list(output, self.metadata, self.checkout)
|
||||
self.assertEqual(suites, {("one", "test:shared"), ("two", "test:shared"), ("two", "doc:two")})
|
||||
self.assertEqual(tests, {
|
||||
("one", "test:shared", "module::case"), ("two", "test:shared", "module::case"),
|
||||
("two", "doc:two", "src/lib.rs - run (line 12)"),
|
||||
})
|
||||
|
||||
def test_empty_ignored_target_and_relative_executable(self):
|
||||
all_output = self.listing("one", "module::case: test")
|
||||
all_output = all_output.replace("(/checkout/target/", "(target/")
|
||||
ignored_output = self.listing("one", "")
|
||||
self.assertEqual(inventory(all_output, ignored_output, self.metadata, self.checkout),
|
||||
({("one", "test:shared", "module::case")}, set()))
|
||||
|
||||
def test_rejects_unresolved_target(self):
|
||||
with self.assertRaisesRegex(ValueError, "no Cargo artifact"):
|
||||
parse_list("Running tests/shared.rs (target/shared)", self.metadata, self.checkout)
|
||||
|
||||
def test_rejects_ignored_test_missing_from_full_list(self):
|
||||
with self.assertRaisesRegex(ValueError, "listings disagree"):
|
||||
inventory(self.listing("one", ""), self.listing("one", "case: test"),
|
||||
self.metadata, self.checkout)
|
||||
|
||||
|
||||
class ReportTests(unittest.TestCase):
|
||||
base = ({("p", "test:t", "kept"), ("p", "test:t", "gone"), ("p", "test:t", "quiet")}, set())
|
||||
candidate = ({("p", "test:t", "kept"), ("p", "test:t", "quiet"), ("p", "test:t", "new")},
|
||||
{("p", "test:t", "quiet")})
|
||||
|
||||
def test_losses_fail_unless_explained(self):
|
||||
import contextlib, io
|
||||
with contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
self.assertEqual(report(self.base, self.candidate, {}), 1)
|
||||
self.assertIn("Unapproved losses: 2", out.getvalue())
|
||||
allowed = {"p/test:t/gone": "replaced by new", "p/test:t/quiet": "needs hardware"}
|
||||
with contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
self.assertEqual(report(self.base, self.candidate, allowed), 0)
|
||||
self.assertIn("p/test:t/gone (allowed: replaced by new)", out.getvalue())
|
||||
|
||||
def test_allow_file_needs_a_key_and_a_reason(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "allow.tsv"
|
||||
path.write_text("# comment\n\np/test:t/gone\treplaced\n", encoding="utf-8")
|
||||
self.assertEqual(read_allow(path), {"p/test:t/gone": "replaced"})
|
||||
path.write_text("p/test:t/gone\n", encoding="utf-8")
|
||||
with self.assertRaises(ValueError):
|
||||
read_allow(path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,105 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Check that a pull request description follows .github/PULL_REQUEST_TEMPLATE.md.
|
||||
|
||||
Standard library only. The description is read as data from the GitHub event
|
||||
file (or a plain text file with --body-file); it is never executed.
|
||||
Exit status 0 when the description passes, 1 when something is missing.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
|
||||
SECTIONS = (
|
||||
"Summary",
|
||||
"Implementation and evidence",
|
||||
"Verification",
|
||||
"Compatibility and limitations",
|
||||
"Checklist",
|
||||
"AI assistance",
|
||||
)
|
||||
# Checklist items that must be ticked, found by the start of their text.
|
||||
REQUIRED_TICKS = (
|
||||
("I claimed the linked issue", "the claimed-first checkbox"),
|
||||
("My commits are signed off under the DCO", "the DCO sign-off checkbox"),
|
||||
)
|
||||
ISSUE_LINK = re.compile(r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#\d+", re.I)
|
||||
NO_ISSUE = re.compile(r"^\s*No linked issue:\s*\S", re.I | re.M)
|
||||
COMMENT = re.compile(r"<!--.*?-->", re.S)
|
||||
EMPTY_LINK = re.compile(r"^\s*(?:close|fix|resolve)\w*\s*#\s*$", re.I)
|
||||
HEADING = re.compile(r"^##\s+(.+?)\s*$", re.M)
|
||||
|
||||
|
||||
def sections(body):
|
||||
"""Map each level-2 heading to its text, with HTML comments removed."""
|
||||
text = COMMENT.sub("", body.replace("\r\n", "\n"))
|
||||
found = {}
|
||||
marks = list(HEADING.finditer(text))
|
||||
for i, m in enumerate(marks):
|
||||
end = marks[i + 1].start() if i + 1 < len(marks) else len(text)
|
||||
found[m.group(1).strip().lower()] = text[m.end():end].strip()
|
||||
return text, found
|
||||
|
||||
|
||||
def has_content(name, value):
|
||||
if name == "Verification":
|
||||
# The empty table from the template does not count: some cell must be filled.
|
||||
rows = [r for r in value.splitlines() if r.strip().startswith("|")]
|
||||
filled = [r for r in rows[2:] if [c for c in r.strip().strip("|").split("|")[1:] if c.strip()]]
|
||||
prose = [r for r in value.splitlines() if r.strip() and not r.strip().startswith("|")]
|
||||
return bool(filled or prose)
|
||||
if name == "Checklist":
|
||||
return "- [" in value
|
||||
# A bare "Closes #" left over from the template is not content.
|
||||
rest = [l for l in value.splitlines() if l.strip() and not EMPTY_LINK.match(l)]
|
||||
return bool(rest)
|
||||
|
||||
|
||||
def check(body):
|
||||
"""Return a list of human-readable problems; empty means the body passes."""
|
||||
if not body or not body.strip():
|
||||
return ["The description is empty. Copy .github/PULL_REQUEST_TEMPLATE.md into it and fill it in."]
|
||||
text, found = sections(body)
|
||||
problems = []
|
||||
for name in SECTIONS:
|
||||
if name.lower() not in found:
|
||||
problems.append('Missing section "## %s".' % name)
|
||||
elif not has_content(name, found[name.lower()]):
|
||||
problems.append('Section "## %s" is empty.' % name)
|
||||
if not ISSUE_LINK.search(text) and not NO_ISSUE.search(text):
|
||||
problems.append('No linked issue: add "Closes #<number>", or a line "No linked issue: <reason>".')
|
||||
checklist = found.get("checklist", "")
|
||||
for prefix, label in REQUIRED_TICKS:
|
||||
item = re.search(r"^\s*[-*]\s*\[( |x|X)\]\s*" + re.escape(prefix), checklist, re.M)
|
||||
if not item:
|
||||
problems.append("Checklist is missing %s." % label)
|
||||
elif item.group(1) == " ":
|
||||
problems.append("Tick %s." % label)
|
||||
return problems
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
src = ap.add_mutually_exclusive_group(required=True)
|
||||
src.add_argument("--event", help="GitHub event JSON file (pull_request or pull_request_target)")
|
||||
src.add_argument("--body-file", help="file holding the description text")
|
||||
args = ap.parse_args(argv)
|
||||
if args.event:
|
||||
with open(args.event, encoding="utf-8") as fh:
|
||||
body = (json.load(fh).get("pull_request") or {}).get("body") or ""
|
||||
else:
|
||||
with open(args.body_file, encoding="utf-8") as fh:
|
||||
body = fh.read()
|
||||
problems = check(body)
|
||||
if problems:
|
||||
print("The pull request description does not follow .github/PULL_REQUEST_TEMPLATE.md:")
|
||||
for p in problems:
|
||||
print("- " + p)
|
||||
print("Edit the description to fix this; the check runs again on every edit.")
|
||||
return 1
|
||||
print("The pull request description follows the template.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,99 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import pr_template_check as c
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
TEMPLATE = open(os.path.join(ROOT, ".github", "PULL_REQUEST_TEMPLATE.md"), encoding="utf-8").read()
|
||||
|
||||
GOOD = """## Summary
|
||||
|
||||
Adds X.
|
||||
|
||||
Closes #12
|
||||
|
||||
## Implementation and evidence
|
||||
|
||||
Touches crates/texture only.
|
||||
|
||||
## Verification
|
||||
|
||||
| Check | Result / evidence |
|
||||
| --- | --- |
|
||||
| Formatting and lint | cargo fmt --check: clean |
|
||||
| Unit / integration tests | cargo test -p xenora-texture: 40 passed |
|
||||
|
||||
## Compatibility and limitations
|
||||
|
||||
None known.
|
||||
|
||||
## Checklist
|
||||
|
||||
- [x] I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.
|
||||
- [x] I reviewed the changes and disclosed material AI assistance below, if applicable.
|
||||
- [x] My commits are signed off under the DCO.
|
||||
|
||||
## AI assistance
|
||||
|
||||
None.
|
||||
"""
|
||||
|
||||
|
||||
class Check(unittest.TestCase):
|
||||
def test_good_body_passes(self):
|
||||
self.assertEqual(c.check(GOOD), [])
|
||||
|
||||
def test_unfilled_template_fails_on_every_rule(self):
|
||||
problems = c.check(TEMPLATE)
|
||||
text = "\n".join(problems)
|
||||
for want in ('"## Summary" is empty', '"## Implementation and evidence" is empty',
|
||||
'"## Verification" is empty', '"## Compatibility and limitations" is empty',
|
||||
'"## AI assistance" is empty', "No linked issue", "claimed-first", "DCO"):
|
||||
self.assertIn(want, text)
|
||||
|
||||
def test_empty_and_freeform_bodies_fail(self):
|
||||
self.assertTrue(c.check(""))
|
||||
self.assertTrue(c.check("Fixes a bug. Closes #3"))
|
||||
|
||||
def test_missing_section_is_named(self):
|
||||
body = GOOD.replace("## Compatibility and limitations\n\nNone known.\n", "")
|
||||
self.assertEqual(c.check(body), ['Missing section "## Compatibility and limitations".'])
|
||||
|
||||
def test_unticked_boxes_fail(self):
|
||||
body = GOOD.replace("- [x] I claimed", "- [ ] I claimed").replace("- [x] My commits", "- [ ] My commits")
|
||||
problems = c.check(body)
|
||||
self.assertEqual(len(problems), 2)
|
||||
self.assertIn("claimed-first", problems[0])
|
||||
self.assertIn("DCO", problems[1])
|
||||
|
||||
def test_issue_link_forms(self):
|
||||
for link in ("Fixes #4", "resolves #4", "Closed #4", "No linked issue: requested by the maintainer"):
|
||||
self.assertEqual(c.check(GOOD.replace("Closes #12", link)), [], link)
|
||||
self.assertIn("No linked issue", "\n".join(c.check(GOOD.replace("Closes #12", "See issue 12"))))
|
||||
|
||||
def test_link_inside_comment_does_not_count(self):
|
||||
self.assertTrue(c.check(GOOD.replace("Closes #12", "<!-- Closes #12 -->")))
|
||||
|
||||
def test_new_claim_checkbox_wording_passes(self):
|
||||
body = GOOD.replace("I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.",
|
||||
"I claimed the linked issue with a reply before starting, and nobody else held a live claim on it.")
|
||||
self.assertEqual(c.check(body), [])
|
||||
|
||||
def test_cli_exit_codes_from_event_file(self):
|
||||
script = os.path.join(ROOT, "scripts", "pr_template_check.py")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
for body, want in ((GOOD, 0), (TEMPLATE, 1), (None, 1)):
|
||||
path = os.path.join(d, "event.json")
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
json.dump({"pull_request": {"body": body}}, fh)
|
||||
run = subprocess.run([sys.executable, script, "--event", path], capture_output=True, text=True)
|
||||
self.assertEqual(run.returncode, want, run.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user