FiWiManager/githooks/post-commit

47 lines
1.5 KiB
Bash
Executable File

#!/usr/bin/env bash
# Post-commit hook: push this repo, then optionally `git pull` on another machine over SSH.
#
# Opt-in (all must be set for the hook to do anything):
# export FIWI_POST_COMMIT_SYNC=1
# export FIWI_POST_COMMIT_REMOTE='user@host' # SSH target for the Pi / lab box
# export FIWI_POST_COMMIT_REMOTE_PATH='~/Code/FiWiManager' # repo root on that host
#
# Skip once: FIWI_POST_COMMIT_SYNC=0 git commit ...
# Disable hook: git config --unset core.hooksPath (or point hooksPath elsewhere)
#
# One-time setup in this clone:
# ./scripts/install-git-hooks.sh
set -euo pipefail
if [[ "${FIWI_POST_COMMIT_SYNC:-}" != "1" ]]; then
exit 0
fi
if [[ -z "${FIWI_POST_COMMIT_REMOTE:-}" ]]; then
echo "post-commit: FIWI_POST_COMMIT_SYNC=1 but FIWI_POST_COMMIT_REMOTE is empty; skipping." >&2
exit 0
fi
root=$(git rev-parse --show-toplevel)
cd "$root"
branch=$(git rev-parse --abbrev-ref HEAD)
if [[ "$branch" == "HEAD" ]]; then
echo "post-commit: detached HEAD; skipping push." >&2
exit 0
fi
echo "post-commit: git push origin $branch" >&2
git push origin "$branch"
rpath=${FIWI_POST_COMMIT_REMOTE_PATH:-~/Code/FiWiManager}
echo "post-commit: ssh $FIWI_POST_COMMIT_REMOTE git pull in $rpath" >&2
if [[ "$rpath" == ~/* ]]; then
_tail=${rpath#~/}
ssh -o BatchMode=yes "$FIWI_POST_COMMIT_REMOTE" bash -lc "cd \"\$HOME/$_tail\" && git pull"
else
_q=$(printf '%q' "$rpath")
ssh -o BatchMode=yes "$FIWI_POST_COMMIT_REMOTE" bash -lc "cd ${_q} && git pull"
fi