Skip to content

Instantly share code, notes, and snippets.

@VacuumBreather
Created January 12, 2025 23:34
Show Gist options
  • Save VacuumBreather/3540653c546490b12817e11294e4c143 to your computer and use it in GitHub Desktop.
Save VacuumBreather/3540653c546490b12817e11294e4c143 to your computer and use it in GitHub Desktop.
pre-commit hook to check for large files that should be tracked by LFS
#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".
# Redirect output to stderr.
exec 1>&2
# Set locale for numeric formatting
LC_NUMERIC="en_US.UTF-8"
FILE_SIZE_LIMIT_KB=1024
CURRENT_DIR="$(pwd)"
HAS_ERROR=""
COUNTER=0
# Generate file extension filter from gitattributes for git-lfs tracked files
filter=$(cat .gitattributes | grep filter=lfs | awk '{printf "-e .%s$ ", $1}')
# Before git commit, check non git-lfs tracked files to limit size
files=$(git diff --cached --name-only | sort | uniq | grep -v $filter)
while read -r file; do
if [ "$file" = "" ]; then
continue
fi
file_path=$CURRENT_DIR/$file
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
printf "%s has size %'i KB, over commit limit %'i KB.\n" "$file" "$file_size_kb" "$FILE_SIZE_LIMIT_KB"
HAS_ERROR="YES"
((COUNTER++))
fi
done <<< "$files"
# Exit with error if any non-lfs tracked files are over file size limit
if [ "$HAS_ERROR" != "" ]; then
echo "$COUNTER files are larger than permitted, please fix them before commit" >&2
exit 1
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment