Skip to content

Commit 09bac29

Browse files
authored
Add doc for Git pre-push hook to block accidental pushes to main/master (#1012)
* Adding a doc on how to setup pre-push hook to forbid pushing to main/master
1 parent d2978aa commit 09bac29

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

docs/pre-push-branch-check.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# 🔒 Prevent Accidental Pushes to `main`/`master` — With Emergency Override
2+
3+
This guide shows you how to install a **Git pre‑push hook** that blocks pushes to branches (`main` or `master`) unless you explicitly set a noisy environment variable:
4+
5+
```
6+
BREAK_GLASS_MAIN_PUSH=1
7+
```
8+
9+
You can install this hook **globally** (affecting all your repos) or **per repo** (only in the specific repo you choose).
10+
Pick the option that best fits your workflow.
11+
12+
---
13+
14+
## 🛠 The Hook Script
15+
16+
Both installation methods use the same script:
17+
18+
```bash
19+
#!/bin/sh
20+
branch="$(git symbolic-ref --short HEAD)"
21+
22+
if [ "$branch" = "main" ] || [ "$branch" = "master" ]; then
23+
if [ "$BREAK_GLASS_MAIN_PUSH" = "1" ]; then
24+
echo "⚠️ Override used: pushing to '$branch'..."
25+
else
26+
echo "❌ Push to '$branch' is disabled locally."
27+
echo " If you REALLY need to, run:"
28+
echo " BREAK_GLASS_MAIN_PUSH=1 git push origin $branch"
29+
exit 1
30+
fi
31+
fi
32+
```
33+
34+
---
35+
36+
## Option 1 — Install Globally (All Repos)
37+
38+
This will protect every repo on your machine by default.
39+
40+
1. Create a global hooks directory:
41+
```bash
42+
mkdir -p ~/.git-hooks
43+
```
44+
45+
2. Create the pre‑push hook:
46+
```bash
47+
vim ~/.git-hooks/pre-push
48+
```
49+
Paste the script above.
50+
51+
3. Make it executable:
52+
```bash
53+
chmod +x ~/.git-hooks/pre-push
54+
```
55+
56+
4. Tell Git to use it globally:
57+
```bash
58+
git config --global core.hooksPath ~/.git-hooks
59+
```
60+
61+
---
62+
63+
## Option 2 — Install Per Repo (Only One Project)
64+
65+
This will protect only the repo you set it up in.
66+
67+
1. Go to your repo:
68+
```bash
69+
cd /path/to/your-repo
70+
```
71+
72+
2. Create the pre‑push hook:
73+
```bash
74+
vim .git/hooks/pre-push
75+
```
76+
Paste the script above.
77+
78+
3. Make it executable:
79+
```bash
80+
chmod +x .git/hooks/pre-push
81+
```
82+
83+
---
84+
85+
## ✅ Testing
86+
87+
1. Try pushing to `main` without override:
88+
```bash
89+
git push origin main
90+
```
91+
➡ Should be **blocked**.
92+
93+
2. Try with override:
94+
```bash
95+
BREAK_GLASS_MAIN_PUSH=1 git push origin main
96+
```
97+
➡ Allowed with warning.
98+
99+
---

0 commit comments

Comments
 (0)