#!/usr/bin/env bash set -euo pipefail # Cuts the per-plugin release tags ADR-0033 requires: one annotated tag # `-v` 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 ] [--plugin ]... # # (no flags) dry run: print the table, create nothing. # --apply create every MISSING tag locally, then print the exact # `git push origin ...` line. Pushing is the maintainer's # step; this script never pushes and never fetches. # --ref the history to read (default origin/main, falling back to the # local `main` with a staleness note). # --plugin 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/

/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. # - Wanted runs: with no `

-v` tag reachable from the ref, only the # current run (the backfill). Otherwise every run from the newest such tag's # run onward. A tag's run is the run it targets; a tag targeting no run # counts as the last run whose target is its ancestor, so a mis-cut tag # widens the wanted set rather than hiding runs. The anchor run itself is # re-checked, so a mis-cut tag surfaces as an ERROR. # - 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). # RELEASED never blocks other rows and never changes the exit code. # # Tag matching is anchored: `

-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, # 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 ] [--plugin ]..." >&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 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 ." >&2 exit 2 fi fi # Plugin directories at the ref: trees under plugins/ that carry apm.yml. ALL_PLUGINS=() while IFS= read -r 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 -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//apm.yml found at $REF." >&2 exit 2 fi # Reads "" lines on stdin and, for plugin path $1, prints one line per # commit: " OK ", " INVALID -" when # the version is not strict semver or the YAML does not parse, or # " ABSENT - -" when the commit has no such file. A name containing # whitespace prints as "", 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 = "" ver = None if ver is None else str(ver).strip("\x27\"") 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})$' is_ancestor() { git merge-base --is-ancestor "$1" "$2" 2>/dev/null; } # 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" == "" ]]; 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')." >&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[@]} # Anchor: the newest run a reachable

-v tag belongs to. anchor=-1 while IFS= read -r tagname; do [[ "$tagname" == "$p-v"* ]] || continue [[ "${tagname#"$p-v"}" =~ $SEMVER_RE ]] || continue peeled="$(git rev-parse --verify -q "refs/tags/$tagname^{commit}")" || continue is_ancestor "$peeled" "$REF_COMMIT" || continue pos=-1 for ((i = 0; i < nruns; i++)); do [[ "${RUN_TARGET[i]}" == "$peeled" ]] && pos=$i done if [[ $pos -lt 0 ]]; then for ((i = 0; i < nruns; i++)); do is_ancestor "${RUN_TARGET[i]}" "$peeled" && pos=$i done fi [[ $pos -gt $anchor ]] && anchor=$pos done < <(git for-each-ref --format='%(refname:strip=2)' "refs/tags/$p-v*") if [[ $anchor -lt 0 ]]; then first=$((nruns - 1)); else first=$anchor; fi 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" 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" 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