GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fork: release workflow for v<upstream>-fork.N on GitHub-hosted runner… · scuttletoby/t3code@ee69d98

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • .github
    • scripts
      • fork-release-workflow.test.py
      • fork-release.sh
      • fork-release.test.sh
    • workflows
      • fork-release.yml
      • fork-tests.yml
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎.github/scripts/fork-release-workflow.test.py‎

Copy file name to clipboard
+142Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
"""Checks the shape of .github/workflows/fork-release.yml that its guards rely on.
2+
3+
python3 .github/scripts/fork-release-workflow.test.py [path/to/fork-release.yml]
4+
5+
Needs PyYAML. Each check prints ok/FAIL; any FAIL exits 1.
6+
"""
7+
8+
import pathlib
9+
import re
10+
import sys
11+
12+
import yaml
13+
14+
root = pathlib.Path(__file__).resolve().parents[2]
15+
path = pathlib.Path(sys.argv[1]) if len(sys.argv) > 1 else root / ".github/workflows/fork-release.yml"
16+
text = path.read_text()
17+
wf = yaml.safe_load(text)
18+
desktop = yaml.safe_load((root / ".github/workflows/release-desktop.yml").read_text())
19+
jobs = wf["jobs"]
20+
failures = []
21+
22+
23+
def check(name, ok, detail=""):
24+
print(("ok " if ok else "FAIL ") + name + ("" if ok or not detail else f"\n | {detail}"))
25+
if not ok:
26+
failures.append(name)
27+
28+
29+
def steps(job):
30+
return job.get("steps", [])
31+
32+
33+
def all_steps():
34+
for job_id, job in jobs.items():
35+
for step in steps(job):
36+
yield job_id, step
37+
38+
39+
# Actions run by commit, so a moved tag cannot change what runs (the release action holds a write
40+
# token). Local actions and workflows are part of this repository.
41+
unpinned = []
42+
for line in text.splitlines():
43+
m = re.match(r"\s*(?:-\s*)?uses:\s*(\S+)(.*)$", line)
44+
if not m or m.group(1).startswith("./"):
45+
continue
46+
if not re.fullmatch(r"[\w.-]+/[\w./-]+@[0-9a-f]{40}", m.group(1)) or not re.match(r"\s*#\s*v\d", m.group(2)):
47+
unpinned.append(m.group(1))
48+
check("external actions are pinned by commit SHA with a version comment", not unpinned, ", ".join(unpinned))
49+
50+
# Named secrets only: the signing secrets release-desktop.yml declares, nothing inherited.
51+
declared = set(desktop[True]["workflow_call"]["secrets"])
52+
inherit = [j for j, job in jobs.items() if job.get("secrets") == "inherit"]
53+
check("no job passes secrets: inherit", not inherit, ", ".join(inherit))
54+
wrong = []
55+
for job_id, job in jobs.items():
56+
if job.get("uses") == "./.github/workflows/release-desktop.yml":
57+
passed = job.get("secrets")
58+
if not isinstance(passed, dict) or set(passed) != declared or any(
59+
v != "${{ secrets.%s }}" % k for k, v in passed.items()
60+
):
61+
wrong.append(job_id)
62+
check("release-desktop.yml gets exactly the secrets it declares", not wrong, ", ".join(wrong))
63+
check("FORK_PUSH_TOKEN appears nowhere", "FORK_PUSH_TOKEN" not in text)
64+
65+
bad = [j for j, s in all_steps() if str(s.get("uses", "")).startswith("actions/checkout@")
66+
and (s.get("with") or {}).get("persist-credentials") is not False]
67+
check("every checkout sets persist-credentials: false", not bad, ", ".join(bad))
68+
69+
release_steps = [(j, s) for j, s in all_steps() if str(s.get("uses", "")).startswith("softprops/action-gh-release@")]
70+
check("one release-action step", len(release_steps) == 1)
71+
check("the release action fails on unmatched files",
72+
all((s.get("with") or {}).get("fail_on_unmatched_files") is True for _, s in release_steps))
73+
74+
# The write token: only the publish job has it, and only its three release-writing steps use it.
75+
write_jobs = [j for j, job in jobs.items() if (job.get("permissions") or {}).get("contents") == "write"]
76+
check("only the publish job has contents: write", write_jobs == ["publish"], ", ".join(write_jobs))
77+
package_code = re.compile(r"(^|[\s;&|(])(vp|node|npm|npx|pnpm|bun)\s")
78+
for job_id in write_jobs:
79+
job_steps = steps(jobs[job_id])
80+
runs_packages = [s.get("name") for s in job_steps
81+
if str(s.get("uses", "")).startswith("./") or package_code.search(str(s.get("run", "")))]
82+
check(f"{job_id}: runs no package code", not runs_packages, ", ".join(map(str, runs_packages)))
83+
token_steps = [s for s in job_steps if "github.token" in yaml.safe_dump(s) or "secrets." in yaml.safe_dump(s)
84+
or str(s.get("uses", "")).startswith("softprops/")]
85+
allowed = [s for s in token_steps if str(s.get("uses", "")).startswith("softprops/")
86+
or re.fullmatch(r"bash \.github/scripts/fork-release\.sh (remove-drafts|publish) .*", str(s.get("run", "")).strip())]
87+
check(f"{job_id}: the token reaches only the remove-drafts, create and publish steps",
88+
len(token_steps) == len(allowed) == 3, ", ".join(str(s.get("name")) for s in token_steps))
89+
90+
def index(pred):
91+
return next((i for i, s in enumerate(job_steps) if pred(s)), -1)
92+
93+
remove = index(lambda s: "fork-release.sh remove-drafts" in str(s.get("run", "")))
94+
create = index(lambda s: str(s.get("uses", "")).startswith("softprops/"))
95+
publish = index(lambda s: "fork-release.sh publish" in str(s.get("run", "")))
96+
check(f"{job_id}: refuse/remove drafts, then create the draft, then publish it",
97+
-1 < remove < create < publish)
98+
if create >= 0 and publish >= 0:
99+
check(f"{job_id}: publishes the draft it created, by id",
100+
job_steps[create].get("id") == "draft"
101+
and "steps.draft.outputs.id" in yaml.safe_dump(job_steps[publish]))
102+
103+
# Shell steps fail on any error in a pipeline.
104+
lax = []
105+
for job_id, s in all_steps():
106+
run = s.get("run")
107+
if run is None:
108+
continue
109+
lines = [l for l in run.strip().splitlines() if l.strip() and not l.strip().startswith("#")]
110+
if s.get("shell") != "bash" or (len(lines) > 1 and lines[0].strip() != "set -euo pipefail"):
111+
lax.append(f"{job_id}/{s.get('name')}")
112+
check("run steps use bash and multi-line ones start with set -euo pipefail", not lax, "; ".join(lax))
113+
114+
runs = "\n".join(str(s.get("run", "")) for _, s in all_steps())
115+
check("preflight resolves the version through the guard script",
116+
"fork-release.sh resolve" in "\n".join(str(s.get("run", "")) for s in steps(jobs["preflight"])))
117+
check("preflight runs the guard tests", "fork-release.test.sh" in runs)
118+
check("the CLI archives are checked for the release repository", "fork-release.sh check-archives release-assets" in runs)
119+
check("preflight runs this shape test", "fork-release-workflow.test.py" in
120+
"\n".join(str(s.get("run", "")) for s in steps(jobs["preflight"])))
121+
122+
# The server bundle check skips dist/client, which names this repository on every Actions build.
123+
bundle_steps = [s for s in steps(jobs["build_bundle"]) if "apps/server/dist" in str(s.get("run", ""))]
124+
check("the server bundle is checked through check-bundle (without dist/client)",
125+
[str(s.get("run", "")).strip() for s in bundle_steps]
126+
== ["bash .github/scripts/fork-release.sh check-bundle apps/server/dist"])
127+
128+
# The build names this fork through the setting scripts/lib/release-repository.ts reads.
129+
build = next((s for s in steps(jobs["build_bundle"]) if s.get("name") == "Build JS bundle"), {})
130+
check("the build sets T3CODE_DESKTOP_UPDATE_REPOSITORY to this repository",
131+
(build.get("env") or {}).get("T3CODE_DESKTOP_UPDATE_REPOSITORY") == "${{ github.repository }}")
132+
check("the former name T3CODE_RELEASE_REPOSITORY appears nowhere", "T3CODE_RELEASE_REPOSITORY" not in text)
133+
134+
# The write job's guard script comes from the workflow's own commit, not the commit being built.
135+
guard = [s for s in steps(jobs["publish"]) if str(s.get("uses", "")).startswith("actions/checkout@")]
136+
check("publish checks out its guard script at github.workflow_sha",
137+
len(guard) == 1 and (guard[0].get("with") or {}).get("ref") == "${{ github.workflow_sha }}")
138+
139+
if failures:
140+
print(f"{len(failures)} failed")
141+
sys.exit(1)
142+
print("all passed")
Collapse file

