-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-prevent-out-of-sync-commit
More file actions
executable file
·52 lines (41 loc) · 1.33 KB
/
git-prevent-out-of-sync-commit
File metadata and controls
executable file
·52 lines (41 loc) · 1.33 KB
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
#!/bin/bash
# Git hook to prevent operations when branch is behind remote
# Place in .git/hooks/pre-push or pre-commit
# Colors for output
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Get the current branch name
current_branch=$(git branch --show-current)
if [ -z "$current_branch" ]; then
echo -e "${RED}Error: Not on any branch (detached HEAD state)${NC}"
exit 1
fi
# Get the remote tracking branch
remote_branch=$(git rev-parse --abbrev-ref --symbolic-full-name "@{u}" 2>/dev/null)
if [ -z "$remote_branch" ]; then
# No remote tracking branch - allow the operation
exit 0
fi
# Fetch the latest changes from remote
git fetch --quiet 2>/dev/null
# Count commits behind
commits_behind=$(git rev-list --count HEAD.."$remote_branch" 2>/dev/null)
if [ -z "$commits_behind" ]; then
# If we can't determine, allow the operation
exit 0
fi
# Check if branch is behind remote
if [ "$commits_behind" -gt 0 ]; then
echo -e "${RED}✗ ERROR: Branch '$current_branch' is behind '$remote_branch' by $commits_behind commit(s)${NC}"
echo ""
echo "Missing commits from remote:"
git log --oneline --decorate HEAD.."$remote_branch"
echo ""
echo -e "${YELLOW}Please pull the latest changes first:${NC}"
echo " git pull"
echo ""
exit 1
fi
# Branch is not behind - allow the operation
exit 0