#!/bin/bash
# git-mirror: Mirror a git repo in leader-followers configuration
# Copyright © 2019 Midgard
#
# This program is free software: you can redistribute it and/or modify it under the terms of the
# GNU Affero General Public License as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License along with this program.
# If not, see .
set -euo pipefail
IFS=$'\n'
tor=true
if [[ "$1" == "--notor" ]]; then
tor=false
shift 1
fi
if [[ $# -lt 3 ]]; then
echo "Usage: $0 [--notor] "
exit 1
fi
cd "$1"
leader="$2"
shift 2
followers=( "$@" )
echo "Working directory: $PWD"
echo "Leader remote: $leader"
echo "Follower remotes: ${followers[*]}" | tr '\n' ' '
echo; echo
if [[ $tor == true ]]; then
torify git fetch --prune --multiple "$leader"
else
git fetch --prune --multiple "$leader"
fi
git fetch --prune --multiple "${followers[@]}"
echo
echo "Leader remote information:"
git remote show -n "$leader"
echo
echo "Follower remotes information:"
git remote show -n "${followers[@]}"
echo
branches=( $(git show-ref | sed -n 's| refs/remotes/'"$leader"'/|\t|p') )
echo -e "${#branches[*]} branches at leader:"
echo "${branches[*]}"
IFS=$'\t'
errors=( )
error() {
echo "XXX $1" >&2
errors[${#errors[*]}]="$1"
}
ref_exists() {
git show-ref --verify --quiet "$1"
}
is_ref_at_sha() {
sha1="$(git show-ref --verify --hash "$1")"
sha2="$2"
[[ $sha1 == $sha2 ]]
}
for branchspec in "${branches[@]}"; do
set $branchspec
leader_sha="$1"
branch="$2"
for remote in "${followers[@]}"; do
echo
echo "Updating $remote/$branch"
follower_ref="refs/remotes/$remote/$branch"
if ! ref_exists "$follower_ref"; then
echo "Branch doesn't yet exist at remote, creating"
git reset --hard "$leader_sha" --
git push "$remote" "+HEAD:$branch" || { error "$remote $branch: failed to push"; continue; }
elif is_ref_at_sha "$follower_ref" "$leader_sha"; then
echo "Already up to date"
else
echo "Branch exists at remote, updating"
git reset --hard "$follower_ref" --
git merge --ff-only "$leader_sha" || { error "$remote $branch: FF not possible"; continue; }
git push "$remote" "+HEAD:$branch" || { error "$remote $branch: failed to push"; continue; }
fi
done
done
echo
if [[ "${#errors[*]}" -gt 0 ]]; then
echo "Errors:"
echo "${errors[@]}"
else
echo "No errors."
fi