Skip to content

Commit 0e78bd3

Browse files
authored
feat: pre-push git hook to check for lock file relevant changes
1 parent d493d3b commit 0e78bd3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

.husky/pre-push

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Configuration: Each entry is an array with [pattern, command, description]
2+
# Format: "pattern" "command" "pattern description"
3+
CHECKS=('^(package\.json|package-lock\.json)$' 'npm install --package-lock-only --ignore-scripts' 'package.json or package-lock.json – please run npm install to update dependencies')
4+
5+
# Check for changes in specified files before pushing and run corresponding commands
6+
## Get the upstream branch
7+
UPSTREAM=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null || echo "")
8+
if [ -z "$UPSTREAM" ]; then
9+
echo "No upstream configured, detecting default branch."
10+
# Try to detect the default branch from origin/HEAD
11+
DEFAULT_BRANCH=$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@')
12+
if [ -z "$DEFAULT_BRANCH" ]; then
13+
echo "Could not detect default branch, falling back to 'main'."
14+
DEFAULT_BRANCH="main"
15+
fi
16+
UPSTREAM="$DEFAULT_BRANCH"
17+
fi
18+
19+
## Get the list of files changed between upstream and HEAD
20+
FILES=$(git diff --name-only $UPSTREAM..HEAD)
21+
22+
## Check each pattern and run corresponding command
23+
for ((i=0; i<${#CHECKS[@]}; i+=3)); do
24+
pattern="${CHECKS[i]}"
25+
command="${CHECKS[i+1]}"
26+
description="${CHECKS[i+2]}"
27+
28+
if echo "$FILES" | grep -qE "$pattern"; then
29+
echo "Detected changes in $description"
30+
31+
## Run the corresponding command
32+
eval "$command"
33+
34+
if [ $? -ne 0 ]; then
35+
echo "Command failed: $command. Aborting push."
36+
exit 1
37+
fi
38+
39+
# Exit after first match to avoid running multiple commands
40+
exit 0
41+
fi
42+
done
43+
44+
echo "No monitored file changes detected. Skipping checks."

0 commit comments

Comments
 (0)