Last active
August 31, 2025 18:32
-
-
Save iTrooz/05df1467bcbd6b2151dac63899cf0f1a to your computer and use it in GitHub Desktop.
Ensures you don't commit/push with the wrong git identity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# This script ensures you don't commit/push with the wrong git identity. My remotes are like this: gitperso:iTrooz/repo.git, gitschool:SomeUser/repo.git | |
# This script should be installed as both pre-commit and pre-push hook (symlink it) | |
# To use it as a global hook, see https://gist.github.com/iTrooz/551f779af2096912baa9d2e395e2642a | |
verify_author() { | |
local author="$1" | |
local url="$2" | |
case "$url" in | |
gitperso*) | |
if [[ "$author" != "iTrooz" ]]; then | |
echo "❌ Wrong author: '$author' (expected iTrooz)." | |
exit 1 | |
fi | |
;; | |
gitschool*) | |
if [[ "$author" != *SomeUser* ]]; then | |
echo "❌ Wrong author: '$author' (must contain 'SomeUser')." | |
exit 1 | |
fi | |
;; | |
*) | |
echo "⚠️ Unsupported origin '$url'. Skipping checks." | |
;; | |
esac | |
} | |
url=$(git config --get remote.origin.url) | |
if [[ "$0" == *pre-commit ]]; then | |
current_user=$(git config user.name) | |
echo "Checking local git user: $current_user" | |
verify_author "$current_user" "$url" | |
elif [[ "$0" == *pre-push ]]; then | |
while read local_ref local_sha remote_ref remote_sha; do | |
if [[ "$remote_sha" == 0000000000000000000000000000000000000000 ]]; then | |
range="$local_sha" | |
else | |
range="$remote_sha..$local_sha" | |
fi | |
[ -z "$range" ] && continue | |
while read -r commit; do | |
author_name=$(git show -s --format='%an' "$commit") | |
verify_author "$author_name" "$url" | |
done < <(git rev-list "$range") | |
done | |
fi | |
# If used as a global hook, call the local hook if it exists | |
# See https://gist.github.com/iTrooz/551f779af2096912baa9d2e395e2642a | |
LOCAL_HOOK=$(realpath ./.git/hooks/$(basename "$0")) | |
if [ -x "$LOCAL_HOOK" ] && [ "$LOCAL_HOOK" != "$(realpath $0)" ]; then | |
"$LOCAL_HOOK" "$@" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment