summaryrefslogtreecommitdiffstats
path: root/bin/git-mirror
blob: 4c7722ecb067917b073740db62e6113b9d604c56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/bin/sh
#
# Copyright (c) 2013 Nagios Plugins Development Team
#
# Originally written by Holger Weiss <holger@zedat.fu-berlin.de>.
#
# This file is free software; the Nagios Plugins Development Team gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY, to the extent permitted by law; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

set -e
set -u

export PATH='/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin'

temp_prefix='/run/shm'
forty_zeros=$(printf '%.40d' 0)
myself=${0##*/}

check_refs()
{
	turn=$1
	temp_dir=$2

	git show-ref | while read object ref
	do
		ref_dir="$temp_dir/${ref%/*}"
		ref_file="$temp_dir/$ref"

		if [ $turn -eq 2 -a -f "$ref_file" ] \
		    && grep "^1 $object$" "$ref_file" >'/dev/null'
		then	# The ref has not been modified.
			rm -f "$ref_file"
		else
			mkdir -p "$ref_dir"
			echo "$turn $object" >>"$ref_file"
		fi
	done
}

if [ $# -lt 1 ]
then
	echo >&2 "Usage: $myself <repository> ..."
	exit 2
fi

temp_dir=$(mktemp -d "$temp_prefix/$myself.XXXXXX")
temp_file=$(mktemp "$temp_prefix/$myself.XXXXXX")
trap 'rm -rf "$temp_dir" "$temp_file"' EXIT

for repository in "$@"
do
	hook="$repository/hooks/post-receive"
	cd "$repository"

	check_refs 1 "$temp_dir"
	if ! git remote update --prune >"$temp_file" 2>&1
	then
		cat >&2 "$temp_file"
		exit 1
	fi
	git fetch --quiet --tags
	check_refs 2 "$temp_dir"

	if [ -x "$hook" ]
	then
		find "$temp_dir" -type 'f' -print | while read ref_file
		do
			ref=${ref_file#$temp_dir/}
			old=$(awk '$1 == "1" { print $2; exit }' "$ref_file")
			new=$(awk '$1 == "2" { print $2; exit }' "$ref_file")
			old=${old:-$fourty_zeros}
			new=${new:-$fourty_zeros}

			echo "$old" "$new" "$ref"
		done >"$temp_file"
		test -s "$temp_file" && "$hook" <"$temp_file"
	fi
	cd "$OLDPWD"
done