Last active
October 14, 2023 12:44
-
-
Save ZoeLeBlanc/0955b95d09d9406fb1158d42f256e96e to your computer and use it in GitHub Desktop.
pre-commit hook for larger files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
GIT_DIR=$(git rev-parse --show-toplevel) | |
# Check if the file or any of its parent directories matches any patterns in gitignore | |
is_ignored_by_git() { | |
# Check if the file is ignored using Git's own check-ignore command | |
git -C "$GIT_DIR" check-ignore -q "$1" | |
return $? | |
} | |
# Use the -print0 option with find to handle spaces in file names correctly | |
find "$GIT_DIR" -type f -size +50M -print0 | while IFS= read -r -d $'\0' FILE; do | |
# Normalize path (remove leading GIT_DIR and './' from find) | |
FILE="${FILE#"$GIT_DIR/"}" | |
FILE="${FILE#./}" | |
# If the file doesn't match any pattern in gitignore (and isn't ignored already), add it | |
if ! is_ignored_by_git "$FILE"; then | |
echo "Adding $FILE to .gitignore" | |
echo "$FILE" >> "$GIT_DIR/.gitignore" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a step-by-step guide for setting up a Git template with your
pre-commit
script:Setting Up a Git Template with a Custom
pre-commit
Hook1. Create a Template Directory
First, we need a directory that will act as our template. This directory will contain the custom hooks and other configurations that we want to be copied to every new Git repository.
mkdir ~/git-template
2. Add the
pre-commit
ScriptNavigate to the hooks directory inside the template directory and create the
pre-commit
script with the desired content.Paste the following content into the
pre-commit
script:Save and exit the editor (for
nano
, pressCTRL + X
, thenY
, thenEnter
).3. Make the Script Executable
Ensure that the
pre-commit
script is executable:4. Configure Git to Use the Template Directory
Now, we'll tell Git to use our custom template directory whenever we initialize a new repository:
git config --global init.templateDir '~/git-template'
5. Test the Template
To test if everything is set up correctly, create a new Git repository and check if the
pre-commit
hook has been copied:mkdir test-repo cd test-repo git init ls .git/hooks
You should see the
pre-commit
script listed in the hooks directory of the new repository.