actual version bump support

This commit is contained in:
Agel committed 2026-11-19 12:25:43 +01:00
1 parent 6445c23fae
commit 4b3a959654
5 files changed
+351 -109

No files matched your search

+333
View File
@@ -0,0 +1,333 @@
#!/usr/bin/env bash
# End-of-pipeline release automation for Asteria Qt (master branch only):
# 1. Checks GITLAB_TOKEN expiration and self-rotates + updates the GitLab CI/CD
# variable if expiry is within TOKEN_ROTATE_THRESHOLD_DAYS (default: 30).
# 2. Creates release Git tag v<BUILT_VERSION> at CI_COMMIT_SHA (if absent).
# 3. Increments patch version in VERSION, commits with [skip ci], and pushes
# to the target branch (retrying on concurrent pushes).
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
cd "$PROJECT_DIR"
DEFAULT_BRANCH="${CI_DEFAULT_BRANCH:-master}"
TARGET_BRANCH="${CI_COMMIT_BRANCH:-}"
TOKEN_ROTATE_THRESHOLD_DAYS="${TOKEN_ROTATE_THRESHOLD_DAYS:-30}"
TOKEN_ROTATE_LIFETIME_DAYS="${TOKEN_ROTATE_LIFETIME_DAYS:-360}"
if [ "$TARGET_BRANCH" != "$DEFAULT_BRANCH" ] && [ "$TARGET_BRANCH" != "master" ]; then
echo "Skipping version bump: branch is '${TARGET_BRANCH:-unknown}', not '${DEFAULT_BRANCH}'."
exit 0
fi
if [ -z "${GITLAB_TOKEN:-}" ]; then
echo "ERROR: GITLAB_TOKEN CI/CD variable is not set" >&2
exit 1
fi
if [ -z "${CI_PROJECT_ID:-}" ] || [ -z "${CI_COMMIT_SHA:-}" ]; then
echo "ERROR: CI_PROJECT_ID and CI_COMMIT_SHA must be set" >&2
exit 1
fi
API_ROOT="${CI_API_V4_URL:-https://gitlab.com/api/v4}"
PROJECT_API="${API_ROOT}/projects/${CI_PROJECT_ID}"
WORK_TMP="$(mktemp -d)"
ASKPASS_SCRIPT="${WORK_TMP}/git-askpass.sh"
cleanup() {
rm -rf "$WORK_TMP"
}
trap cleanup EXIT
cat > "$ASKPASS_SCRIPT" <<'EOF'
#!/bin/sh
case "$1" in
*Username*|*username*) printf '%s\n' "oauth2" ;;
*) printf '%s\n' "${GITLAB_TOKEN}" ;;
esac
EOF
chmod 700 "$ASKPASS_SCRIPT"
parse_semver() {
local v="$1"
if ! [[ "$v" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
echo "ERROR: Invalid SemVer '$v' (expected MAJOR.MINOR.PATCH)" >&2
return 1
fi
}
semver_gt() {
local a="$1" b="$2"
parse_semver "$a"
local a1="${BASH_REMATCH[1]}" a2="${BASH_REMATCH[2]}" a3="${BASH_REMATCH[3]}"
parse_semver "$b"
local b1="${BASH_REMATCH[1]}" b2="${BASH_REMATCH[2]}" b3="${BASH_REMATCH[3]}"
if [ "$a1" -ne "$b1" ]; then
[ "$a1" -gt "$b1" ]
elif [ "$a2" -ne "$b2" ]; then
[ "$a2" -gt "$b2" ]
else
[ "$a3" -gt "$b3" ]
fi
}
increment_patch() {
local v="$1"
parse_semver "$v"
local major="${BASH_REMATCH[1]}"
local minor="${BASH_REMATCH[2]}"
local patch="${BASH_REMATCH[3]}"
echo "${major}.${minor}.$((patch + 1))"
}
ensure_fresh_token() {
local info_file="${WORK_TMP}/token_self.json"
local info_code
info_code=$(curl -s -o "$info_file" -w '%{http_code}' \
--header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
"${API_ROOT}/personal_access_tokens/self")
if [ "$info_code" != "200" ]; then
echo "WARNING: Could not query token expiry (HTTP ${info_code}); proceeding with current GITLAB_TOKEN."
return 0
fi
local expires_at
expires_at="$(jq -r '.expires_at // empty' "$info_file")"
if [ -z "$expires_at" ]; then
echo "GITLAB_TOKEN has no expiration date; skipping rotation."
return 0
fi
local days_left
days_left="$(python3 - "$expires_at" <<'PY'
from datetime import date
import sys
exp = date.fromisoformat(sys.argv[1][:10])
print((exp - date.today()).days)
PY
)"
echo "GITLAB_TOKEN expires on ${expires_at} (${days_left} days remaining)."
if [ "$days_left" -gt "$TOKEN_ROTATE_THRESHOLD_DAYS" ]; then
echo "Token valid for more than ${TOKEN_ROTATE_THRESHOLD_DAYS} days; no rotation needed."
return 0
fi
echo "Token expires within ${TOKEN_ROTATE_THRESHOLD_DAYS} days; checking CI/CD variable write access before rotating..."
local var_update_url=""
local group_id=""
local proj_var_code
proj_var_code=$(curl -s -o /dev/null -w '%{http_code}' \
--header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
"${PROJECT_API}/variables/GITLAB_TOKEN")
if [ "$proj_var_code" = "200" ]; then
var_update_url="${PROJECT_API}/variables/GITLAB_TOKEN"
else
local proj_info="${WORK_TMP}/project.json"
local proj_code
proj_code=$(curl -s -o "$proj_info" -w '%{http_code}' \
--header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
"${PROJECT_API}")
if [ "$proj_code" = "200" ]; then
local ns_kind
ns_kind="$(jq -r '.namespace.kind // empty' "$proj_info")"
if [ "$ns_kind" = "group" ]; then
group_id="$(jq -r '.namespace.id // empty' "$proj_info")"
if [ -n "$group_id" ]; then
local grp_var_code
grp_var_code=$(curl -s -o /dev/null -w '%{http_code}' \
--header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
"${API_ROOT}/groups/${group_id}/variables/GITLAB_TOKEN")
if [ "$grp_var_code" = "200" ]; then
var_update_url="${API_ROOT}/groups/${group_id}/variables/GITLAB_TOKEN"
fi
fi
fi
fi
fi
if [ -z "$var_update_url" ]; then
echo "WARNING: GITLAB_TOKEN CI/CD variable is not accessible via API (project check HTTP ${proj_var_code}). Skipping rotation to avoid losing the rotated token."
return 0
fi
local new_expires_at
new_expires_at="$(python3 - "$TOKEN_ROTATE_LIFETIME_DAYS" <<'PY'
from datetime import date, timedelta
import sys
days = int(sys.argv[1])
print((date.today() + timedelta(days=days)).isoformat())
PY
)"
local rotate_urls=("${PROJECT_API}/access_tokens/self/rotate?expires_at=${new_expires_at}")
if [ -n "$group_id" ]; then
rotate_urls+=("${API_ROOT}/groups/${group_id}/access_tokens/self/rotate?expires_at=${new_expires_at}")
fi
rotate_urls+=("${API_ROOT}/personal_access_tokens/self/rotate?expires_at=${new_expires_at}")
local rotated_token=""
local rot_file="${WORK_TMP}/rotate_resp.json"
local rot_code=""
local url
for url in "${rotate_urls[@]}"; do
rot_code=$(curl -s -o "$rot_file" -w '%{http_code}' -X POST \
--header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
"$url")
if [ "$rot_code" = "200" ] || [ "$rot_code" = "201" ]; then
rotated_token="$(jq -r '.token // empty' "$rot_file")"
if [ -n "$rotated_token" ]; then
break
fi
fi
done
if [ -z "$rotated_token" ]; then
echo "ERROR: Failed to self-rotate GITLAB_TOKEN (last HTTP ${rot_code}):" >&2
jq 'del(.token)' "$rot_file" >&2 || true
return 1
fi
export GITLAB_TOKEN="$rotated_token"
local put_file="${WORK_TMP}/var_put.json"
local put_code
put_code=$(jq -n --arg v "${GITLAB_TOKEN}" '{value: $v}' | \
curl -s -o "$put_file" -w '%{http_code}' -X PUT \
--header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
--header "Content-Type: application/json" \
--data-binary @- \
"$var_update_url")
if [ "$put_code" != "200" ]; then
echo "ERROR: Rotated GITLAB_TOKEN, but failed to persist new value to CI/CD variable (HTTP ${put_code}):" >&2
cat "$put_file" >&2
return 1
fi
echo "Successfully self-rotated GITLAB_TOKEN (new expiry: ${new_expires_at}) and updated CI/CD variable."
}
create_release_tag() {
local built_version="$1"
local tag_name="v${built_version}"
local encoded_tag
encoded_tag="$(jq -rn --arg t "${tag_name}" '$t|@uri')"
local exists_code
exists_code=$(curl -s -o /dev/null -w '%{http_code}' \
--header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
"${PROJECT_API}/repository/tags/${encoded_tag}")
if [ "$exists_code" = "200" ]; then
echo "Tag ${tag_name} already exists; skipping tag creation."
return 0
fi
local tag_resp="${WORK_TMP}/tag_resp.json"
local create_code
create_code=$(jq -n \
--arg tag "${tag_name}" \
--arg ref "${CI_COMMIT_SHA}" \
--arg msg "Release ${tag_name} (pipeline #${CI_PIPELINE_ID:-0})" \
'{tag_name: $tag, ref: $ref, message: $msg}' | \
curl -s -o "$tag_resp" -w '%{http_code}' -X POST \
--header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
--header "Content-Type: application/json" \
--data-binary @- \
"${PROJECT_API}/repository/tags")
if [ "$create_code" = "201" ] || [ "$create_code" = "200" ]; then
echo "Created release tag ${tag_name} at ${CI_COMMIT_SHA}"
else
echo "ERROR: Failed to create tag ${tag_name} (HTTP ${create_code})" >&2
cat "$tag_resp" >&2
return 1
fi
}
bump_and_commit_version() {
local built_version="$1"
local remote_url="${BUMP_GIT_REMOTE:-}"
if [ -z "$remote_url" ]; then
if [ -z "${CI_SERVER_HOST:-}" ] || [ -z "${CI_PROJECT_PATH:-}" ]; then
echo "ERROR: CI_SERVER_HOST and CI_PROJECT_PATH must be set for git push" >&2
return 1
fi
remote_url="${CI_SERVER_PROTOCOL:-https}://${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git"
fi
git config user.name "${GITLAB_USER_NAME:-Asteria CI}"
git config user.email "${GITLAB_USER_EMAIL:-ci@asteria-bookreader.local}"
local push_opts=()
if [[ "$remote_url" == http://* ]] || [[ "$remote_url" == https://* ]]; then
push_opts+=(-o ci.skip)
fi
local next_version
next_version="$(increment_patch "$built_version")"
printf '%s\n' "$next_version" > VERSION
if git diff --quiet VERSION; then
echo "VERSION already at ${next_version}; nothing to commit."
return 0
fi
git add VERSION
git commit -m "chore: bump version to ${next_version} [skip ci]"
if GIT_ASKPASS="$ASKPASS_SCRIPT" GIT_TERMINAL_PROMPT=0 \
git push ${push_opts[@]+"${push_opts[@]}"} "$remote_url" "HEAD:refs/heads/${TARGET_BRANCH}"; then
echo "Bumped VERSION from ${built_version} to ${next_version} and pushed to ${TARGET_BRANCH}."
return 0
fi
# Fallback only if origin moved during the pipeline run
local attempt
for attempt in 1 2; do
echo "Push rejected (remote ${TARGET_BRANCH} moved); fetching latest and retrying (${attempt}/2)..."
GIT_ASKPASS="$ASKPASS_SCRIPT" GIT_TERMINAL_PROMPT=0 \
git fetch "$remote_url" "$TARGET_BRANCH"
git checkout -f -B "$TARGET_BRANCH" FETCH_HEAD
local remote_version
remote_version="$(tr -d '[:space:]' < VERSION)"
parse_semver "$remote_version"
if semver_gt "$remote_version" "$built_version"; then
echo "Remote VERSION (${remote_version}) is already ahead of built version (${built_version}); skipping VERSION bump commit."
return 0
fi
next_version="$(increment_patch "$remote_version")"
printf '%s\n' "$next_version" > VERSION
git add VERSION
git commit -m "chore: bump version to ${next_version} [skip ci]"
if GIT_ASKPASS="$ASKPASS_SCRIPT" GIT_TERMINAL_PROMPT=0 \
git push ${push_opts[@]+"${push_opts[@]}"} "$remote_url" "HEAD:refs/heads/${TARGET_BRANCH}"; then
echo "Bumped VERSION from ${remote_version} to ${next_version} and pushed to ${TARGET_BRANCH}."
return 0
fi
sleep 2
done
echo "ERROR: Failed to push bumped VERSION to ${TARGET_BRANCH}." >&2
return 1
}
BUILT_VERSION="$(tr -d '[:space:]' < VERSION)"
parse_semver "$BUILT_VERSION"
ensure_fresh_token
create_release_tag "$BUILT_VERSION"
bump_and_commit_version "$BUILT_VERSION"
+4 -58
View File
@@ -2,13 +2,10 @@
# Compute Semantic Version (SemVer 2.0.0) for Asteria Qt.
#
# Rules:
# - Base version (MAJOR.MINOR.BASE_PATCH) is read from the root VERSION file.
# - Current version (MAJOR.MINOR.PATCH) is read from the root VERSION file.
# - On master (default branch):
# - If HEAD already has a release tag vMAJOR.MINOR.P, reuse MAJOR.MINOR.P.
# - Otherwise, PATCH = max(BASE_PATCH, highest existing vMAJOR.MINOR.* tag + 1).
# - Outputs: MAJOR.MINOR.PATCH
# - On feature branches:
# - PATCH = max(BASE_PATCH, highest existing vMAJOR.MINOR.* tag + 1).
# - Branch name is sanitized to lowercase [a-z0-9-] for SemVer pre-release.
# - Outputs: MAJOR.MINOR.PATCH-<sanitized-branch>.<short-sha>
#
@@ -35,7 +32,7 @@ while [[ $# -gt 0 ]]; do
shift 2
;;
-h|--help)
sed -n '2,18p' "$0" | sed 's/^# \{0,1\}//'
sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'
exit 0
;;
*)
@@ -58,7 +55,7 @@ fi
MAJOR="${BASH_REMATCH[1]}"
MINOR="${BASH_REMATCH[2]}"
BASE_PATCH="${BASH_REMATCH[3]}"
PATCH="${BASH_REMATCH[3]}"
# Determine current branch and short SHA
BRANCH="${OVERRIDE_BRANCH:-${CI_COMMIT_BRANCH:-${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-${CI_COMMIT_REF_NAME:-}}}}"
@@ -82,58 +79,7 @@ if [ -z "$SHORT_SHA" ]; then
fi
DEFAULT_BRANCH="${CI_DEFAULT_BRANCH:-master}"
IS_MASTER=false
if [ "$BRANCH" = "$DEFAULT_BRANCH" ] || [ "$BRANCH" = "master" ]; then
IS_MASTER=true
fi
# Extract max patch from tags matching v?MAJOR.MINOR.PATCH (no pre-release suffix)
max_patch_in_tags() {
local max_p=-1
local tag p
while IFS= read -r tag; do
[ -z "$tag" ] && continue
if [[ "$tag" =~ ^v?${MAJOR}\.${MINOR}\.([0-9]+)$ ]]; then
p="${BASH_REMATCH[1]}"
if [ "$p" -gt "$max_p" ]; then
max_p="$p"
fi
fi
done
echo "$max_p"
}
PATCH="$BASE_PATCH"
if [ "$HAS_GIT" = true ]; then
# If on master (or detached HEAD) and HEAD is already tagged with a matching release tag, keep it
if [ "$IS_MASTER" = true ] || [ "$BRANCH" = "HEAD" ] || [ -z "$BRANCH" ]; then
HEAD_MAX_PATCH="$(git -C "$PROJECT_DIR" tag --points-at HEAD 2>/dev/null | max_patch_in_tags)"
if [ "$HEAD_MAX_PATCH" -ge 0 ]; then
if [ "$HEAD_MAX_PATCH" -ge "$BASE_PATCH" ]; then
PATCH="$HEAD_MAX_PATCH"
fi
echo "${MAJOR}.${MINOR}.${PATCH}"
exit 0
fi
fi
REPO_MAX_PATCH="$(git -C "$PROJECT_DIR" tag -l "v${MAJOR}.${MINOR}.*" "${MAJOR}.${MINOR}.*" 2>/dev/null | max_patch_in_tags)"
if [ "$REPO_MAX_PATCH" -ge 0 ]; then
NEXT_PATCH=$((REPO_MAX_PATCH + 1))
if [ "$NEXT_PATCH" -gt "$PATCH" ]; then
PATCH="$NEXT_PATCH"
fi
fi
fi
if [ "$IS_MASTER" = true ]; then
echo "${MAJOR}.${MINOR}.${PATCH}"
exit 0
fi
# Non-git fallback if branch couldn't be determined
if [ -z "$BRANCH" ]; then
if [ "$BRANCH" = "$DEFAULT_BRANCH" ] || [ "$BRANCH" = "master" ] || [ -z "$BRANCH" ]; then
echo "${MAJOR}.${MINOR}.${PATCH}"
exit 0
fi