blueprint-shared-templates 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,272 @@
1
+ #!/usr/bin/env bash
2
+ # Release the executables of the units whose publish.to in release-policy.json is binary (blueprint-shared.publishing.binary-release).
3
+ # Each unit is a Go program: it is cross-compiled for every platform the policy lists, packed, and released with its checksum file
4
+ # to the public release repository, and at a GA version the Homebrew formula in that repository is updated.
5
+ #
6
+ # build CGO_ENABLED=0 go build -trimpath -buildvcs=false for each <os>/<arch> of publish.platforms, in the unit directory.
7
+ # -buildvcs=false keeps the commit and its time out of the executable, so one source gives the same bytes at any commit
8
+ # archive <command>-<version>-<os>-<arch>.tar.gz, one file in it: the executable <command>. The archive is the same bytes for the
9
+ # same executable (fixed mtime, owner and gzip header), so a rerun can tell a version that changed from one that did not
10
+ # checksum <command>-<version>.sha256, sha256sum format: "<sha256> <archive name>" for every archive
11
+ # version the unit has a version.txt and it must equal the version of .release-please-manifest.json. After the build the
12
+ # executable of the runner platform runs with --version and must print that version
13
+ # release tag <ComponentName>/v<version> in the release repository (the same string as the unit tag of the source
14
+ # repository), with the archives and the checksum file. A prerelease version is a GitHub prerelease and the formula
15
+ # is not touched. A GA version updates Formula/<command>.rb on main with a fast-forward push, never forced
16
+ # formula in on_macos and on_linux, each on_arm and on_intel block holds a url and the sha256 of the archive; a comment lists
17
+ # the platforms. Only darwin and linux on amd64 and arm64 can be in a formula; any other platform is released but left out
18
+ #
19
+ # A rerun is safe:
20
+ # - the release exists and its checksum file is the one just built: nothing is released again
21
+ # - the release exists with another checksum file: refuse, because a published version must not move
22
+ # - the release exists without a checksum file (an upload that did not finish): refuse, a person decides
23
+ # - a GA formula that already says this version is left alone, and one that says a higher version is not changed
24
+ #
25
+ # usage: binary-units.sh [--dry-run] <path>... units whose publish.to is not binary are skipped
26
+ # --dry-run print the release (tag, archives, formula) and write nothing: nothing is built, released or pushed
27
+ # BINARY_RELEASE_REPOSITORY the name of the release repository without the owner (binaryReleaseRepository of the organization values)
28
+ # BINARY_RELEASE_OWNER owner of that repository (default: the owner of GITHUB_REPOSITORY)
29
+ # BINARY_RELEASE_REMOTE full remote URL or path of the release repository for git (tests use a local bare repository)
30
+ # BINARY_RELEASE_TOKEN GitHub App token with contents: write on the release repository only; sent as an HTTP header that git reads
31
+ # from its environment (GIT_CONFIG_*), never in a URL or in an argument (default for gh: GH_TOKEN)
32
+ # BINARY_OUT where the archives are built (default tmp/binary)
33
+ set -euo pipefail
34
+ source "$(dirname "$0")/../lib/common.sh"
35
+ cd "$REPO_ROOT"
36
+
37
+ dry=0
38
+ if [[ "${1:-}" == --dry-run ]]; then dry=1; shift; fi
39
+ [[ $# -ge 1 ]] || die "usage: binary-units.sh [--dry-run] <path>..."
40
+
41
+ unit_tag() { printf '%s/v%s\n' "$(unit_component "$1")" "$2"; } # the unit tag, <ComponentName>/v<version>
42
+
43
+ # version_gt <a> <b> → success when version a is above b (X.Y.Z or X.Y.Z-<alpha|beta|rc>.N)
44
+ version_gt() {
45
+ local a="$1" b="$2" sa="${1%%-*}" sb="${2%%-*}"
46
+ [[ "$a" != "$b" ]] || return 1
47
+ if [[ "$sa" != "$sb" ]]; then
48
+ [[ "$(printf '%s\n%s\n' "$sa" "$sb" | sort -V | tail -1)" == "$sa" ]]
49
+ return
50
+ fi
51
+ [[ "$a" != "$sa" ]] || return 0 # a is the release, b a pre-release of it
52
+ [[ "$b" != "$sb" ]] || return 1
53
+ [[ "$(printf '%s\n%s\n' "${a#*-}" "${b#*-}" | sort -V | tail -1)" == "${a#*-}" ]]
54
+ }
55
+
56
+ release_token() { printf '%s\n' "${BINARY_RELEASE_TOKEN:-${GH_TOKEN:-}}"; }
57
+
58
+ # gh against the release repository, with its token
59
+ ghr() { GH_TOKEN="$(release_token)" gh "$@"; }
60
+ ghr_read() { GH_TOKEN="$(release_token)" read_retry gh "$@"; }
61
+
62
+ # git against the release repository. The token goes to git as an HTTP header set in the environment of that one call (GIT_CONFIG_*),
63
+ # so it is in no argument and no process list shows it
64
+ with_git_auth() { # with_git_auth <command>...
65
+ local t n="${GIT_CONFIG_COUNT:-0}"; t="$(release_token)"
66
+ if [[ -z "$t" ]]; then "$@"; return; fi
67
+ env "GIT_CONFIG_COUNT=$((n + 1))" "GIT_CONFIG_KEY_${n}=http.https://github.com/.extraheader" \
68
+ "GIT_CONFIG_VALUE_${n}=Authorization: Basic $(printf 'x-access-token:%s' "$t" | base64 | tr -d '\n')" "$@"
69
+ }
70
+ rgit() { with_git_auth git "$@"; }
71
+ rgit_push() { # a push that is asked again after a transient error of GitHub, never forced
72
+ with_git_auth node "$RETRY_MJS" push -- git push "$@"
73
+ }
74
+
75
+ release_repo() { # → owner/name of the release repository
76
+ local owner="${BINARY_RELEASE_OWNER:-${GITHUB_REPOSITORY:-}}"
77
+ owner="${owner%%/*}"
78
+ [[ -n "${BINARY_RELEASE_REPOSITORY:-}" ]] || die "組織值 binaryReleaseRepository 沒有填,不知道執行檔要發到哪個倉;有 binary 單元的倉要填它"
79
+ [[ "$BINARY_RELEASE_REPOSITORY" =~ ^[A-Za-z0-9._-]+$ ]] || die "binaryReleaseRepository「${BINARY_RELEASE_REPOSITORY}」只能是倉庫名,不含 owner"
80
+ [[ -n "$owner" ]] || die "不知道發布倉的 owner,請設 GITHUB_REPOSITORY(owner/repo)或 BINARY_RELEASE_OWNER"
81
+ printf '%s/%s\n' "$owner" "$BINARY_RELEASE_REPOSITORY"
82
+ }
83
+
84
+ release_remote() { # → the remote git uses for the release repository
85
+ if [[ -n "${BINARY_RELEASE_REMOTE:-}" ]]; then printf '%s\n' "$BINARY_RELEASE_REMOTE"
86
+ else printf 'https://github.com/%s.git\n' "$(release_repo)"; fi
87
+ }
88
+
89
+ sha256_of() { # sha256_of <file> → the hex digest
90
+ if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi
91
+ }
92
+
93
+ # pack_archive <executable> <command> <archive>: a tar.gz of the one file, the same bytes for the same executable
94
+ pack_archive() {
95
+ python3 - "$@" <<'PY'
96
+ import gzip, io, sys, tarfile
97
+ src, name, dest = sys.argv[1:4]
98
+ data = open(src, "rb").read()
99
+ with open(dest, "wb") as raw:
100
+ with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0, compresslevel=9) as gz:
101
+ with tarfile.open(fileobj=gz, mode="w", format=tarfile.GNU_FORMAT) as tar:
102
+ info = tarfile.TarInfo(name)
103
+ info.size, info.mode, info.mtime, info.uid, info.gid = len(data), 0o755, 0, 0, 0
104
+ tar.addfile(info, io.BytesIO(data))
105
+ PY
106
+ }
107
+
108
+ # the Homebrew blocks of a platform: <os>/<arch> → "on_macos on_arm", or nothing when a formula cannot hold it
109
+ formula_slot() {
110
+ local os arch
111
+ case "${1%%/*}" in darwin) os=on_macos ;; linux) os=on_linux ;; *) return 1 ;; esac
112
+ case "${1#*/}" in arm64) arch=on_arm ;; amd64) arch=on_intel ;; *) return 1 ;; esac
113
+ printf '%s %s\n' "$os" "$arch"
114
+ }
115
+
116
+ # formula_text <command> <description> <version> <tag> <repo> <checksum file> <platform>...
117
+ formula_text() {
118
+ local cmd="$1" desc="$2" ver="$3" tag="$4" repo="$5" sums="$6" cls="" part pl slot os arch name sha listed=()
119
+ shift 6
120
+ for part in $(printf '%s' "$cmd" | tr '._-' ' '); do cls+="$(tr '[:lower:]' '[:upper:]' <<<"${part:0:1}")${part:1}"; done
121
+ for pl in "$@"; do formula_slot "$pl" >/dev/null && listed+=("$pl"); done
122
+ (( ${#listed[@]} )) || die "${cmd}:平台 $* 裡沒有 formula 放得下的(darwin 或 linux,amd64 或 arm64)"
123
+ printf '# Supported platforms: %s\n' "$(IFS=,; printf '%s' "${listed[*]}" | sed 's/,/, /g')"
124
+ printf 'class %s < Formula\n desc "%s"\n homepage "https://github.com/%s"\n version "%s"\n' "$cls" "${desc//\"/\\\"}" "$repo" "$ver"
125
+ for os in on_macos on_linux; do
126
+ local opened=0
127
+ for arch in on_arm on_intel; do
128
+ for pl in "${listed[@]}"; do
129
+ slot="$(formula_slot "$pl")"
130
+ [[ "$slot" == "$os $arch" ]] || continue
131
+ (( opened )) || { printf '\n %s do\n' "$os"; opened=1; }
132
+ name="${cmd}-${ver}-${pl%%/*}-${pl#*/}.tar.gz"
133
+ sha="$(awk -v n="$name" '$2 == n { print $1 }' "$sums")"
134
+ [[ -n "$sha" ]] || die "$sums 沒有 $name 的一行"
135
+ printf ' %s do\n url "https://github.com/%s/releases/download/%s/%s"\n sha256 "%s"\n end\n' "$arch" "$repo" "$tag" "$name" "$sha"
136
+ done
137
+ done
138
+ (( ! opened )) || printf ' end\n'
139
+ done
140
+ printf '\n def install\n bin.install "%s"\n end\n\n test do\n assert_match version.to_s, shell_output("#{bin}/%s --version")\n end\nend\n' "$cmd" "$cmd"
141
+ }
142
+
143
+ summary() { [[ -z "${GITHUB_STEP_SUMMARY:-}" ]] || printf '%s\n' "- $*" >> "$GITHUB_STEP_SUMMARY"; }
144
+
145
+ # update_formula <command> <description> <version> <tag> <repo> <checksum file> <source tag> <platform>...
146
+ update_formula() {
147
+ local cmd="$1" desc="$2" ver="$3" tag="$4" repo="$5" sums="$6" ref="$7" remote work text have cur ad
148
+ shift 7
149
+ remote="$(release_remote)"
150
+ work="$(mktemp -d "${TMPDIR:-/tmp}/formula.XXXXXX")"
151
+ text="$(formula_text "$cmd" "$desc" "$ver" "$tag" "$repo" "$sums" "$@")"
152
+ [[ -n "$(rgit ls-remote "$remote" refs/heads/main | cut -f1)" ]] || { rm -rf "$work"; die "發布倉 ${repo} 沒有 main,formula 沒有地方推;先建好有 main 的發布倉"; }
153
+ rgit clone -q --no-tags --branch main "$remote" "$work"
154
+ if [[ -f "$work/Formula/$cmd.rb" ]]; then
155
+ cur="$(sed -n 's/^ version "\(.*\)"$/\1/p' "$work/Formula/$cmd.rb" | head -1)"
156
+ if [[ -n "$cur" ]] && version_gt "$cur" "$ver"; then
157
+ info "formula $cmd 已是更高的版本 ${cur},不改成 $ver"; rm -rf "$work"; return 0
158
+ fi
159
+ have="$(cat "$work/Formula/$cmd.rb")"
160
+ if [[ "$have" == "$text" ]]; then info "formula $cmd 已是 ${ver},沒有要推的"; rm -rf "$work"; return 0; fi
161
+ fi
162
+ mkdir -p "$work/Formula"
163
+ printf '%s\n' "$text" > "$work/Formula/$cmd.rb"
164
+ # the commit is made by the bot, not by the author of the source repository: that one may be private and its address would be public here
165
+ ad="$(git log -1 --format='%aI' "$ref")"
166
+ local bot_name="github-actions[bot]" bot_email="41898283+github-actions[bot]@users.noreply.github.com"
167
+ GIT_AUTHOR_NAME="$bot_name" GIT_AUTHOR_EMAIL="$bot_email" GIT_AUTHOR_DATE="$ad" GIT_COMMITTER_NAME="$bot_name" GIT_COMMITTER_EMAIL="$bot_email" GIT_COMMITTER_DATE="$ad" \
168
+ git -C "$work" add "Formula/$cmd.rb"
169
+ GIT_AUTHOR_NAME="$bot_name" GIT_AUTHOR_EMAIL="$bot_email" GIT_AUTHOR_DATE="$ad" GIT_COMMITTER_NAME="$bot_name" GIT_COMMITTER_EMAIL="$bot_email" GIT_COMMITTER_DATE="$ad" \
170
+ git -C "$work" commit -q --no-gpg-sign -m "$cmd $ver" -m "Source: $ref"
171
+ # a fast-forward only: a push that is not one is refused by the remote, and the script stops with its error
172
+ ( cd "$work" && rgit_push origin HEAD:refs/heads/main )
173
+ rm -rf "$work"
174
+ log "formula $cmd → $ver 已推到 ${repo} 的 main"
175
+ summary "formula \`$cmd\` → \`$ver\`(${repo})"
176
+ }
177
+
178
+ binary_unit() { # binary_unit <path>
179
+ local p="${1%/}" comp ver stage cmd desc tag repo ref work out sums host plat os arch bin archive pre=0 title sum_have
180
+ local -a platforms=() archives=()
181
+ comp="$(unit_component "$p")"
182
+ if [[ "$(policy_unit_publish_to "$comp")" != binary ]]; then info "$p: publish.to is not binary, skipped"; return 0; fi
183
+ [[ -f "$p/go.mod" ]] || die "${p}:publish.to 是 binary,但單元沒有 go.mod;這一版的執行檔發布只支援 Go"
184
+ jq -e --arg p "$p" '.packages | has($p)' "$CONFIG" >/dev/null || die "unexpected package path: $p (not a key of packages in $CONFIG)"
185
+ ver="$(manifest_version "$p")"
186
+ [[ -n "$ver" ]] || die "$p 不在 $MANIFEST"
187
+ stage="$(version_stage "$ver")" || die "$p: version \"$ver\" is not X.Y.Z or X.Y.Z-<alpha|beta|rc>.N"
188
+ [[ "$stage" == ga ]] || pre=1
189
+ cmd="$(policy_unit_publish_field "$comp" command)"
190
+ desc="$(policy_unit_publish_field "$comp" description)"
191
+ mapfile -t platforms < <(policy_unit_publish_field "$comp" platforms)
192
+ [[ -n "$cmd" && -n "$desc" ]] || die "${p}:政策檔的 units.${comp}.publish 要寫 command 與 description"
193
+ (( ${#platforms[@]} )) || die "${p}:政策檔的 units.${comp}.publish 要寫 platforms"
194
+ for plat in "${platforms[@]}"; do [[ "$plat" =~ ^[a-z0-9]+/[a-z0-9]+$ ]] || die "${p}:平台「${plat}」不是 <os>/<arch>"; done
195
+ [[ -f "$p/version.txt" ]] || die "${p}:執行檔的單元要有 version.txt,放它的版號"
196
+ [[ "$(tr -d '[:space:]' < "$p/version.txt")" == "$ver" ]] \
197
+ || die "${p}:manifest 是 ${ver},但 $p/version.txt 是 $(tr -d '[:space:]' < "$p/version.txt");release-please 沒有更新到這個檔"
198
+ tag="$(unit_tag "$p" "$ver")"
199
+ repo="$(release_repo)"
200
+
201
+ if (( dry )); then
202
+ echo "## $comp ($p $ver)"
203
+ echo "release repo $repo"
204
+ echo "release tag $tag$( (( pre )) && echo ' (prerelease)')"
205
+ for plat in "${platforms[@]}"; do echo "archive ${cmd}-${ver}-${plat%%/*}-${plat#*/}.tar.gz"; done
206
+ echo "checksum ${cmd}-${ver}.sha256"
207
+ if (( pre )); then echo "formula not changed (prerelease)"; else echo "formula Formula/${cmd}.rb"; fi
208
+ echo "dry run: nothing built, released or pushed"
209
+ return 0
210
+ fi
211
+
212
+ ref="$tag"
213
+ git rev-parse -q --verify "refs/tags/$ref^{commit}" >/dev/null 2>&1 || die "release tag $ref does not exist, so $p $ver has not been released"
214
+ command -v go >/dev/null 2>&1 || die "找不到 go:binary job 要先用 actions/setup-go 裝 go.mod 指定的版本"
215
+ work="${BINARY_OUT:-$REPO_ROOT/tmp/binary}/${comp}-${ver}"
216
+ out="$work/out"
217
+ rm -rf "$work"; mkdir -p "$out"
218
+ host="$(go env GOHOSTOS)/$(go env GOHOSTARCH)"
219
+
220
+ for plat in "${platforms[@]}"; do
221
+ os="${plat%%/*}" arch="${plat#*/}"
222
+ mkdir -p "$work/bin/$os-$arch"
223
+ log "build:$cmd $ver for $plat"
224
+ ( cd "$p" && CGO_ENABLED=0 GOOS="$os" GOARCH="$arch" go build -trimpath -buildvcs=false -o "$work/bin/$os-$arch/$cmd" . )
225
+ archive="${cmd}-${ver}-${os}-${arch}.tar.gz"
226
+ pack_archive "$work/bin/$os-$arch/$cmd" "$cmd" "$out/$archive"
227
+ archives+=("$archive")
228
+ done
229
+ sums="$out/${cmd}-${ver}.sha256"
230
+ : > "$sums"
231
+ for archive in "${archives[@]}"; do printf '%s %s\n' "$(sha256_of "$out/$archive")" "$archive" >> "$sums"; done
232
+
233
+ # the executable of the runner platform must say it is this version
234
+ if [[ ! -x "$work/bin/${host%%/*}-${host#*/}/$cmd" ]]; then
235
+ mkdir -p "$work/bin/host"
236
+ ( cd "$p" && CGO_ENABLED=0 GOOS="${host%%/*}" GOARCH="${host#*/}" go build -trimpath -buildvcs=false -o "$work/bin/host/$cmd" . )
237
+ bin="$work/bin/host/$cmd"
238
+ else
239
+ bin="$work/bin/${host%%/*}-${host#*/}/$cmd"
240
+ fi
241
+ sum_have="$("$bin" --version 2>&1)" || die "$cmd --version 在 ${host} 失敗:$sum_have"
242
+ [[ "$sum_have" == *"$ver"* ]] || die "$cmd --version 印的是「${sum_have}」,沒有版號 ${ver}:版號要從 version.txt 進到執行檔裡"
243
+
244
+ # what the release repository has now
245
+ local view rc=0 existing
246
+ view="$(ghr_read release view "$tag" --repo "$repo" 2>&1)" || rc=$?
247
+ if (( rc == 0 )); then
248
+ existing="$work/existing"; mkdir -p "$existing"
249
+ ghr_read release download "$tag" --repo "$repo" --pattern "${cmd}-${ver}.sha256" --dir "$existing" >/dev/null 2>&1 || true
250
+ [[ -s "$existing/${cmd}-${ver}.sha256" ]] || die "$repo 已有 release ${tag},但沒有 ${cmd}-${ver}.sha256:上傳沒有做完,請使用者決定怎麼補,不要覆蓋已發布的檔"
251
+ cmp -s "$existing/${cmd}-${ver}.sha256" "$sums" \
252
+ || die "$repo 的 release $tag 已有 ${cmd}-${ver}.sha256,但內容和這次建置的不同;已發布的版本不能動,請使用者決定,改發下一個版號"
253
+ echo "$cmd $tag is already released in $repo, nothing to release"
254
+ else
255
+ [[ "$view" == *"release not found"* ]] || die "查 $repo 的 release $tag 失敗:$view"
256
+ title="$comp $ver"
257
+ local -a flags=()
258
+ (( ! pre )) || flags+=(--prerelease)
259
+ log "release:$tag → ${repo}(${#archives[@]} 個壓縮檔與 checksum)"
260
+ ghr release create "$tag" --repo "$repo" --title "$title" --notes "Source: $ref" --target main ${flags[@]+"${flags[@]}"} \
261
+ "${archives[@]/#/$out/}" "$sums"
262
+ summary "執行檔 \`$cmd $ver\` → \`$repo\` release \`$tag\`$( (( pre )) && echo '(prerelease)')"
263
+ fi
264
+
265
+ if (( pre )); then
266
+ info "預發布版本,不更新 formula"
267
+ else
268
+ update_formula "$cmd" "$desc" "$ver" "$tag" "$repo" "$sums" "$ref" "${platforms[@]}"
269
+ fi
270
+ }
271
+
272
+ for p in "$@"; do binary_unit "$p"; done
@@ -0,0 +1,171 @@
1
+ #!/usr/bin/env bash
2
+ # Push the container images of the units whose publish.to in release-policy.json is image (blueprint-shared.publishing.container-image)
3
+ # and attach each digest to the Release of the unit tag in this repository.
4
+ #
5
+ # image ghcr.io/<owner>/<ComponentName>:<version>, one tag per version and never latest. A prerelease version is pushed too,
6
+ # with its full version as the tag (1.2.0-rc.1)
7
+ # build docker buildx build with the Dockerfile in the unit directory (the build context), for every <os>/<arch> of
8
+ # publish.platforms, in one command. The Dockerfile compiles on the build platform (FROM --platform=$BUILDPLATFORM)
9
+ # and does not run under emulation
10
+ # digest <ComponentName>-<version>.digest, one line "sha256:...", an asset of the Release of the unit tag
11
+ # (<ComponentName>/v<version>) in this repository. The digest is also written to the job summary
12
+ # login docker login ghcr.io with the token of the job (GITHUB_TOKEN, packages: write). DOCKER_CONFIG is a new directory
13
+ # in the temporary directory, and it is deleted when the script ends, whatever the exit status. Its config.json lists
14
+ # the cli-plugins directory of the original DOCKER_CONFIG (cliPluginsExtraDirs), so the buildx plugin is still found
15
+ # builder docker buildx create --driver docker-container, named publish-<pid>, used for the build and removed when the script
16
+ # ends, whatever the exit status. A runner needs docker and the buildx plugin (selfHostedRunnerLabels.docker)
17
+ # config the image carries no configuration of the organization: it is mounted at deployment
18
+ #
19
+ # A rerun is safe:
20
+ # - the image exists: nothing is built or pushed, and its digest is attached to the Release when the Release has none
21
+ # - the image exists and the digest on the Release is another one: refuse, because a published version must not move
22
+ # - only an answer of the registry that says the image is not there (not found, MANIFEST_UNKNOWN) counts as "no image"; any other
23
+ # error of the inspect stops the run and is printed
24
+ # - the image does not exist but the Release already has a digest: refuse, a person decides
25
+ #
26
+ # A package is private after its first push. A person makes it public once in GitHub, and that cannot be undone.
27
+ #
28
+ # usage: image-units.sh [--dry-run] <path>... units whose publish.to is not image are skipped
29
+ # --dry-run print the image and the digest file and run nothing: no login, no build, no push
30
+ # IMAGE_OWNER owner of the image (default: the owner of GITHUB_REPOSITORY, in lower case, as ghcr.io requires)
31
+ # IMAGE_REGISTRY the registry host (default ghcr.io)
32
+ # IMAGE_TOKEN the token docker logs in with (default: GITHUB_TOKEN, then GH_TOKEN)
33
+ # IMAGE_ACTOR the user name of the login (default: GITHUB_ACTOR, then x-access-token)
34
+ # GH_TOKEN the token gh reads and writes the Release of this repository with (contents: write)
35
+ # GITHUB_REPOSITORY owner/repo of this repository, the one that has the Release
36
+ # IMAGE_OUT where the digest file and the build metadata are written (default tmp/image)
37
+ set -euo pipefail
38
+ source "$(dirname "$0")/../lib/common.sh"
39
+ cd "$REPO_ROOT"
40
+
41
+ dry=0
42
+ if [[ "${1:-}" == --dry-run ]]; then dry=1; shift; fi
43
+ [[ $# -ge 1 ]] || die "usage: image-units.sh [--dry-run] <path>..."
44
+
45
+ unit_tag() { printf '%s/v%s\n' "$(unit_component "$1")" "$2"; } # the unit tag, <ComponentName>/v<version>
46
+
47
+ summary() { [[ -z "${GITHUB_STEP_SUMMARY:-}" ]] || printf '%s\n' "- $*" >> "$GITHUB_STEP_SUMMARY"; }
48
+
49
+ registry() { printf '%s\n' "${IMAGE_REGISTRY:-ghcr.io}"; }
50
+
51
+ image_owner() {
52
+ local owner="${IMAGE_OWNER:-${GITHUB_REPOSITORY:-}}"
53
+ owner="${owner%%/*}"
54
+ [[ -n "$owner" ]] || die "不知道映像的 owner,請設 GITHUB_REPOSITORY(owner/repo)或 IMAGE_OWNER"
55
+ printf '%s\n' "$owner" | tr '[:upper:]' '[:lower:]'
56
+ }
57
+
58
+ # the DOCKER_CONFIG of this run: a directory of its own that holds the credential of the login, deleted when the script ends
59
+ docker_cfg=""
60
+ builder=""
61
+ cleanup() {
62
+ local rc=$?
63
+ # the builder is removed with the DOCKER_CONFIG it was made in; a failure here does not change the exit status
64
+ [[ -z "$builder" ]] || docker buildx rm "$builder" >/dev/null 2>&1 || true
65
+ [[ -z "$docker_cfg" ]] || rm -rf "$docker_cfg"
66
+ return "$rc"
67
+ }
68
+ trap 'cleanup; report_skipped_external' EXIT
69
+
70
+ docker_login() {
71
+ [[ -z "$docker_cfg" ]] || return 0 # one login for the whole run
72
+ local token="${IMAGE_TOKEN:-${GITHUB_TOKEN:-${GH_TOKEN:-}}}"
73
+ [[ -n "$token" ]] || die "沒有可以登入 $(registry) 的 token:job 的 GITHUB_TOKEN 要帶 packages: write,並設成 IMAGE_TOKEN 或 GITHUB_TOKEN"
74
+ local plugins="${DOCKER_CONFIG:-$HOME/.docker}/cli-plugins"
75
+ docker_cfg="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/docker-config.XXXXXX")"
76
+ # the new directory has no plugins of its own, so it points at the ones of the runner
77
+ if [[ -d "$plugins" ]]; then jq -n --arg d "$plugins" '{cliPluginsExtraDirs: [$d]}' > "$docker_cfg/config.json"; fi
78
+ export DOCKER_CONFIG="$docker_cfg"
79
+ printf '%s' "$token" | docker login "$(registry)" -u "${IMAGE_ACTOR:-${GITHUB_ACTOR:-x-access-token}}" --password-stdin >/dev/null
80
+ }
81
+
82
+ # the digest of an image that is in the registry, or nothing when it is not there
83
+ # Only an answer that says the image is not there is "nothing"; any other error (network, auth, daemon) stops the run
84
+ image_digest() { # image_digest <ref>
85
+ local out rc=0
86
+ out="$(docker buildx imagetools inspect "$1" --format '{{.Manifest.Digest}}' 2>&1)" || rc=$?
87
+ if (( rc == 0 )); then printf '%s\n' "$out"; return 0; fi
88
+ shopt -s nocasematch
89
+ # A package that was never pushed answers NAME_UNKNOWN ("name unknown"), a missing tag answers MANIFEST_UNKNOWN or "not found"
90
+ if [[ "$out" == *"not found"* || "$out" == *MANIFEST_UNKNOWN* || "$out" == *NAME_UNKNOWN* || "$out" == *"name unknown"* ]]; then shopt -u nocasematch; return 0; fi
91
+ shopt -u nocasematch
92
+ die "查 $1 在 $(registry) 的狀態失敗,不當成映像不存在:$out"
93
+ }
94
+
95
+ image_unit() { # image_unit <path>
96
+ local p="${1%/}" comp ver ref tag repo out file="" platforms_csv have attached view rc=0 existing digest
97
+ local -a platforms=()
98
+ comp="$(unit_component "$p")"
99
+ if [[ "$(policy_unit_publish_to "$comp")" != image ]]; then info "$p: publish.to is not image, skipped"; return 0; fi
100
+ [[ -f "$p/Dockerfile" ]] || die "${p}:publish.to 是 image,但單元目錄沒有 Dockerfile"
101
+ jq -e --arg p "$p" '.packages | has($p)' "$CONFIG" >/dev/null || die "unexpected package path: $p (not a key of packages in $CONFIG)"
102
+ ver="$(manifest_version "$p")"
103
+ [[ -n "$ver" ]] || die "$p 不在 $MANIFEST"
104
+ version_stage "$ver" >/dev/null || die "$p: version \"$ver\" is not X.Y.Z or X.Y.Z-<alpha|beta|rc>.N"
105
+ mapfile -t platforms < <(policy_unit_publish_field "$comp" platforms)
106
+ (( ${#platforms[@]} )) || die "${p}:政策檔的 units.${comp}.publish 要寫 platforms"
107
+ for have in "${platforms[@]}"; do [[ "$have" =~ ^[a-z0-9]+/[a-z0-9]+$ ]] || die "${p}:平台「${have}」不是 <os>/<arch>"; done
108
+ platforms_csv="$(IFS=,; printf '%s' "${platforms[*]}")"
109
+ ref="$(registry)/$(image_owner)/${comp}:${ver}"
110
+ tag="$(unit_tag "$p" "$ver")"
111
+ file="${comp}-${ver}.digest"
112
+ repo="${GITHUB_REPOSITORY:-}"
113
+
114
+ if (( dry )); then
115
+ echo "## $comp ($p $ver)"
116
+ echo "image $ref"
117
+ echo "platforms $platforms_csv"
118
+ echo "digest file $file (asset of the Release $tag${repo:+ in $repo})"
119
+ echo "dry run: nothing built or pushed"
120
+ return 0
121
+ fi
122
+
123
+ [[ -n "$repo" ]] || die "不知道要把 digest 附到哪個倉的 Release,請設 GITHUB_REPOSITORY(owner/repo)"
124
+ git rev-parse -q --verify "refs/tags/$tag^{commit}" >/dev/null 2>&1 || die "release tag $tag does not exist, so $p $ver has not been released"
125
+ command -v docker >/dev/null 2>&1 || die "找不到 docker:image job 要跑在組織值 selfHostedRunnerLabels.docker 指定的 runner 上;組織沒有給這個值,就沒有能建映像的 runner"
126
+ docker version >/dev/null 2>&1 || die "docker 連不上 daemon:image job 要跑在有 docker 的 runner 上(組織值 selfHostedRunnerLabels.docker)"
127
+ docker buildx version >/dev/null 2>&1 || die "docker 沒有 buildx 外掛:image job 要跑在裝了 docker buildx 的 runner 上(組織值 selfHostedRunnerLabels.docker)"
128
+ out="${IMAGE_OUT:-$REPO_ROOT/tmp/image}/${comp}-${ver}"
129
+ rm -rf "$out"; mkdir -p "$out"
130
+
131
+ # the Release of the unit tag must be there: release-please creates it with the tag
132
+ view="$(read_retry gh release view "$tag" --repo "$repo" 2>&1)" || rc=$?
133
+ if (( rc != 0 )); then
134
+ [[ "$view" == *"release not found"* ]] && die "$repo 沒有 $tag 的 Release,digest 沒有地方附;release-please 發版時會建它"
135
+ die "查 $repo 的 Release $tag 失敗:$view"
136
+ fi
137
+ attached=""
138
+ existing="$out/existing"; mkdir -p "$existing"
139
+ read_retry gh release download "$tag" --repo "$repo" --pattern "$file" --dir "$existing" >/dev/null 2>&1 || true
140
+ [[ ! -s "$existing/$file" ]] || attached="$(tr -d '[:space:]' < "$existing/$file")"
141
+
142
+ docker_login
143
+ digest="$(image_digest "$ref")"
144
+ if [[ -n "$digest" ]]; then
145
+ if [[ -n "$attached" && "$attached" != "$digest" ]]; then
146
+ die "$ref 已在 $(registry),digest 是 ${digest},但 Release $tag 附的 $file 是 ${attached};已發布的版本不能動,請使用者決定,改發下一個版號"
147
+ fi
148
+ echo "$ref is already pushed ($digest), not built again"
149
+ else
150
+ [[ -z "$attached" ]] || die "$ref 不在 $(registry),但 Release $tag 已附 ${file}(${attached});請使用者決定怎麼處理,不要推出另一個 digest"
151
+ log "build and push:${ref}(${platforms_csv})"
152
+ local -a labels=(--label "org.opencontainers.image.version=$ver")
153
+ labels+=(--label "org.opencontainers.image.source=https://github.com/$repo")
154
+ if [[ -z "$builder" ]]; then
155
+ docker buildx create --name "publish-$$" --driver docker-container --use >/dev/null
156
+ builder="publish-$$"
157
+ fi
158
+ docker buildx build --platform "$platforms_csv" --file "$p/Dockerfile" --tag "$ref" "${labels[@]}" --metadata-file "$out/metadata.json" --push "$p"
159
+ digest="$(jq -r '."containerimage.digest" // empty' "$out/metadata.json")"
160
+ [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || die "建置沒有回報 $ref 的 digest(${digest:-空})"
161
+ fi
162
+
163
+ printf '%s\n' "$digest" > "$out/$file"
164
+ if [[ -z "$attached" ]]; then
165
+ gh release upload "$tag" "$out/$file" --repo "$repo"
166
+ log "digest $digest 已附到 $repo 的 Release $tag"
167
+ fi
168
+ summary "映像 \`$ref\`,digest \`$digest\`(附在 Release \`$tag\`)"
169
+ }
170
+
171
+ for p in "$@"; do image_unit "$p"; done