Files
Holocron/scripts/tag-plugin-releases.sh
T
Defame1297andClaude Opus 5.5 b3fd1f2f0c fix(scripts): validate every release tag and gate --apply on origin/main
A mis-cut tag could serve as the start point and silently drop the runs
before it: x-v9.9.9 or a lightweight x-v1.0.1 on a later landing hid an
untagged 1.1.0 and --apply succeeded. Every reachable <p>-v<semver> tag is
now validated (annotated, peels to a landing of its own version); an
invalid one is an ERROR row naming it, blocks --apply, and is never the
start point.

Also from review:
- --apply needs origin/main and a ref on it; no local-main fallback.
- A version with literal quotes is invalid, not stripped.
- Plugin dirs are listed NUL-separated; a leading-dash name exits 2.
- With no tags, the backfill starts at the current version's first
  landing, so a recurring version is released once, there (Case 2, 12d).
- expect_row ERE-escapes plugin and version.

ADR-0033 updated to match.

Refs: #223

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNugst7K9Bd2FTR4Mi
2026-11-27 18:14:23 +00:00

477 lines
18 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
# Cuts the per-plugin release tags ADR-0033 requires: one annotated tag
# `<plugin>-v<version>` per version a plugin ships on main, on the commit where
# that version first landed. Consumers pin these (Renovate's apm manager, `apm
# outdated`); the repo-level v* tags match no plugin.
#
# Usage: scripts/tag-plugin-releases.sh [--apply] [--ref <rev>] [--plugin <name>]...
#
# (no flags) dry run: print the table, create nothing.
# --apply create every MISSING tag locally, then print the exact
# `git push origin <tag>...` line. Pushing is the maintainer's
# step; this script never pushes and never fetches. Requires
# origin/main to resolve and the ref to be on it (an ancestor
# of, or equal to, origin/main); otherwise exit 2.
# --ref <rev> the history to read (default origin/main; a dry run falls
# back to the local `main` with a staleness note, --apply
# never does).
# --plugin <n> limit to these plugins (repeatable; default: every plugin).
#
# Run `git fetch origin --tags` first. The script reads only local refs, so a
# stale origin/main hides a merged bump and a missing remote tag reads MISSING.
#
# Everything is read from the ref's git objects (`git ls-tree`, `git show`),
# never the working tree, so a dirty checkout or another branch cannot change
# the answer.
#
# Per plugin (a directory under plugins/ carrying apm.yml at the ref):
# - apm.yml `name` must equal the directory and `version` must be strict
# MAJOR.MINOR.PATCH at the ref, neither containing whitespace; otherwise
# exit 2.
# - Walk the ref's FIRST-PARENT history over commits touching
# plugins/<p>/apm.yml, oldest first, and group contiguous equal-version
# commits into runs. An apm.yml edit that leaves the version alone extends
# the current run; it never starts a new one. A run's target is its oldest
# commit: the merge or squash commit on main where the version first
# landed, never a feature-branch commit.
# - Every `<p>-v<semver>` tag reachable from the ref is validated: it must be
# annotated and peel to a run target carrying its own version. Any other
# such tag is an ERROR row naming it, and it never serves as the start
# point, so a mis-cut tag can neither hide runs nor go unreported.
# - Wanted runs: every run from the newest validly tagged run onward. With
# no valid tag (the backfill), every run from the FIRST landing of the
# current version onward; when the current version never recurred, that is
# the current run alone. Older history is not tagged retroactively.
# - A version is released once, at its FIRST landing. When a version recurs
# (a revert, or apm.yml deleted and re-added), the later run is not tagged
# again: it reports RELEASED.
# - Status per wanted run: MISSING (no tag), OK (annotated, peels to the
# target), RELEASED (the tag peels to an earlier run of the same version,
# or the version is untagged and an earlier wanted run carries it, so that
# run is the one tagged), ERROR (lightweight, peels to no landing of that
# version, invalid version in history, or a tag name git rejects).
# - A plugin directory whose name starts with `-` is rejected (exit 2): its
# tag name would parse as an option.
# RELEASED never blocks other rows and never changes the exit code.
#
# Tag matching is anchored: `<p>-v` followed by a strict semver and nothing
# else, so git, gitea and gitops never claim each other's tags.
#
# Tags are immutable: this script never moves, deletes or overwrites one.
# --apply is all-or-nothing: any ERROR anywhere creates nothing. If `git tag`
# still fails mid-run, the tags already created are listed with their push
# line and the script exits 2.
#
# Exit: 0 nothing missing (or --apply created all of it); 1 dry run found
# MISSING tags; 2 any ERROR, bad input, shallow clone, unresolvable ref,
# --apply off origin/main, missing python3/PyYAML, or a `git tag` failure
# during --apply.
export LC_ALL=C
# shellcheck source=scripts/lib/clean-git-env.sh
source "$(dirname "${BASH_SOURCE[0]}")/lib/clean-git-env.sh"
usage() {
echo "Usage: $0 [--apply] [--ref <rev>] [--plugin <name>]..." >&2
}
APPLY=false
REF=""
PLUGINS=()
while [[ $# -gt 0 ]]; do
case "$1" in
--apply) APPLY=true; shift ;;
--ref)
[[ $# -ge 2 && -n "$2" ]] || { usage; exit 2; }
REF="$2"; shift 2 ;;
--plugin)
[[ $# -ge 2 && -n "$2" ]] || { usage; exit 2; }
PLUGINS+=("$2"); shift 2 ;;
-h|--help) usage; exit 0 ;;
*) echo "FAIL: unknown argument: $1" >&2; usage; exit 2 ;;
esac
done
if ! REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"; then
echo "FAIL: not inside a git work tree." >&2
exit 2
fi
cd "$REPO_ROOT"
if ! command -v python3 > /dev/null 2>&1; then
echo "FAIL: python3 is required to read apm.yml but was not found on PATH." >&2
exit 2
fi
if ! python3 -c 'import yaml' > /dev/null 2>&1; then
echo "FAIL: PyYAML is required to read apm.yml but is not importable by python3." >&2
echo " Fix: python3 -m pip install PyYAML (or your distro's python3-yaml package)." >&2
exit 2
fi
# A shallow clone truncates first-parent history, so the oldest commit of a run
# would be wrong without any error. Fail closed.
if [[ "$(git rev-parse --is-shallow-repository)" == "true" ]]; then
echo "FAIL: shallow clone; run targets cannot be computed from truncated history." >&2
echo " Fix: git fetch --unshallow origin, then retry." >&2
exit 2
fi
is_ancestor() { git merge-base --is-ancestor "$1" "$2" 2>/dev/null; }
if [[ -n "$REF" ]]; then
if ! REF_COMMIT="$(git rev-parse --verify -q "$REF^{commit}")"; then
echo "FAIL: --ref $REF does not resolve to a commit." >&2
exit 2
fi
else
if REF_COMMIT="$(git rev-parse --verify -q "origin/main^{commit}")"; then
REF="origin/main"
elif REF_COMMIT="$(git rev-parse --verify -q "main^{commit}")"; then
REF="main"
echo "NOTE: origin/main does not resolve; reading local main, which may be behind the remote." >&2
else
echo "FAIL: neither origin/main nor main resolves; pass --ref <rev>." >&2
exit 2
fi
fi
# --apply tags only commits on origin/main: never a feature-branch commit, and
# never the local `main`, which may hold unpushed work.
if $APPLY; then
if ! ORIGIN_MAIN="$(git rev-parse --verify -q "origin/main^{commit}")"; then
echo "FAIL: --apply needs origin/main, which does not resolve; run git fetch origin --tags first." >&2
exit 2
fi
if ! is_ancestor "$REF_COMMIT" "$ORIGIN_MAIN"; then
echo "FAIL: --apply: $REF (${REF_COMMIT:0:7}) is not on origin/main; release tags go only on main's history." >&2
exit 2
fi
fi
# Plugin directories at the ref: trees under plugins/ that carry apm.yml.
# NUL-separated, so unusual names are read verbatim, never quoted.
ALL_PLUGINS=()
while IFS= read -r -d '' path; do
p="${path#plugins/}"
if git cat-file -e "$REF_COMMIT:plugins/$p/apm.yml" 2>/dev/null; then
ALL_PLUGINS+=("$p")
fi
done < <(git ls-tree -z -d --name-only "$REF_COMMIT" plugins/)
if [[ ${#PLUGINS[@]} -eq 0 ]]; then
PLUGINS=(${ALL_PLUGINS[@]+"${ALL_PLUGINS[@]}"})
else
for p in ${PLUGINS[@]+"${PLUGINS[@]}"}; do
found=false
for q in ${ALL_PLUGINS[@]+"${ALL_PLUGINS[@]}"}; do
[[ "$p" == "$q" ]] && { found=true; break; }
done
if ! $found; then
echo "FAIL: --plugin $p: no plugins/$p/apm.yml at $REF." >&2
exit 2
fi
done
fi
if [[ ${#PLUGINS[@]} -eq 0 ]]; then
echo "FAIL: no plugins/<name>/apm.yml found at $REF." >&2
exit 2
fi
# A leading dash would make the tag name `-x-v1.0.0` parse as an option.
for p in ${PLUGINS[@]+"${PLUGINS[@]}"}; do
if [[ "$p" == -* ]]; then
echo "ERROR: plugins/$p: a plugin name must not start with '-' (its tag would parse as an option)." >&2
exit 2
fi
done
# Reads "<commit>" lines on stdin and, for plugin path $1, prints one line per
# commit: "<commit> OK <name> <version>", "<commit> INVALID <name|-> -" when
# the version is not strict semver or the YAML does not parse, or
# "<commit> ABSENT - -" when the commit has no such file. A name containing
# whitespace prints as "<whitespace>", which never equals a directory name; a
# version containing whitespace is INVALID. Blobs come from one
# `git cat-file --batch`, so the cost is one python3 start per plugin, not per
# commit. A crash prints nothing for the remaining commits; the caller checks
# the count.
read_versions() {
python3 -c '
import re, subprocess, sys, yaml
path = sys.argv[1]
commits = [l.strip() for l in sys.stdin if l.strip()]
p = subprocess.Popen(["git", "cat-file", "--batch"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
SEMVER = re.compile(r"(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})")
for c in commits:
p.stdin.write(("%s:%s\n" % (c, path)).encode()); p.stdin.flush()
header = p.stdout.readline().decode().split()
if len(header) < 3 or header[-1] == "missing":
print(c, "ABSENT - -"); continue
if header[1] != "blob":
p.stdout.read(int(header[2])); p.stdout.readline()
print(c, "ABSENT - -"); continue
data = p.stdout.read(int(header[2])); p.stdout.readline()
try:
doc = yaml.safe_load(data.decode("utf-8-sig", errors="replace"))
except yaml.YAMLError:
doc = None
name = doc.get("name") if isinstance(doc, dict) else None
ver = doc.get("version") if isinstance(doc, dict) else None
name = "-" if name is None else (str(name) or "-")
if re.search(r"\s", name):
name = "<whitespace>"
ver = None if ver is None else str(ver)
if ver is not None and SEMVER.fullmatch(ver):
print(c, "OK", name, ver)
else:
print(c, "INVALID", name, "-")
p.stdin.close(); p.wait()
' "$1"
}
SEMVER_RE='^(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})$'
# Result rows, index-matched (bash 3.2 has no declare -A).
ROW_PLUGIN=(); ROW_VERSION=(); ROW_COMMIT=(); ROW_STATUS=(); ROW_DETAIL=()
add_row() {
ROW_PLUGIN+=("$1"); ROW_VERSION+=("$2"); ROW_COMMIT+=("$3"); ROW_STATUS+=("$4"); ROW_DETAIL+=("$5")
}
for p in ${PLUGINS[@]+"${PLUGINS[@]}"}; do
apm="plugins/$p/apm.yml"
# Oldest first. --first-parent with a path keeps each first-parent commit
# whose apm.yml differs from its first parent's: on main that is the merge
# or squash commit that brought the change in.
COMMITS=()
while IFS= read -r c; do COMMITS+=("$c"); done \
< <(git rev-list --first-parent --reverse "$REF_COMMIT" -- "$apm")
LINES=()
while IFS= read -r l; do LINES+=("$l"); done \
< <(printf '%s\n' ${COMMITS[@]+"${COMMITS[@]}"} | read_versions "$apm")
if [[ ${#LINES[@]} -ne ${#COMMITS[@]} ]]; then
echo "FAIL: could not read $apm across $REF history (see error above)." >&2
exit 2
fi
# The ref's own copy is authoritative for name and current version.
read -r _ cur_status cur_name _ <<< "$(printf '%s\n' "$REF_COMMIT" | read_versions "$apm")"
if [[ "$cur_name" == "<whitespace>" ]]; then
echo "FAIL: $apm at $REF has whitespace in its name; it must equal the directory name '$p'." >&2
exit 2
fi
if [[ "$cur_name" != "$p" ]]; then
echo "FAIL: $apm at $REF has name '$cur_name'; it must equal the directory name '$p' (the tag is '$p-v<version>')." >&2
exit 2
fi
if [[ "$cur_status" != "OK" ]]; then
echo "FAIL: $apm at $REF has no strict MAJOR.MINOR.PATCH version (no whitespace allowed)." >&2
exit 2
fi
# Group into runs. A commit where the file is absent breaks contiguity.
RUN_VER=(); RUN_TARGET=(); RUN_VALID=()
prev=""
for l in ${LINES[@]+"${LINES[@]}"}; do
read -r c st _ v <<< "$l"
case "$st" in
ABSENT) prev=""; continue ;;
INVALID) key="INVALID" ;;
*) key="$v" ;;
esac
if [[ "$key" != "$prev" ]]; then
RUN_VER+=("$v"); RUN_TARGET+=("$c")
if [[ "$st" == OK ]]; then RUN_VALID+=(true); else RUN_VALID+=(false); fi
prev="$key"
fi
done
nruns=${#RUN_VER[@]}
# Start point: the newest run a VALID reachable <p>-v<semver> tag peels to.
# Every such tag is validated first: annotated, and peeling to a run target
# carrying its own version. Any other is recorded as bad: it is reported and
# never serves as the start point, so it cannot hide the runs before it.
anchor=-1
BAD_TAG=(); BAD_VER=(); BAD_COMMIT=(); BAD_DETAIL=()
while IFS= read -r tagname; do
[[ "$tagname" == "$p-v"* ]] || continue
tv="${tagname#"$p-v"}"
[[ "$tv" =~ $SEMVER_RE ]] || continue
if ! peeled="$(git rev-parse --verify -q "refs/tags/$tagname^{commit}")"; then
BAD_TAG+=("$tagname"); BAD_VER+=("$tv"); BAD_COMMIT+=("-")
BAD_DETAIL+=("$tagname does not peel to a commit")
continue
fi
is_ancestor "$peeled" "$REF_COMMIT" || continue
if [[ "$(git cat-file -t "refs/tags/$tagname")" != "tag" ]]; then
BAD_TAG+=("$tagname"); BAD_VER+=("$tv"); BAD_COMMIT+=("$peeled")
BAD_DETAIL+=("$tagname is a lightweight tag; it must be annotated")
continue
fi
pos=-1
for ((i = 0; i < nruns; i++)); do
if [[ "${RUN_TARGET[i]}" == "$peeled" && "${RUN_VALID[i]}" == true && "${RUN_VER[i]}" == "$tv" ]]; then pos=$i; fi
done
if [[ $pos -lt 0 ]]; then
BAD_TAG+=("$tagname"); BAD_VER+=("$tv"); BAD_COMMIT+=("$peeled")
BAD_DETAIL+=("$tagname peels to ${peeled:0:7}, which is no landing of $tv on the first-parent history")
continue
fi
[[ $pos -gt $anchor ]] && anchor=$pos
done < <(git for-each-ref --format='%(refname:strip=2)' "refs/tags/$p-v*")
if [[ $anchor -ge 0 ]]; then
first=$anchor
else
# Backfill: start at the current version's first landing, so it is
# released once, there; a later run of it then reports RELEASED.
cur_ver="${RUN_VER[nruns - 1]}"
first=$((nruns - 1))
for ((i = 0; i < nruns; i++)); do
if [[ "${RUN_VALID[i]}" == true && "${RUN_VER[i]}" == "$cur_ver" ]]; then first=$i; break; fi
done
fi
# Tags the run loop below reports itself, so the bad-tag rows skip them.
REPORTED=()
for ((i = first; i < nruns; i++)); do
v="${RUN_VER[i]}"; target="${RUN_TARGET[i]}"
if [[ "${RUN_VALID[i]}" != true ]]; then
add_row "$p" "INVALID" "$target" ERROR "$apm version at ${target:0:7} is not MAJOR.MINOR.PATCH"
continue
fi
tag="$p-v$v"
if ! git rev-parse --verify -q "refs/tags/$tag" > /dev/null; then
# Untagged: the version is released at its first landing in the wanted
# set, so a later run of the same version is not tagged again.
earlier=""
for ((j = first; j < i; j++)); do
if [[ "${RUN_VALID[j]}" == true && "${RUN_VER[j]}" == "$v" ]]; then earlier="${RUN_TARGET[j]}"; break; fi
done
if [[ -n "$earlier" ]]; then
add_row "$p" "$v" "$target" RELEASED "$v is released at its first landing ${earlier:0:7}"
continue
fi
if ! git check-ref-format "refs/tags/$tag"; then
add_row "$p" "$v" "$target" ERROR "'$tag' is not a valid tag name (git check-ref-format)"
continue
fi
add_row "$p" "$v" "$target" MISSING ""
continue
fi
if [[ "$(git cat-file -t "refs/tags/$tag")" != "tag" ]]; then
add_row "$p" "$v" "$target" ERROR "$tag is a lightweight tag; it must be annotated"
REPORTED+=("$tag")
continue
fi
peeled="$(git rev-parse --verify -q "refs/tags/$tag^{commit}" || true)"
if [[ "$peeled" == "$target" ]]; then
add_row "$p" "$v" "$target" OK ""
continue
fi
# Tagged elsewhere: fine only if it peels to an EARLIER run of the same
# version (the first landing, e.g. before a revert brought $v back).
landing=-1
for ((j = 0; j < i; j++)); do
if [[ "${RUN_TARGET[j]}" == "$peeled" && "${RUN_VALID[j]}" == true && "${RUN_VER[j]}" == "$v" ]]; then landing=$j; fi
done
if [[ $landing -ge 0 ]]; then
add_row "$p" "$v" "$target" RELEASED "$tag already released at ${peeled:0:7}"
continue
fi
add_row "$p" "$v" "$target" ERROR "$tag peels to ${peeled:0:7}, not ${target:0:7} or any earlier landing of $v"
REPORTED+=("$tag")
done
# Bad tags no wanted run reported: one ERROR row each, naming the tag.
for ((k = 0; k < ${#BAD_TAG[@]}; k++)); do
seen=false
for r in ${REPORTED[@]+"${REPORTED[@]}"}; do
[[ "$r" == "${BAD_TAG[k]}" ]] && { seen=true; break; }
done
$seen || add_row "$p" "${BAD_VER[k]}" "${BAD_COMMIT[k]}" ERROR "${BAD_DETAIL[k]}"
done
done
print_table() {
local i
printf '%-12s %-10s %-8s %s\n' PLUGIN VERSION COMMIT STATUS
for ((i = 0; i < ${#ROW_PLUGIN[@]}; i++)); do
printf '%-12s %-10s %-8s %s\n' "${ROW_PLUGIN[i]}" "${ROW_VERSION[i]}" "${ROW_COMMIT[i]:0:7}" "${ROW_STATUS[i]}"
done
}
ERRORS=0; MISSING=0
for ((i = 0; i < ${#ROW_STATUS[@]}; i++)); do
case "${ROW_STATUS[i]}" in
ERROR) ERRORS=$((ERRORS + 1)) ;;
MISSING) MISSING=$((MISSING + 1)) ;;
esac
done
report_released() {
local i
for ((i = 0; i < ${#ROW_STATUS[@]}; i++)); do
[[ "${ROW_STATUS[i]}" == RELEASED ]] && echo "NOTE: ${ROW_PLUGIN[i]}: ${ROW_DETAIL[i]}; nothing to tag at ${ROW_COMMIT[i]:0:7}." >&2
done
return 0
}
report_errors() {
local i
for ((i = 0; i < ${#ROW_STATUS[@]}; i++)); do
[[ "${ROW_STATUS[i]}" == ERROR ]] && echo "ERROR: ${ROW_PLUGIN[i]}: ${ROW_DETAIL[i]}" >&2
done
echo "Tags are immutable: fix by hand only after deciding which commit each version belongs to (ADR-0033)." >&2
}
if ! $APPLY; then
print_table
report_released
if [[ $ERRORS -gt 0 ]]; then report_errors; exit 2; fi
if [[ $MISSING -gt 0 ]]; then
echo "$MISSING tag(s) missing at $REF. Re-run with --apply to create them." >&2
exit 1
fi
exit 0
fi
if [[ $ERRORS -gt 0 ]]; then
print_table
report_released
report_errors
echo "Nothing created: --apply is all-or-nothing." >&2
exit 2
fi
CREATED=()
print_push() {
[[ ${#CREATED[@]} -gt 0 ]] || return 0
echo "Created ${#CREATED[@]} tag(s) locally. Push them (maintainer's step, ADR-0033):"
echo "git push origin ${CREATED[*]}"
}
for ((i = 0; i < ${#ROW_STATUS[@]}; i++)); do
[[ "${ROW_STATUS[i]}" == MISSING ]] || continue
tag="${ROW_PLUGIN[i]}-v${ROW_VERSION[i]}"
if ! git tag -a "$tag" -m "${ROW_PLUGIN[i]} ${ROW_VERSION[i]}" "${ROW_COMMIT[i]}"; then
ROW_STATUS[i]=ERROR
print_table
echo "ERROR: git tag $tag failed (see above); stopped there." >&2
print_push
exit 2
fi
ROW_STATUS[i]=CREATED
CREATED+=("$tag")
done
print_table
report_released
print_push
exit 0