| 1 | #!/usr/bin/env bash |
| 2 | # Mirror github.com/codician-team/diffinery to Diffinery's codician/diffinery. |
| 3 | # |
| 4 | # Development happens on GitHub. Its main and tags are copied to Diffinery as they are, so |
| 5 | # both have the same commits and Diffinery's main always ends up where GitHub's is: anything |
| 6 | # pushed to Diffinery's main by other means is overwritten. Diffinery's other branches, and |
| 7 | # its issues, pull requests and releases, are left alone. |
| 8 | # |
| 9 | # Pushes with DIFFINERY_TOKEN when set, otherwise with whatever credentials git already has |
| 10 | # for diffinery.com. It must be a person's token with the admin scope: only an admin's push |
| 11 | # goes past main's branch protection, agents can't push to main, and a workflow's own token |
| 12 | # can't push changes to workflow files. |
| 13 | # |
| 14 | # Usage: scripts/mirror-from-github.sh [--dry-run] |
| 15 | # |
| 16 | # MIRROR_WORKDIR=<empty dir> keeps the fetched repository for inspection. |
| 17 | set -euo pipefail |
| 18 | |
| 19 | SRC=${MIRROR_SRC:-https://github.com/codician-team/diffinery.git} |
| 20 | DST=${MIRROR_DST:-https://diffinery.com/codician/diffinery.git} |
| 21 | dry_run=${1:-} |
| 22 | |
| 23 | auth=() |
| 24 | if [ -n "${DIFFINERY_TOKEN:-}" ]; then |
| 25 | # The helper reads the token from the environment, so it never lands on a command line. |
| 26 | auth=(-c 'credential.https://diffinery.com.helper=!f() { [ "$1" = get ] && printf "username=x-token\npassword=%s\n" "$DIFFINERY_TOKEN"; }; f') |
| 27 | fi |
| 28 | |
| 29 | # main and the tags, one "<sha>\t<ref>" line each (peeled tag lines dropped), sorted for comm. |
| 30 | refs() { git ${auth[@]+"${auth[@]}"} ls-remote "$1" refs/heads/main 'refs/tags/*' | grep -v '\^{}$' | LC_ALL=C sort; } |
| 31 | want=$(refs "$SRC") |
| 32 | have=$(refs "$DST") |
| 33 | # Diffinery may have tags GitHub doesn't; only GitHub's refs have to match. |
| 34 | stale=$(LC_ALL=C comm -23 <(printf '%s\n' "$want") <(printf '%s\n' "$have")) |
| 35 | if [ -z "$stale" ]; then |
| 36 | echo "Diffinery is up to date with GitHub." |
| 37 | exit 0 |
| 38 | fi |
| 39 | echo "To copy from GitHub:" |
| 40 | printf '%s\n' "$stale" |
| 41 | if [ "$dry_run" = "--dry-run" ]; then |
| 42 | exit 0 |
| 43 | fi |
| 44 | |
| 45 | work=${MIRROR_WORKDIR:-} |
| 46 | if [ -z "$work" ]; then |
| 47 | work=$(mktemp -d) |
| 48 | trap 'rm -rf "$work"' EXIT |
| 49 | fi |
| 50 | git init --quiet --bare "$work/repo.git" |
| 51 | cd "$work/repo.git" |
| 52 | git fetch --quiet "$SRC" '+refs/heads/main:refs/heads/main' '+refs/tags/*:refs/tags/*' |
| 53 | # GitHub wins: main and the tags move to where GitHub has them, fast-forward or not. |
| 54 | git ${auth[@]+"${auth[@]}"} push --force "$DST" 'refs/heads/main:refs/heads/main' 'refs/tags/*:refs/tags/*' |