Skip to content

Instantly share code, notes, and snippets.

@santutu
Created February 2, 2024 12:07
Show Gist options
  • Save santutu/93e399621af52f0045b92224832933e1 to your computer and use it in GitHub Desktop.
Save santutu/93e399621af52f0045b92224832933e1 to your computer and use it in GitHub Desktop.
pre-push hook for git lfs. Prevent to ocurr error when pushing large files.
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting '.git/hooks/pre-push'.\n"; exit 2; }
git lfs pre-push "$@"
# This pre-push hook will check any non git-lfs tracked files that are about to be pushed and make sure they are not too big.
# Big files can be migrated to LFS using [git lfs migrate]
#
# To enable this hook, rename this file to "pre-push".
# It should be installed to a path like "[Reponame]/.git/hooks/pre-push".
# Redirect output to stderr.
exec 1>&2
FILE_SIZE_LIMIT_KB=102400 # 100 MB
CURRENT_DIR="$(pwd)"
HAS_ERROR=""
COUNTER=0
echo "Checking filesizes..."
# generate file extension filter from gitattributes for git-lfs tracked files
# Looks for either the exact filepath (^%s$) or uses the extension wildcard (.%s$)
filter=$(cat .gitattributes | grep filter=lfs | awk '{printf "-e \\(^%s$\\|.%s$\\) ", $1, $1}')
# before git commit, check non git-lfs tracked files to limit size
files=$(git diff origin/main --name-only | sort | uniq | grep -i -v "$filter")
OVERSIZED_FILES=()
while read -r file; do
if [ "$file" = "" ]; then
continue
fi
file_path=$CURRENT_DIR/$file
if [ ! -f "$file_path" ]; then
continue
fi
file_size=$(ls -l "$file_path" | awk '{print $5}')
file_size_kb=$((file_size / 1024))
if [ "$file_size_kb" -ge "$FILE_SIZE_LIMIT_KB" ]; then
echo "File [${file}] has size ${file_size_kb}KB, over commit limit ${FILE_SIZE_LIMIT_KB}KB."
HAS_ERROR="YES"
((COUNTER++))
OVERSIZED_FILES+=("$file")
fi
done <<< "$files"
# All good
if [ "$HAS_ERROR" == "" ]; then
exit 0
fi
# Some non-lfs tracked files are over file size limit
# Give option to automatically track them
echo "$COUNTER committed files are larger than permitted. Files should be migrated to LFS: [git lfs migrate import --include='path/to/file']"
# enable user input
for i in "${OVERSIZED_FILES[@]}"
do
$(git lfs migrate import --include="$i")
done
git lfs pull
exit 0
# Exit with error
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment