mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
ci: port block workflows to the shared repository
This commit is contained in:
1 parent
a5686e7fa7
commit
4762c84e43
21 files changed
+1705
No files matched your search
@@ -0,0 +1,122 @@
|
||||
"""Local-only checks for the nested-module CI port; no Go suites or publishing."""
|
||||
from pathlib import Path
|
||||
import copy
|
||||
import importlib.util
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parents[2]
|
||||
|
||||
|
||||
class PortTests(unittest.TestCase):
|
||||
def test_root_workflows_use_module_run_and_action_paths(self):
|
||||
for name in ("test", "spec-trace", "post-merge-review", "known-bugs"):
|
||||
text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text()
|
||||
self.assertIn("working-directory: seaweed-block", text)
|
||||
self.assertIn("vars.BLOCK_RUNNER_LABEL", text)
|
||||
self.assertIn("|| 'ubuntu-latest'", text)
|
||||
if "go-version-file:" in text: self.assertIn("go-version-file: seaweed-block/go.mod", text)
|
||||
if name != "known-bugs":
|
||||
self.assertIn('"seaweed-block/**"', text)
|
||||
self.assertIn('".github/workflows/block-*.yml"', text)
|
||||
test = (ROOT / ".github/workflows/block-test.yml").read_text()
|
||||
self.assertIn("- master", test)
|
||||
self.assertIn("git diff --relative --name-only HEAD^1 HEAD -- .", test)
|
||||
self.assertIn("go test (linux)", test)
|
||||
self.assertIn("process-level tests (real binaries)", test)
|
||||
post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text()
|
||||
self.assertIn("working-directory: ${{ github.workspace }}", post)
|
||||
|
||||
def test_release_tag_namespace_and_artifact_identity(self):
|
||||
text = (ROOT / ".github/workflows/block-release.yml").read_text()
|
||||
self.assertIn('"seaweed-block/v*"', text)
|
||||
self.assertNotIn('tags:\n - "v*"', text)
|
||||
self.assertIn("git tag -l 'seaweed-block/v*'", text)
|
||||
self.assertIn('docker pull "${BLOCK_IMAGE}@${BLOCK_DIGEST}"', text)
|
||||
self.assertIn('gh release create "$GITHUB_REF_NAME"', text)
|
||||
self.assertIn('--latest=false', text)
|
||||
self.assertIn('vars.BLOCK_RUNNER_LABEL', text)
|
||||
self.assertIn("|| 'ubuntu-latest'", text)
|
||||
self.assertIn('github.event.pull_request.head.repo.full_name == github.repository', text)
|
||||
self.assertIn('sw-block-${version}-linux-amd64.tar.gz', text)
|
||||
self.assertNotIn("go build", text)
|
||||
for name in ("sw-block", "blockcsi"):
|
||||
recipe = (ROOT / (".github/dockerfiles/block-" + name + ".Dockerfile")).read_text()
|
||||
self.assertIn("WORKDIR /src/seaweed-block", recipe)
|
||||
self.assertIn("COPY . /src", recipe)
|
||||
self.assertGreater(recipe.index("RUN bash scripts/refuse-lab-binary.sh"), recipe.rindex("go build"))
|
||||
|
||||
def test_nested_git_paths_and_blobs_stay_module_relative(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp); module = root / "seaweed-block"; module.mkdir()
|
||||
def git(*args):
|
||||
return subprocess.check_output(["git", *args], cwd=root, timeout=15)
|
||||
git("init", "-b", "master")
|
||||
git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid")
|
||||
git("config", "commit.gpgsign", "false")
|
||||
(module / "core").mkdir(); (module / "docs").mkdir()
|
||||
code = module / "core/a.go"; code.write_text("package a\nconst N=1\n")
|
||||
(root / "host.go").write_text("package host\n")
|
||||
git("add", "."); git("commit", "-m", "base")
|
||||
base = git("rev-parse", "HEAD").decode().strip()
|
||||
(module / "docs/a.md").write_text("documentation\n")
|
||||
git("add", "."); git("commit", "-m", "docs")
|
||||
docs = git("rev-parse", "HEAD").decode().strip()
|
||||
def run(name, *args):
|
||||
return subprocess.check_output(["bash", str(HERE / name), *args], cwd=module, timeout=20)
|
||||
self.assertEqual(run("docs-only-scope.sh", base, docs), b"docs_only 1\n")
|
||||
code.write_text("package a\nconst N=2\n")
|
||||
(root / "host.go").write_text("package host\nconst Changed=true\n")
|
||||
git("add", "."); git("commit", "-m", "code")
|
||||
head = git("rev-parse", "HEAD").decode().strip()
|
||||
self.assertEqual(run("post-merge-review-changed.sh", docs, head), b"M\0core/a.go\0")
|
||||
self.assertTrue(run("chunkstore-scope.sh", docs, head).startswith(b"skip 1"))
|
||||
blobs = root / "blobs"
|
||||
run("changed-go-blobs.sh", docs, head, str(blobs))
|
||||
self.assertEqual((blobs / "old/core/a.go").read_text(), "package a\nconst N=1\n")
|
||||
self.assertEqual((blobs / "new/core/a.go").read_text(), "package a\nconst N=2\n")
|
||||
self.assertFalse((blobs / "new/host.go").exists())
|
||||
control = root / ".github/workflows/block-test.yml"
|
||||
control.parent.mkdir(parents=True)
|
||||
control.write_text("name: Block Test\n")
|
||||
git("add", ".github"); git("commit", "-m", "CI control")
|
||||
control_head = git("rev-parse", "HEAD").decode().strip()
|
||||
self.assertIn(b".github/workflows/block-test.yml\0", run("post-merge-review-changed.sh", docs, control_head))
|
||||
self.assertTrue(run("docs-only-scope.sh", base, control_head).startswith(b"run "))
|
||||
|
||||
|
||||
def test_safe_merge_refuses_wrong_head_base_and_incomplete_jobs(self):
|
||||
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
|
||||
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
|
||||
pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}}
|
||||
run = {"name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]}
|
||||
jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS]
|
||||
check.validate(pr, run, jobs, "base")
|
||||
for key, value in (("head_sha", "other"), ("conclusion", "cancelled"), ("name", "Other Test")):
|
||||
wrong = copy.deepcopy(run); wrong[key] = value
|
||||
with self.assertRaises(ValueError): check.validate(pr, wrong, jobs, "base")
|
||||
with self.assertRaises(ValueError): check.validate(pr, run, jobs, "moved")
|
||||
with self.assertRaises(ValueError): check.validate(pr, run, jobs[:1], "base")
|
||||
failed = copy.deepcopy(jobs); failed[0]["conclusion"] = "failure"
|
||||
with self.assertRaises(ValueError): check.validate(pr, run, failed, "base")
|
||||
|
||||
def test_batch_preserves_pinned_base_heads_order_and_evidence(self):
|
||||
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
|
||||
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
evidence = Path(tmp) / "acceptance"; evidence.write_text("review accepted")
|
||||
prs = [{"number": n, "state": "open", "draft": False, "base": {"ref": "master"}, "head": {"sha": str(n)}} for n in (1, 2)]
|
||||
manifest = {"base": "base", "head": "batch", "prs": [{"number": p["number"], "head": p["head"]["sha"], "evidence": str(evidence)} for p in prs]}
|
||||
check.validate_batch(manifest, prs, "base")
|
||||
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "moved")
|
||||
with self.assertRaises(ValueError): check.validate_batch(manifest, list(reversed(prs)), "base")
|
||||
wrong = copy.deepcopy(prs); wrong[0]["head"]["sha"] = "new"
|
||||
with self.assertRaises(ValueError): check.validate_batch(manifest, wrong, "base")
|
||||
evidence.write_text("")
|
||||
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "base")
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
# Writes the old and new blob of each changed non-test Go file between two
|
||||
# commits under <out>/old/<path> and <out>/new/<path>, for the spec trace's
|
||||
# kind DOCS (objects only; nothing from the PR is built or run).
|
||||
#
|
||||
# usage: changed-go-blobs.sh <merge-base> <head> <out>
|
||||
#
|
||||
# The paths come from the PR's tree objects, which git does not check when it
|
||||
# prints a diff. A path that is absolute or has an empty, '.' or '..'
|
||||
# component would write outside <out>, so it is refused before anything is
|
||||
# written (exit 1).
|
||||
set -euo pipefail
|
||||
mb=$1 head=$2 out=$3
|
||||
prefix=$(git rev-parse --show-prefix)
|
||||
mkdir -p "$out"
|
||||
git diff --relative --name-only --no-renames -z "$mb" "$head" -- "*.go" ":(exclude)*_test.go" >"$out/.paths"
|
||||
while IFS= read -r -d "" p; do
|
||||
case "/$p/" in
|
||||
*//* | */./* | */../*)
|
||||
printf 'changed-go-blobs: refusing path %q\n' "$p" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done <"$out/.paths"
|
||||
while IFS= read -r -d "" p; do
|
||||
mkdir -p "$out/old/$(dirname "$p")" "$out/new/$(dirname "$p")"
|
||||
git show "$mb:$prefix$p" >"$out/old/$p" 2>/dev/null || rm -f "$out/old/$p"
|
||||
git show "$head:$prefix$p" >"$out/new/$p" 2>/dev/null || rm -f "$out/new/$p"
|
||||
done <"$out/.paths"
|
||||
rm -f "$out/.paths"
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run only from a trusted base checkout; HEAD code is inspected as Git objects.
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
base=${1:?BASE}; head=${2:?HEAD}; body=${3:?BODY}; title=${4:?TITLE}
|
||||
[ "$(git rev-parse HEAD)" = "$(git rev-parse "$base")" ] || { echo "refusing: checkout is not the trusted base" >&2; exit 2; }
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
mb=$(git merge-base "$base" "$head")
|
||||
bash "$here/post-merge-review-changed.sh" "$mb" "$head" >"$work/changed.bin"
|
||||
bash "$here/changed-go-blobs.sh" "$mb" "$head" "$work/blobs"
|
||||
bash .github/scripts/spec-trace-check.sh "$body" "$work/blobs" .github/model-code-trace.tsv <"$work/changed.bin"
|
||||
bash "$here/public-text-check.sh" "$mb" "$head" "$title" "$body"
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env bash
|
||||
# chunkstore-scope.sh BASE HEAD: decides whether a pull request runs the
|
||||
# real-filer integration tests. It prints one line:
|
||||
# "run N FIRST" at least one of the N changed files is under
|
||||
# core/frontend/chunkstore/, core/storage/ or
|
||||
# core/frontend/durable/ (FIRST is one)
|
||||
# "skip N" none of the N changed files is
|
||||
# and exits 0. Any error (git fails, the list cannot be read) exits nonzero,
|
||||
# and the caller then runs the tests: an error never selects skip.
|
||||
#
|
||||
# The NUL-delimited list is written to a file first and read to its end, so
|
||||
# no pipe can stop early and leave a writer's error looking like an answer.
|
||||
set -euo pipefail
|
||||
[ "$#" -eq 2 ] || { echo "usage: chunkstore-scope.sh BASE HEAD" >&2; exit 2; }
|
||||
list=$(mktemp)
|
||||
trap 'rm -f "$list"' EXIT
|
||||
if ! git diff --relative --name-only --no-renames -z "$1" "$2" -- . >"$list"; then
|
||||
echo "chunkstore-scope: git diff $1 $2 failed" >&2
|
||||
exit 2
|
||||
fi
|
||||
n=0
|
||||
hit=""
|
||||
while IFS= read -r -d '' f; do
|
||||
n=$((n + 1))
|
||||
case $f in
|
||||
core/frontend/chunkstore/* | core/storage/* | core/frontend/durable/*) [ -n "$hit" ] || hit=$f ;;
|
||||
esac
|
||||
done <"$list"
|
||||
if [ -n "$hit" ]; then
|
||||
echo "run $n $hit"
|
||||
else
|
||||
echo "skip $n"
|
||||
fi
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
# docs-only-scope.sh BASE HEAD: classifies the files changed between BASE and
|
||||
# HEAD for the process-level suite. It prints one line:
|
||||
# "docs_only N" every one of the N changed files is under docs/
|
||||
# "run N [FIRST-OTHER]" no file changed, or at least one is elsewhere
|
||||
# and exits 0. Any error (git fails, the list cannot be read) exits nonzero,
|
||||
# and the caller then runs the tests: an error never selects docs_only.
|
||||
#
|
||||
# The NUL-delimited list is written to a file first and read to its end, so
|
||||
# no pipe can stop early and leave a writer's error looking like an answer.
|
||||
set -euo pipefail
|
||||
[ "$#" -eq 2 ] || { echo "usage: docs-only-scope.sh BASE HEAD" >&2; exit 2; }
|
||||
list=$(mktemp)
|
||||
trap 'rm -f "$list"' EXIT
|
||||
if ! git diff --relative --name-only --no-renames -z "$1" "$2" -- . >"$list"; then
|
||||
echo "docs-only-scope: git diff $1 $2 failed" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [ -n "$(git rev-parse --show-prefix)" ]; then
|
||||
git -C "$(git rev-parse --show-toplevel)" diff --name-only --no-renames -z "$1" "$2" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**' >>"$list"
|
||||
fi
|
||||
n=0
|
||||
other=""
|
||||
while IFS= read -r -d '' f; do
|
||||
n=$((n + 1))
|
||||
case $f in
|
||||
docs/*) ;;
|
||||
*) [ -n "$other" ] || other=$f ;;
|
||||
esac
|
||||
done <"$list"
|
||||
if [ "$n" -gt 0 ] && [ -z "$other" ]; then
|
||||
echo "docs_only $n"
|
||||
else
|
||||
echo "run $n${other:+ $other}"
|
||||
fi
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Check that every code and test anchor of the invariants ledger exists at a git ref.
|
||||
|
||||
usage: python -I ledger_check.py <repo-dir> <git-ref> [<ledger path in repo>]
|
||||
|
||||
A ledger row is a table line whose first cell holds `INV-...`. In its cells, a
|
||||
backticked token that ends in .go is a FILE; a backticked identifier (or
|
||||
Type.Method) is a SYMBOL of the nearest file named before it in the same cell,
|
||||
or, in the test cell, of any file named in that cell. A file must exist at the
|
||||
ref; a symbol must occur in its file as a whole word (for a test: `func Name(`).
|
||||
A symbol with no file in its cell is looked up in the whole tree. A file may
|
||||
be a glob (`volume_lock*.go`). A lower-case token with an underscore (a build
|
||||
tag, a JSON key, a reason string) is not a Go symbol and is not checked.
|
||||
Prints one line per missing anchor and a summary. It reads; it changes nothing.
|
||||
Exit: 0 when every anchor exists; 1 when one is missing; 2 when git fails or no
|
||||
row or anchor was found (an error is never read as a pass).
|
||||
"""
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def git(repo, *args):
|
||||
"""git's output. A git failure ends the check with exit 2: an error must
|
||||
never read as "no anchors". `git grep` finding nothing (exit 1) is not one."""
|
||||
r = subprocess.run(["git", "-C", repo] + list(args), capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace")
|
||||
if r.returncode != 0 and not (args and args[0] == "grep" and r.returncode == 1):
|
||||
print("ledger_check: git %s failed (exit %d): %s" % (" ".join(args[:2]), r.returncode, r.stderr.strip()[:300]),
|
||||
file=sys.stderr)
|
||||
sys.exit(2)
|
||||
return r.stdout
|
||||
|
||||
|
||||
def main():
|
||||
repo, ref = sys.argv[1], sys.argv[2]
|
||||
ledger = sys.argv[3] if len(sys.argv) > 3 else "docs/design/invariants.md"
|
||||
text = git(repo, "show", "%s:%s" % (ref, ledger))
|
||||
prefix = sys.argv[4] if len(sys.argv) > 4 else ""
|
||||
files = set(git(repo, "ls-tree", "-r", "--name-only", ref, "--", prefix or ".").split("\n"))
|
||||
cache = {}
|
||||
|
||||
def body(path):
|
||||
if path not in cache:
|
||||
cache[path] = git(repo, "show", "%s:%s" % (ref, path))
|
||||
return cache[path]
|
||||
|
||||
def resolve(tok):
|
||||
"""A file token may be a full path or a bare file name."""
|
||||
if tok in files:
|
||||
return [tok]
|
||||
if "*" in tok:
|
||||
rx = re.compile("^(.*/)?" + "[^/]*".join(re.escape(x) for x in tok.split("*")) + "$")
|
||||
return [f for f in files if rx.match(f)]
|
||||
if "/" not in tok:
|
||||
return [f for f in files if f.endswith("/" + tok)]
|
||||
# a path with a directory matches whole path components only
|
||||
return [f for f in files if f.endswith("/" + tok)]
|
||||
|
||||
ident = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?(\(\))?$")
|
||||
go_all = None
|
||||
rows = missing = anchors = 0
|
||||
for n, line in enumerate(text.split("\n"), 1):
|
||||
if not line.startswith("|"):
|
||||
continue
|
||||
cells = [c.strip() for c in line.strip().strip("|").split("|")]
|
||||
m = re.match(r"`(INV-[A-Z0-9-]+)`", cells[0]) if cells else None
|
||||
if not m or len(cells) < 6:
|
||||
continue
|
||||
rows += 1
|
||||
inv, status = m.group(1), cells[-1]
|
||||
if "ARCHIVED" in status:
|
||||
continue
|
||||
for ci, kind in ((3, "code"), (4, "test")):
|
||||
toks = re.findall(r"`([^`]+)`", cells[ci])
|
||||
cell_files = []
|
||||
for t in toks:
|
||||
if t.endswith(".go"):
|
||||
cell_files.append(t)
|
||||
cur = None
|
||||
for t in toks:
|
||||
if t.endswith(".go"):
|
||||
cur = t
|
||||
anchors += 1
|
||||
if not resolve(t):
|
||||
missing += 1
|
||||
print("%s (line %d, %s, %s): file %s does not exist" % (inv, n, kind, status, t))
|
||||
continue
|
||||
if not ident.match(t):
|
||||
continue
|
||||
sym = t.rstrip("()").split(".")[-1]
|
||||
if sym in ("nil", "true", "false") or sym.isupper() or len(sym) < 3:
|
||||
continue
|
||||
if "_" in sym and sym == sym.lower():
|
||||
# a build tag, a JSON key or a reason string: not a Go symbol
|
||||
continue
|
||||
scope = [cur] if (cur and kind == "code") else cell_files
|
||||
paths = [p for f in scope for p in resolve(f)]
|
||||
anchors += 1
|
||||
if kind == "test" and sym.startswith(("Test", "Fuzz", "Benchmark")):
|
||||
pat = re.compile(r"func %s\(" % re.escape(sym))
|
||||
else:
|
||||
pat = re.compile(r"\b%s\b" % re.escape(sym))
|
||||
if paths:
|
||||
ok = any(pat.search(body(p)) for p in paths)
|
||||
else:
|
||||
if go_all is None:
|
||||
go_all = git(repo, "grep", "-h", "-E", r"^(func|type|var|const|\s+[A-Za-z_]+\s)", ref, "--", prefix + "*.go")
|
||||
ok = bool(pat.search(go_all))
|
||||
if not ok:
|
||||
missing += 1
|
||||
where = ", ".join(scope) if scope else "the tree"
|
||||
print("%s (line %d, %s, %s): %s not found in %s" % (inv, n, kind, status, t, where))
|
||||
print("%d rows, %d anchors, %d missing at %s" % (rows, anchors, missing, ref))
|
||||
if rows == 0 or anchors == 0:
|
||||
print("ledger_check: no ledger rows or anchors found: refusing to pass", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
sys.exit(1 if missing else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
# Usage: post-merge-review-changed.sh BASE HEAD
|
||||
#
|
||||
# Writes what a PR changes (BASE...HEAD) as NUL-separated STATUS, PATH pairs,
|
||||
# unquoted, so any byte in a name reaches the check as itself. --no-renames
|
||||
# reports a move as a delete of the old name and an add of the new one.
|
||||
set -euo pipefail
|
||||
base=${1:?usage: post-merge-review-changed.sh BASE HEAD}
|
||||
head=${2:?usage: post-merge-review-changed.sh BASE HEAD}
|
||||
git diff --relative -z --name-status --no-renames "$base...$head" -- .
|
||||
|
||||
if [ -n "$(git rev-parse --show-prefix)" ]; then
|
||||
git -C "$(git rev-parse --show-toplevel)" diff -z --name-status --no-renames "$base...$head" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**'
|
||||
fi
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
# Refuses internal names in what a pull request makes public: the lines it
|
||||
# adds, its commit messages, its title and its description. This repository is
|
||||
# public; internal seat names and internal file-share paths do not belong in it.
|
||||
#
|
||||
# Usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE
|
||||
# Exit 0: clean. Exit 1: at least one hit (each printed). Exit 2: usage.
|
||||
#
|
||||
# The patterns live only here and in this check's own test; both files are
|
||||
# excluded from the scan of added lines.
|
||||
set -euo pipefail
|
||||
[ "$#" -eq 4 ] || { echo "usage: public-text-check.sh MERGE_BASE HEAD TITLE_FILE BODY_FILE" >&2; exit 2; }
|
||||
mb=$1; head=$2; title=$3; body=$4
|
||||
for f in "$title" "$body"; do
|
||||
[ -f "$f" ] && [ -r "$f" ] || { echo "public-text: cannot read $f" >&2; exit 2; }
|
||||
done
|
||||
git rev-parse -q --verify "$mb^{commit}" >/dev/null && git rev-parse -q --verify "$head^{commit}" >/dev/null ||
|
||||
{ echo "public-text: unknown commit $mb or $head" >&2; exit 2; }
|
||||
# match: a grep error fails the check instead of reading as "no hit".
|
||||
match() { local rc=0; grep -E -i -- "$pat" "$@" || rc=$?; [ "$rc" -le 1 ] || { echo "public-text: grep failed ($rc)" >&2; exit 2; }; }
|
||||
pat='(claude|codex)0[0-9]|share[/\]rdma|V:[/\]share|diskstation'
|
||||
out=$(mktemp); trap 'rm -f "$out"' EXIT
|
||||
report() { # report WHERE < matching lines
|
||||
local where=$1 line
|
||||
while IFS= read -r line; do
|
||||
printf 'public-text: %s: %s
|
||||
' "$where" "${line:0:160}" >>"$out"
|
||||
done
|
||||
}
|
||||
# Added lines of the diff, with file and line number.
|
||||
{
|
||||
git diff --relative --no-color --no-renames -U0 "$mb" "$head" -- . \
|
||||
':(exclude).github/scripts/public-text-check.sh' ':(exclude).github/scripts/public-text-check-test.sh'
|
||||
if [ -n "$(git rev-parse --show-prefix)" ]; then
|
||||
git -C "$(git rev-parse --show-toplevel)" diff --no-color --no-renames -U0 "$mb" "$head" -- '.github/workflows/block-*.yml' '.github/dockerfiles/block-*.Dockerfile' '.github/block/**'
|
||||
fi
|
||||
} |
|
||||
awk '
|
||||
/^diff --git / { hdr = 1; next }
|
||||
hdr && /^\+\+\+ / { f = substr($0, 7); next }
|
||||
/^@@ / { hdr = 0; split($3, a, ","); n = substr(a[1], 2) + 0; next }
|
||||
!hdr && /^\+/ { print f ":" n ": " substr($0, 2); n++ }
|
||||
' | match | report "added line"
|
||||
# Commit messages (subjects and bodies) of the pull request.
|
||||
git log --format='%h %s%n%b' "$mb..$head" | match | report "commit message"
|
||||
match "$title" | report "title"
|
||||
match "$body" | report "description"
|
||||
hits=$(wc -l <"$out" | tr -d ' ')
|
||||
if [ "$hits" -gt 0 ]; then
|
||||
cat "$out"
|
||||
echo "public-text: $hits hit(s). Say what the code or test does instead of who asked for it; keep internal paths out." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "public-text: clean"
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Run fake recorders through the real group executor, without product tests."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
import importlib.util
|
||||
import signal
|
||||
|
||||
SCRIPT = Path(__file__).with_name("run-unit-groups.py")
|
||||
FAKE = r'''import json, os, sys, time
|
||||
from pathlib import Path
|
||||
out = Path(sys.argv[1]); group = out.parent.name
|
||||
root = Path(os.environ["FIXTURE_ROOT"])
|
||||
(root / (group + ".started")).write_text("started")
|
||||
deadline = time.monotonic() + 5
|
||||
while not all((root / (g + ".started")).exists() for g in os.environ["EXPECTED_GROUPS"].split()):
|
||||
if time.monotonic() >= deadline: sys.exit(17)
|
||||
time.sleep(.01)
|
||||
flags = sys.argv[2:]
|
||||
assert "-p=" + ("4" if group == "g3" else "1") in flags
|
||||
assert "-short" in flags and "-count=1" in flags and "20m" in flags
|
||||
if sys.platform == "linux":
|
||||
wal = Path(os.environ["TMPDIR"]) / "v1.bin"
|
||||
with wal.open("w") as descriptor:
|
||||
assert os.readlink(f"/proc/self/fd/{descriptor.fileno()}") == str(wal), "fixture WAL descriptor not found"
|
||||
else:
|
||||
assert Path(os.environ["TMPDIR"]) == Path(os.environ["TMPDIR"]).resolve(), "TMPDIR must identify the canonical directory"
|
||||
out.write_text(json.dumps({"Action":"pass", "Package":group}) + "\n")
|
||||
out.with_suffix(".stderr").write_text("fixture stderr")
|
||||
(root / (group + ".finished")).write_text("finished")
|
||||
sys.exit(7 if os.environ.get("FAIL_GROUP") == group else 0)
|
||||
'''
|
||||
|
||||
|
||||
class GroupRunnerTests(unittest.TestCase):
|
||||
def run_groups(self, fail="", empty=False, alias=False):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp); plan = root / "plan"; plan.mkdir()
|
||||
for group in ("g1", "g2", "g3"):
|
||||
(plan / (group + ".txt")).write_text("" if empty and group != "g3" else "example/" + group + "\n")
|
||||
fake = root / "fake.py"; fake.write_text(FAKE)
|
||||
env = dict(os.environ, FIXTURE_ROOT=str(root), EXPECTED_GROUPS="g3" if empty else "g1 g2 g3", FAIL_GROUP=fail)
|
||||
scratch = root / "tmp"
|
||||
if alias:
|
||||
scratch.mkdir()
|
||||
link = root / "runner-temp"
|
||||
link.symlink_to(scratch, target_is_directory=True)
|
||||
scratch = link
|
||||
result = subprocess.run([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(scratch), sys.executable, str(fake)], env=env, text=True, capture_output=True, timeout=20)
|
||||
self.assertEqual(result.returncode, 1 if fail else 0, result.stdout + result.stderr)
|
||||
expected = ["g3"] if empty else ["g1", "g2", "g3"]
|
||||
for group in expected:
|
||||
self.assertTrue((root / (group + ".finished")).exists(), result.stdout + result.stderr)
|
||||
self.assertTrue((root / "evidence" / group / "go-test.stderr").exists())
|
||||
self.assertTrue((root / "tmp" / group).is_dir())
|
||||
events = [json.loads(line) for line in (root / "evidence" / "go-test.json").read_text().splitlines()]
|
||||
self.assertCountEqual([e["Package"] for e in events], expected)
|
||||
statuses = json.loads((root / "evidence" / "unit-groups.json").read_text())
|
||||
self.assertEqual(statuses["groups"]["g2"]["status"], 7 if fail == "g2" else 0)
|
||||
|
||||
@unittest.skipUnless(os.name == "posix", "Linux runner temp symlink control")
|
||||
def test_runner_temp_symlink_passes_canonical_scratch_paths(self): self.run_groups(alias=True)
|
||||
|
||||
def test_all_groups_overlap_and_keep_separate_events(self): self.run_groups()
|
||||
def test_failure_fails_job_after_every_group_finishes(self): self.run_groups(fail="g2")
|
||||
def test_scope_empty_groups_launch_no_recorder(self): self.run_groups(empty=True)
|
||||
|
||||
|
||||
def test_cancel_escalates_even_after_group_leader_exits(self):
|
||||
spec = importlib.util.spec_from_file_location("unit_groups", SCRIPT)
|
||||
module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
|
||||
leader = Mock(pid=12345)
|
||||
leader.wait.return_value = 0
|
||||
with patch.object(module.signal, "SIGKILL", 9, create=True), patch.object(module.os, "name", "posix"), patch.object(module.os, "killpg", create=True) as killpg, patch.object(module.time, "monotonic", side_effect=[0, 6]):
|
||||
module.terminate([leader])
|
||||
self.assertIn(unittest.mock.call(12345, signal.SIGTERM), killpg.call_args_list)
|
||||
self.assertIn(unittest.mock.call(12345, 9), killpg.call_args_list)
|
||||
leader.wait.assert_called()
|
||||
|
||||
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
|
||||
def test_cancel_kills_resistant_child_after_recorder_exits(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp); plan = root / "plan"; plan.mkdir()
|
||||
for group in ("g1", "g2", "g3"):
|
||||
(plan / (group + ".txt")).write_text("example/g1\n" if group == "g1" else "")
|
||||
child = root / "child.py"
|
||||
child.write_text("import os,signal,sys,time\nfrom pathlib import Path\nsignal.signal(signal.SIGTERM,signal.SIG_IGN)\np=Path(sys.argv[1])\np.with_suffix('.tmp').write_text(str(os.getpid()))\np.with_suffix('.tmp').replace(p)\nwhile True: time.sleep(.1)\n")
|
||||
fake = root / "recorder.py"
|
||||
fake.write_text("import subprocess,sys,time\nsubprocess.Popen([sys.executable,sys.argv[1],sys.argv[2]])\nwhile True: time.sleep(.1)\n")
|
||||
marker = root / "child"
|
||||
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake), str(child), str(marker)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
||||
pid = None
|
||||
try:
|
||||
deadline = time.monotonic() + 5
|
||||
while not marker.exists():
|
||||
if time.monotonic() >= deadline: self.fail("resistant child did not start")
|
||||
time.sleep(.01)
|
||||
pid = int(marker.read_text())
|
||||
runner.terminate()
|
||||
self.assertEqual(runner.wait(timeout=12), 130)
|
||||
deadline = time.monotonic() + 2
|
||||
while True:
|
||||
stat = Path(f"/proc/{pid}/stat")
|
||||
if not stat.exists() or stat.read_text().split(") ", 1)[1].startswith("Z"): break
|
||||
if time.monotonic() >= deadline: self.fail("resistant child survived cancellation")
|
||||
time.sleep(.01)
|
||||
finally:
|
||||
if pid is not None:
|
||||
try: os.kill(pid, signal.SIGKILL)
|
||||
except ProcessLookupError: pass
|
||||
if runner.poll() is None: runner.kill()
|
||||
runner.communicate(timeout=5)
|
||||
|
||||
@unittest.skipUnless(os.name == "posix", "process-group cancellation is a Linux runner control")
|
||||
def test_cancel_joins_every_started_group(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp); plan = root / "plan"; plan.mkdir()
|
||||
for group in ("g1", "g2", "g3"):
|
||||
(plan / (group + ".txt")).write_text("example/" + group + "\n")
|
||||
fake = root / "held.py"
|
||||
fake.write_text("import os,sys,time\nfrom pathlib import Path\np=Path(sys.argv[1]).parent\n(p/'process.tmp').write_text(str(os.getpid()))\n(p/'process.tmp').replace(p/'process')\nwhile True: time.sleep(.1)\n")
|
||||
runner = subprocess.Popen([sys.executable, str(SCRIPT), str(plan), str(root / "evidence"), str(root / "tmp"), sys.executable, str(fake)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
||||
try:
|
||||
deadline = time.monotonic() + 5
|
||||
markers = [root / "evidence" / g / "process" for g in ("g1", "g2", "g3")]
|
||||
while not all(p.exists() for p in markers):
|
||||
if time.monotonic() >= deadline: self.fail("groups did not start")
|
||||
time.sleep(.01)
|
||||
children = [int(p.read_text()) for p in markers]
|
||||
runner.terminate()
|
||||
self.assertEqual(runner.wait(timeout=10), 130)
|
||||
for child in children:
|
||||
with self.assertRaises(ProcessLookupError): os.kill(child, 0)
|
||||
finally:
|
||||
if runner.poll() is None: runner.terminate()
|
||||
runner.communicate(timeout=10)
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Run the three default unit groups concurrently on the current runner.
|
||||
|
||||
Usage: run-unit-groups.py PLAN_DIR EVIDENCE_DIR TMP_DIR RECORDER [RECORDER_ARG ...]
|
||||
The recorder accepts OUTPUT followed by go-test flags and packages. Each group
|
||||
owns its logs/events; they are combined only after all group processes exit.
|
||||
"""
|
||||
from contextlib import ExitStack
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
def stop(_signum, _frame):
|
||||
raise KeyboardInterrupt
|
||||
|
||||
|
||||
def terminate(processes):
|
||||
for process in processes:
|
||||
try:
|
||||
if os.name == "posix": os.killpg(process.pid, signal.SIGTERM)
|
||||
elif process.poll() is None: process.terminate()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
if os.name == "posix":
|
||||
# The leader may exit on TERM while its descendants remain in the group.
|
||||
# Bound the grace period by group lifetime, never by leader lifetime.
|
||||
deadline = time.monotonic() + 5
|
||||
remaining = list(processes)
|
||||
while remaining and time.monotonic() < deadline:
|
||||
alive = []
|
||||
for process in remaining:
|
||||
process.poll() # Reap an exited leader without forgetting its PGID.
|
||||
try:
|
||||
os.killpg(process.pid, 0)
|
||||
alive.append(process)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
remaining = alive
|
||||
if remaining: time.sleep(.05)
|
||||
for process in remaining:
|
||||
try: os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError: pass
|
||||
for process in processes:
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
|
||||
|
||||
|
||||
def run(plan, evidence, temp, recorder):
|
||||
groups = {g: (plan / (g + ".txt")).read_text().splitlines() for g in ("g1", "g2", "g3")}
|
||||
evidence.mkdir(parents=True, exist_ok=True)
|
||||
started = time.monotonic()
|
||||
processes, results, times = {}, {}, {}
|
||||
with ExitStack() as files:
|
||||
try:
|
||||
for group, packages in groups.items():
|
||||
results[group] = {"packages": len(packages), "status": 0, "elapsed_seconds": 0}
|
||||
if not packages:
|
||||
print(f"{group}: no packages selected by scope", flush=True)
|
||||
continue
|
||||
out = evidence / group; out.mkdir(parents=True, exist_ok=True)
|
||||
scratch = temp / group; scratch.mkdir(parents=True, exist_ok=True)
|
||||
# /proc/self/fd exposes resolved paths; preserve fixture identity even
|
||||
# when the runner temp directory is a symlink to its data disk.
|
||||
scratch = scratch.resolve(strict=True)
|
||||
log = files.enter_context((out / "console.log").open("w", encoding="utf-8"))
|
||||
command = recorder + [str(out / "go-test.json"), "-p=" + ("4" if group == "g3" else "1"), "-short", "-count=1", "-timeout", "20m", *packages]
|
||||
times[group] = time.monotonic()
|
||||
processes[group] = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
|
||||
env=dict(os.environ, TMPDIR=str(scratch)), start_new_session=os.name == "posix")
|
||||
print(f"{group}: started {len(packages)} packages", flush=True)
|
||||
remaining = set(processes)
|
||||
while remaining:
|
||||
for group in tuple(remaining):
|
||||
status = processes[group].poll()
|
||||
if status is not None:
|
||||
results[group]["status"] = status
|
||||
results[group]["elapsed_seconds"] = round(time.monotonic() - times[group], 3)
|
||||
remaining.remove(group)
|
||||
if remaining: time.sleep(.05)
|
||||
except BaseException:
|
||||
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
terminate(processes.values())
|
||||
raise
|
||||
for group in processes:
|
||||
print(f"--- {group} ---", flush=True)
|
||||
print((evidence / group / "console.log").read_text(errors="replace"), flush=True)
|
||||
summary = {"elapsed_seconds": round(time.monotonic() - started, 3), "groups": results}
|
||||
try:
|
||||
(evidence / "unit-groups.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
|
||||
with (evidence / "go-test.json").open("ab") as combined:
|
||||
for group in processes:
|
||||
events = evidence / group / "go-test.json"
|
||||
if events.exists(): combined.write(events.read_bytes())
|
||||
except OSError as error:
|
||||
print(f"test evidence unavailable: {error}", file=sys.stderr)
|
||||
print(json.dumps(summary), flush=True)
|
||||
return int(any(r["status"] != 0 for r in results.values()))
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) < 5:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
try:
|
||||
return run(Path(argv[1]), Path(argv[2]), Path(argv[3]), argv[4:])
|
||||
except KeyboardInterrupt:
|
||||
return 130
|
||||
except (OSError, ValueError) as error:
|
||||
print(f"unit groups: {error}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__": sys.exit(main(sys.argv))
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Read-only block merge readiness check. Run from a trusted master checkout.
|
||||
|
||||
Usage (inside seaweed-block/): python3 ../.github/block/scripts/safe-merge-check.py PR
|
||||
Never merges, posts comments, changes account config or pushes refs.
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO = "seaweedfs/seaweedfs"
|
||||
JOBS = {"go test (linux)", "process-level tests (real binaries)"}
|
||||
|
||||
|
||||
def validate(pr, run, jobs, current):
|
||||
if pr["state"] != "open" or pr["draft"] or pr["mergeable"] is not True:
|
||||
raise ValueError("PR must be open, ready and mergeable")
|
||||
if pr["base"]["ref"] != "master": raise ValueError("expected master base")
|
||||
if run["name"] != "Block Test" or run["head_sha"] != pr["head"]["sha"]:
|
||||
raise ValueError("wrong workflow or head")
|
||||
if run["status"] != "completed" or run["conclusion"] != "success":
|
||||
raise ValueError("Block Test is not successful")
|
||||
bases = [p["base"]["sha"] for p in run["pull_requests"] if p["number"] == pr["number"]]
|
||||
if bases != [current]: raise ValueError("tested base is not current master")
|
||||
required = [j for j in jobs if j["name"] in JOBS]
|
||||
if len(required) != 2 or {j["name"] for j in required} != JOBS or any(j["conclusion"] != "success" for j in required):
|
||||
raise ValueError("both block test jobs must succeed")
|
||||
|
||||
|
||||
def api(path):
|
||||
return json.loads(subprocess.check_output(["gh", "api", "repos/" + REPO + "/" + path]))
|
||||
|
||||
|
||||
def successful_run(pr, current):
|
||||
runs = api("actions/runs?head_sha=" + pr["head"]["sha"] + "&event=pull_request&per_page=100")["workflow_runs"]
|
||||
runs = [r for r in runs if r["name"] == "Block Test"]
|
||||
if not runs: raise ValueError("no Block Test run")
|
||||
run = max(runs, key=lambda r: (r["created_at"], r["id"]))
|
||||
pages = json.loads(subprocess.check_output(["gh", "api", "--paginate", "--slurp", "repos/" + REPO + "/actions/runs/" + str(run["id"]) + "/jobs?per_page=100"]))
|
||||
validate(pr, run, [j for page in pages for j in page["jobs"]], current)
|
||||
return run
|
||||
|
||||
|
||||
def local_checks(pr, current):
|
||||
if subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() != current:
|
||||
raise ValueError("run from trusted current master checkout")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
body, title = Path(tmp) / "body", Path(tmp) / "title"
|
||||
body.write_text(pr["body"] or "", encoding="utf-8")
|
||||
title.write_text(pr["title"], encoding="utf-8")
|
||||
subprocess.run(["git", "-c", "fetch.fsckObjects=true", "fetch", "--no-tags", "origin", "+refs/pull/" + str(pr["number"]) + "/head:refs/remotes/block-review/head"], check=True)
|
||||
actual = subprocess.check_output(["git", "rev-parse", "refs/remotes/block-review/head"], text=True).strip()
|
||||
if actual != pr["head"]["sha"]: raise ValueError("PR head moved; recheck")
|
||||
subprocess.run(["bash", str(Path(__file__).resolve().with_name("check-pr-base.sh")), current, actual, str(body), str(title)], check=True)
|
||||
|
||||
|
||||
def validate_batch(manifest, prs, current):
|
||||
if manifest["base"] != current: raise ValueError("master moved since batch creation")
|
||||
if not manifest["head"] or len(manifest["prs"]) < 2: raise ValueError("expected pinned batch and at least two PRs")
|
||||
numbers = [p["number"] for p in manifest["prs"]]
|
||||
if len(set(numbers)) != len(numbers) or numbers != [p["number"] for p in prs]:
|
||||
raise ValueError("batch PR order differs or repeats")
|
||||
for saved, pr in zip(manifest["prs"], prs):
|
||||
if pr["state"] != "open" or pr["draft"] or pr["base"]["ref"] != "master" or pr["head"]["sha"] != saved["head"]:
|
||||
raise ValueError("batch member is not ready or its head changed")
|
||||
if not Path(saved["evidence"]).is_file() or not Path(saved["evidence"]).read_text().strip():
|
||||
raise ValueError("batch member has no acceptance evidence")
|
||||
|
||||
|
||||
def main(args):
|
||||
current = api("git/ref/heads/master")["object"]["sha"]
|
||||
if len(args) == 2 and args[0] == "--verify-tree":
|
||||
tree = api("git/commits/" + current)["tree"]["sha"]
|
||||
if tree != args[1]: raise ValueError("master tree differs from the tested batch")
|
||||
print(json.dumps({"tree_matches": True, "master": current, "tree": tree}))
|
||||
return
|
||||
if len(args) == 2 and args[0] == "--batch":
|
||||
manifest = json.loads(Path(args[1]).read_text())
|
||||
prs = [api("pulls/" + str(p["number"])) for p in manifest["prs"]]
|
||||
validate_batch(manifest, prs, current)
|
||||
batch = api("pulls/" + str(manifest["batch_pr"]))
|
||||
if batch["head"]["sha"] != manifest["head"]: raise ValueError("batch head changed")
|
||||
run = successful_run(batch, current)
|
||||
for pr in prs: local_checks(pr, current)
|
||||
if api("git/ref/heads/master")["object"]["sha"] != current: raise ValueError("master moved; recheck")
|
||||
for pr in prs + [batch]:
|
||||
if api("pulls/" + str(pr["number"]))["head"]["sha"] != pr["head"]["sha"]: raise ValueError("head moved; recheck")
|
||||
print(json.dumps({"ready": True, "base": current, "head": manifest["head"], "run": run["id"], "tree": api("git/commits/" + manifest["head"])["tree"]["sha"], "order": [p["number"] for p in prs]}))
|
||||
return
|
||||
if len(args) != 1 or not args[0].isdecimal(): raise ValueError("expected PR, --batch MANIFEST or --verify-tree TREE")
|
||||
pr = api("pulls/" + args[0])
|
||||
run = successful_run(pr, current)
|
||||
local_checks(pr, current)
|
||||
if api("git/ref/heads/master")["object"]["sha"] != current or api("pulls/" + args[0])["head"]["sha"] != pr["head"]["sha"]:
|
||||
raise ValueError("base or head moved; recheck")
|
||||
print(json.dumps({"ready": True, "head": pr["head"]["sha"], "base": current, "run": run["id"], "merge_mode": "squash"}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main(sys.argv[1:])
|
||||
except (IndexError, KeyError, ValueError, OSError, subprocess.SubprocessError) as error:
|
||||
print("REFUSED: " + str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Exact coverage before scope selection; old heavy-package rules afterward."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location("planner", Path(__file__).with_name("unit-test-shards.py"))
|
||||
planner = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(planner)
|
||||
MODULE = "example.invalid/product"
|
||||
HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority")
|
||||
|
||||
|
||||
class UnitShardTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.packages = [MODULE + "/" + p for p in (*HEAVY, "cmd/sw-block", "core/frontend/chunkstore", "internal/newpackage", "core/storage/child")]
|
||||
self.groups = planner.partition(MODULE, self.packages)
|
||||
|
||||
def test_exact_cover_and_stable_order(self):
|
||||
flat = [p for group in self.groups.values() for p in group]
|
||||
self.assertCountEqual(flat, self.packages)
|
||||
self.assertEqual(len(flat), len(set(flat)))
|
||||
self.assertEqual(self.groups, planner.partition(MODULE, list(reversed(self.packages))))
|
||||
self.assertEqual(self.groups["g1"], [MODULE + "/core/storage"])
|
||||
self.assertEqual(self.groups["g2"], [MODULE + "/" + p for p in HEAVY[1:]])
|
||||
self.assertIn(MODULE + "/internal/newpackage", self.groups["g3"])
|
||||
self.assertIn(MODULE + "/core/storage/child", self.groups["g3"])
|
||||
|
||||
def test_existing_heavy_scope_on_main_train_and_prs(self):
|
||||
all_changed = [p + "/changed.go" for p in HEAVY]
|
||||
for event, ref in (("push", ""), ("pull_request", "train/next")):
|
||||
selected = planner.select(MODULE, self.groups, event, ref, all_changed)
|
||||
self.assertEqual(selected["g1"], [])
|
||||
self.assertEqual(selected["g2"], [])
|
||||
self.assertEqual(selected["g3"], self.groups["g3"])
|
||||
self.assertEqual(planner.select(MODULE, self.groups, "pull_request", "fix/x", all_changed), self.groups)
|
||||
for path in HEAVY:
|
||||
selected = planner.select(MODULE, self.groups, "pull_request", "fix/x", [path + "/x.go"])
|
||||
heavy = selected["g1"] + selected["g2"]
|
||||
self.assertEqual(heavy, [MODULE + "/" + path])
|
||||
nested = planner.select(MODULE, self.groups, "pull_request", "fix/x", ["core/storage/child/x.go", "core/storage/"])
|
||||
self.assertEqual(nested["g1"], [])
|
||||
self.assertEqual(nested["g2"], [])
|
||||
self.assertEqual(nested["g3"], self.groups["g3"])
|
||||
|
||||
def test_invalid_inventory_is_refused(self):
|
||||
for packages in ([], self.packages + [self.packages[0]], self.packages[1:], self.packages + ["other/pkg"]):
|
||||
with self.subTest(packages=packages), self.assertRaises(ValueError):
|
||||
planner.partition(MODULE, packages)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Plan the default unit groups from the full go-list inventory.
|
||||
|
||||
Usage: go list ./... | python3 unit-test-shards.py MODULE OUT_DIR EVENT HEAD_REF CHANGED_FILE
|
||||
The complete partition covers every package exactly once. Existing scope rules
|
||||
then select heavy packages only on ordinary PRs that touch their direct files.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
HEAVY = ("core/storage", "core/frontend/durable", "core/host/master", "core/authority")
|
||||
|
||||
|
||||
def partition(module, packages):
|
||||
if not module or any(c.isspace() for c in module):
|
||||
raise ValueError("expected one module path")
|
||||
if not packages or len(packages) != len(set(packages)):
|
||||
raise ValueError("empty package list or duplicate package")
|
||||
if any(p != module and not p.startswith(module + "/") for p in packages):
|
||||
raise ValueError("package outside the selected module")
|
||||
heavy = [module + "/" + p for p in HEAVY]
|
||||
if not set(heavy) <= set(packages):
|
||||
raise ValueError("required heavy packages missing from go list")
|
||||
return {"g1": heavy[:1], "g2": heavy[1:], "g3": sorted(set(packages) - set(heavy))}
|
||||
|
||||
|
||||
def select(module, groups, event, head_ref, changed):
|
||||
selected = set()
|
||||
if event != "push" and not head_ref.startswith("train/"):
|
||||
for p in HEAVY:
|
||||
if any(f.startswith(p + "/") and f[len(p) + 1:] and "/" not in f[len(p) + 1:] for f in changed):
|
||||
selected.add(module + "/" + p)
|
||||
return {name: [p for p in packages if name == "g3" or p in selected]
|
||||
for name, packages in groups.items()}
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 6:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
groups = partition(argv[1], sys.stdin.read().split())
|
||||
groups = select(argv[1], groups, argv[3], argv[4], Path(argv[5]).read_text().splitlines())
|
||||
out = Path(argv[2])
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
for name, packages in groups.items():
|
||||
(out / (name + ".txt")).write_text("".join(p + "\n" for p in packages), encoding="utf-8")
|
||||
print(f"{name}: {len(packages)} packages")
|
||||
except (OSError, ValueError) as error:
|
||||
print(f"unit-test-shards: {error}", file=sys.stderr)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
Reference in new issue
Block a user