Skip to content

Commit 18f2d5c

Browse files
committed
chore: prevent direct commits and pushes to main branch (#281)
# Prevent direct commits and pushes to main branch This PR adds git hooks to prevent accidental direct commits and pushes to the main branch, enforcing a workflow where changes must go through pull requests. The implementation: - Adds a pre-commit hook that checks if the current branch is main and blocks commits if it is - Creates a pre-push hook script that prevents: - Pushing from the main branch - Pushing to the main branch (including cases like `git push origin feature:main`) These hooks are configured in lefthook.yml and will help maintain code quality by ensuring all changes to main go through proper review.
1 parent 940507a commit 18f2d5c

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/bin/bash
2+
3+
# Check current branch
4+
branch=$(git rev-parse --abbrev-ref HEAD)
5+
if [ "$branch" = "main" ]; then
6+
echo "ERROR: Direct pushes from main branch are not allowed!"
7+
exit 1
8+
fi
9+
10+
# Check destination branch (handles: git push origin feature:main)
11+
# Git hook receives: <local_ref> <local_sha> <remote_ref> <remote_sha> per line
12+
# Note: Using timeout because lefthook's script execution may keep stdin open
13+
while read -r -t 0.5 local_ref local_sha remote_ref remote_sha || [ -n "$local_ref" ]; do
14+
[ -z "$remote_ref" ] && break
15+
remote_branch=$(echo "$remote_ref" | sed 's#^refs/heads/##')
16+
if [ "$remote_branch" = "main" ]; then
17+
echo "ERROR: Pushing to remote main branch is not allowed!"
18+
echo "Attempted: $local_ref -> $remote_ref"
19+
exit 1
20+
fi
21+
done
22+
23+
exit 0

lefthook.yml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,19 @@ prepare-commit-msg:
99

1010
pre-commit:
1111
commands:
12+
'prevent-commit-on-main':
13+
run: |
14+
branch=$(git rev-parse --abbrev-ref HEAD)
15+
if [ "$branch" = "main" ]; then
16+
echo "ERROR: Direct commits to main branch are not allowed!"
17+
exit 1
18+
fi
1219
'validate-json-files':
1320
glob: '*.{json,jsonc}'
1421
run: |
1522
./scripts/validate-json-files.sh
23+
24+
pre-push:
25+
scripts:
26+
'prevent-push-to-main.sh':
27+
runner: bash

0 commit comments

Comments
 (0)