‎.github/scripts/fork-release.sh‎

Copy file name to clipboard
+233Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
#!/usr/bin/env bash
2+
# The guards of fork-release.yml, one subcommand each, so they can be tested without a run
3+
# (fork-release.test.sh). Every refusal exits non-zero with a ::error:: line; nothing falls back.
4+
#
5+
# resolve Preflight: picks base tag, version and tag for HEAD (key=value lines).
6+
# remove-drafts TAG Refuses a published TAG, then deletes drafts with TAG left by earlier runs.
7+
# publish ID TAG VERSION Refuses a published TAG or a published release that is not below
8+
# VERSION, then publishes draft ID as the latest release.
9+
# check-bundle DIR The server bundle DIR (apps/server/dist) outside DIR/client must name
10+
# REPOSITORY as its release repository.
11+
# check-archives DIR The `t3` program of every CLI archive in DIR must name REPOSITORY.
12+
#
13+
# Environment: REPOSITORY (owner/name of this fork; GITHUB_REPOSITORY in a run), UPSTREAM
14+
# (owner/name, resolve looks it up), UPSTREAM_URL (git URL of upstream, default GitHub), ORIGIN
15+
# (git remote or URL of this fork, default origin). Output goes to $GITHUB_OUTPUT, else stdout.
16+
set -euo pipefail
17+
18+
REPOSITORY="${REPOSITORY:-${GITHUB_REPOSITORY:?REPOSITORY or GITHUB_REPOSITORY}}"
19+
ORIGIN="${ORIGIN:-origin}"
20+
OUTPUT="${GITHUB_OUTPUT:-/dev/stdout}"
21+
22+
die() {
23+
printf '::error::%s\n' "$*" >&2
24+
exit 1
25+
}
26+
27+
stable_version_re='^v[0-9]+\.[0-9]+\.[0-9]+$'
28+
fork_version_re='^v?[0-9]+\.[0-9]+\.[0-9]+-fork\.[0-9]+$'
29+
30+
# version_gt A B: A sorts above B. Takes X.Y.Z or X.Y.Z-fork.N (leading v allowed). A fork
31+
# release of X.Y.Z sorts above X.Y.Z itself here, which is what this fork's ordering needs.
32+
version_gt() {
33+
local a="${1#v}" b="${2#v}" i
34+
local -a x y
35+
IFS=. read -r -a x <<< "${a/-fork./.}"
36+
IFS=. read -r -a y <<< "${b/-fork./.}"
37+
for i in 0 1 2 3; do
38+
if (( 10#${x[i]:-0} != 10#${y[i]:-0} )); then
39+
(( 10#${x[i]:-0} > 10#${y[i]:-0} ))
40+
return
41+
fi
42+
done
43+
return 1
44+
}
45+
46+
# Prints the releases of this fork through a jq filter; a failed listing stops everything.
47+
releases() {
48+
gh api "repos/$REPOSITORY/releases" --paginate --jq "$1" \
49+
|| die "Could not list the releases of $REPOSITORY; nothing was changed."
50+
}
51+
52+
# A published (non-draft) release or a tag with this name means the version is taken: "Re-run failed
53+
# jobs" reuses the preflight's version, and publishing again would replace a live release's files.
54+
refuse_published() {
55+
local tag="$1" published
56+
if git ls-remote --exit-code --tags "$ORIGIN" "refs/tags/$tag" > /dev/null; then
57+
die "Tag $tag already exists, so $tag is published or being published. Start a new run (Re-run all jobs) for the next number; nothing was changed."
58+
else
59+
# 2 means no such ref; anything else is a failed lookup, which must not read as "free".
60+
[[ $? == 2 ]] || die "Could not list the tags of $ORIGIN."
61+
fi
62+
published="$(releases ".[] | select((.draft | not) and .tag_name == \"$tag\") | .id")"
63+
if [[ -n "$published" ]]; then
64+
die "A published release ($published) already has tag $tag. Start a new run (Re-run all jobs); nothing was changed."
65+
fi
66+
}
67+
68+
# The server's updater (packages/shared/src/cliRelease.ts newestCliReleaseVersion) takes the
69+
# newest-created non-draft release on its channel, not the highest version. So every new release
70+
# must be above every published one, or `t3 update` would see a downgrade and stall until a higher
71+
# build exists. Stable channel = any vX.Y.Z[-...] tag except -nightly./-preview. builds.
72+
refuse_older() {
73+
local version="$1" other published
74+
published="$(releases '.[] | select(.draft | not) | .tag_name')"
75+
for other in $published; do
76+
[[ "$other" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-.*)?$ ]] || continue
77+
[[ ! "$other" =~ -(nightly|preview)\. ]] || continue
78+
[[ "$other" =~ $stable_version_re || "$other" =~ $fork_version_re ]] \
79+
|| die "Published release $other is on the server's stable channel but has no X.Y.Z or X.Y.Z-fork.N version, so $version cannot be ordered against it; nothing was changed."
80+
version_gt "$version" "$other" \
81+
|| die "$other is published and not below $version. The server updates to the newest-created release, so publishing $version would show every server a downgrade. Build a newer upstream release instead; to go back, install the older release with t3 update --version X --allow-downgrade. Nothing was changed."
82+
done
83+
}
84+
85+
cmd_resolve() {
86+
local upstream="${UPSTREAM:-}"
87+
if [[ -z "$upstream" ]]; then
88+
upstream="$(gh api "repos/$REPOSITORY" --jq '.parent.full_name // empty')"
89+
[[ -n "$upstream" ]] || die "$REPOSITORY is not a fork, so there is no upstream release to build on."
90+
fi
91+
local url="${UPSTREAM_URL:-https://github.com/$upstream.git}"
92+
local head
93+
head="$(git rev-parse HEAD)"
94+
95+
# Read-only fetch of upstream's tags and default branch into refs this run alone uses.
96+
git fetch --quiet --no-tags "$url" "+refs/tags/v*:refs/upstream-tags/v*" "+HEAD:refs/upstream-head"
97+
98+
# Lists are read into variables first: a failure inside <(...) would go unnoticed.
99+
local refs tag
100+
local -a contained=()
101+
refs="$(git for-each-ref --format='%(refname:strip=2)' refs/upstream-tags)"
102+
for tag in $(grep -E "$stable_version_re" <<< "$refs" | sort -rV || true); do
103+
if git merge-base --is-ancestor "refs/upstream-tags/$tag^{commit}" HEAD; then
104+
contained+=("$tag")
105+
fi
106+
done
107+
(( ${#contained[@]} > 0 )) || die "$head contains no stable $upstream release tag."
108+
local base_tag="${contained[0]}"
109+
local base
110+
base="$(git rev-parse "refs/upstream-tags/$base_tag^{commit}")"
111+
112+
# The base must be the newest stable tag in the series' history, not just the highest name: a
113+
# stray tag on an old commit (say v1.0.0) would otherwise outrank every later real release.
114+
for tag in "${contained[@]:1}"; do
115+
git merge-base --is-ancestor "refs/upstream-tags/$tag^{commit}" "$base" \
116+
|| die "$base_tag sorts highest but is not the newest stable $upstream tag in this history ($tag is not part of it). Delete or fix the stray tag; nothing was built."
117+
done
118+
119+
# Upstream's own ordering: never above the release upstream marks latest.
120+
local upstream_latest
121+
upstream_latest="$(gh api "repos/$upstream/releases/latest" --jq '.tag_name')"
122+
[[ "$upstream_latest" =~ $stable_version_re ]] \
123+
|| die "$upstream's latest release is '$upstream_latest', not a stable vX.Y.Z tag."
124+
if version_gt "$base_tag" "$upstream_latest"; then
125+
die "$base_tag sorts above $upstream's latest release $upstream_latest. Only released upstream versions are built."
126+
fi
127+
128+
# Releases only: every commit after the base tag must be the fork's own. Upstream commits there
129+
# are unreleased upstream code (for example a branch that still equals upstream's default branch).
130+
local total own
131+
total="$(git rev-list --count "$base..HEAD")"
132+
own="$(git rev-list --count "$base..HEAD" --not refs/upstream-head)"
133+
if [[ "$total" != "$own" ]]; then
134+
die "$head holds $((total - own)) unreleased $upstream commits after $base_tag. Build a branch of $base_tag plus the fork's own commits."
135+
fi
136+
137+
local version="${base_tag#v}" last
138+
last="$(git ls-remote --tags --refs "$ORIGIN" "v$version-fork.*" \
139+
| sed -n "s|.*refs/tags/v$version-fork\.\([0-9]\+\)$|\1|p" | sort -n | tail -n1)"
140+
version="$version-fork.$(( ${last:-0} + 1 ))"
141+
refuse_older "$version"
142+
{
143+
echo "ref=$head"
144+
echo "upstream=$upstream"
145+
echo "base_tag=$base_tag"
146+
echo "version=$version"
147+
echo "tag=v$version"
148+
} >> "$OUTPUT"
149+
echo "Building $version from $(git rev-parse --short HEAD) on $upstream $base_tag." \
150+
| tee -a "${GITHUB_STEP_SUMMARY:-/dev/null}" >&2
151+
}
152+
153+
cmd_remove_drafts() {
154+
local tag="${1:?tag}" id
155+
refuse_published "$tag"
156+
local ids
157+
ids="$(releases ".[] | select(.draft and .tag_name == \"$tag\") | .id")"
158+
for id in $ids; do
159+
gh api -X DELETE "repos/$REPOSITORY/releases/$id" > /dev/null
160+
echo "Removed leftover draft $id for $tag."
161+
done
162+
[[ -n "$ids" ]] || echo "No leftover draft for $tag."
163+
}
164+
165+
cmd_publish() {
166+
local id="${1:?release id}" tag="${2:?tag}" version="${3:?version}"
167+
[[ "$version" =~ $fork_version_re ]] || die "'$version' is not a fork version."
168+
refuse_published "$tag"
169+
# Checked again here: a release published since preflight must not end up above this one. After
170+
# this check VERSION is the highest release, so the server and the desktop updater agree on it.
171+
refuse_older "$version"
172+
gh api -X PATCH "repos/$REPOSITORY/releases/$id" -F draft=false -f make_latest=true > /dev/null
173+
echo "Published $tag (latest: true)."
174+
{
175+
echo "published=true"
176+
echo "latest=true"
177+
} >> "$OUTPUT"
178+
}
179+
180+
# The web client (DIR/client) names this repository on every Actions build anyway: upstream's
181+
# apps/web/vite.config.ts bakes GITHUB_REPOSITORY into it. Only the server code counts here.
182+
cmd_check_bundle() {
183+
local dir="${1:?directory}" file files
184+
[[ -d "$dir" ]] || die "No server bundle at $dir."
185+
files="$(find "$dir" -path "$dir/client" -prune -o -type f -print)"
186+
[[ -n "$files" ]] || die "The server bundle $dir holds no files outside client/."
187+
while IFS= read -r file; do
188+
if grep -qaF "\"$REPOSITORY\"" "$file"; then
189+
echo "The server bundle names $REPOSITORY (${file#"$dir"/})."
190+
return 0
191+
fi
192+
done <<< "$files"
193+
die "The server bundle $dir (outside client/) does not name $REPOSITORY as its release repository, so it would update from elsewhere."
194+
}
195+
196+
cmd_check_archives() {
197+
local dir="${1:?directory}" archive work name stem program found=0
198+
shopt -s nullglob
199+
for archive in "$dir"/t3-*.tar.gz "$dir"/t3-*.zip; do
200+
found=1
201+
work="$(mktemp -d)"
202+
case "$archive" in
203+
*.tar.gz) tar -xzf "$archive" -C "$work" ;;
204+
*.zip) python3 -I -m zipfile -e "$archive" "$work" ;;
205+
esac
206+
# Only the `t3` program at <stem>/ (scripts/build-cli-archive.ts): it bundles the server again,
207+
# and its updater is what counts. client/ names this repository on every Actions build anyway.
208+
name="$(basename "$archive")"
209+
stem="${name%.tar.gz}"
210+
stem="${stem%.zip}"
211+
program="$work/$stem/t3"
212+
[[ "$archive" != *.zip ]] || program="$work/$stem/t3.exe"
213+
[[ -f "$program" ]] \
214+
|| die "$name has no ${program#"$work"/}, so the server program in it cannot be checked."
215+
grep -qaF "\"$REPOSITORY\"" "$program" \
216+
|| die "${program#"$work"/} in $name does not name $REPOSITORY as its release repository, so it would update from elsewhere."
217+
rm -rf "$work"
218+
echo "${program#"$work"/} in $name names $REPOSITORY."
219+
done
220+
(( found )) || die "No CLI archive in $dir."
221+
}
222+
223+
command="${1:-}"
224+
shift || true
225+
case "$command" in
226+
resolve) cmd_resolve "$@" ;;
227+
remove-drafts) cmd_remove_drafts "$@" ;;
228+
publish) cmd_publish "$@" ;;
229+
check-bundle) cmd_check_bundle "$@" ;;
230+
check-archives) cmd_check_archives "$@" ;;
231+
version-gt) version_gt "$@" ;;
232+
*) die "usage: $0 resolve | remove-drafts TAG | publish ID TAG VERSION | check-bundle DIR | check-archives DIR" ;;
233+
esac

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.