garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /hooks/git-post-receive

raw

#!/bin/sh
# Tell the midas hub that branches moved, the moment they do.
#
# Installed by the git server's machine owner into a repository's own hooks
# (for Forgejo: <repo>.git/hooks/post-receive.d/midas — see docs/hub.md, and
# never leave that directory empty: Forgejo's generated hook then fails on the
# unexpanded glob on every push). It runs as the git server's user after every
# push, with "<old> <new> <ref>" lines on stdin, and tells the hub's
# `POST /v1/pushed`, which accepts it only from the hub's own address — so this
# must run on the hub's machine. The hub fetches its mirror at once and logs a
# `pushed` event; nothing else depends on it.
#
# It fails open: a short timeout and always exit 0. The push it reports has
# already happened, and a hub that is down must never read as a push error.

# The hub's address, as docs/hub.md says to set it where this hook is installed.
hub="${MIDAS_HUB:-}"
[ -n "$hub" ] || exit 0

# The repository as owner/name, from where git runs the hook: its directory.
dir=$(pwd -P)
repo="$(basename "$(dirname "$dir")")/$(basename "$dir")"

refs=""
while read -r old new ref; do
    case "$ref" in
        refs/heads/*) ;;
        *) continue ;;
    esac
    # Only what is safe inside a JSON string without escaping.
    printf '%s' "$old$new$ref" | grep -q '^[A-Za-z0-9._/-]*$' || continue
    refs="$refs${refs:+,}{\"old\":\"$old\",\"new\":\"$new\",\"ref\":\"$ref\"}"
done
[ -n "$refs" ] || exit 0

curl -s -o /dev/null --max-time 3 -X POST -H 'Content-Type: application/json' \
    -d "{\"repo\":\"$repo\",\"refs\":[$refs]}" "$hub/v1/pushed" 2>/dev/null
exit 0