I'm looking to create a client-side pre-commit git hook that will prevent a commit if any of the files added to the commit have a file name longer than a specified limit (say 256).
I'm looking to create a client-side pre-commit git hook that will prevent a commit if any of the files added to the commit have a file name longer than a specified limit (say 256).
Here's a starting point:
#!/bin/sh
# .git/hooks/pre-commit
# Checks that the file about to be committed
# doesn't have a name longer than 256 characters
if test $(git diff --cached --diff-filter=A --name-only | xargs -0 basename | tr -d '\n' | wc -c) -gt 256
then
echo "The staged file name is longer than 256 characters"
exit 1
fi
exit 0
Here's a breakdown of the command:
git diff --cached --diff-filter=A --name-only Gets the paths of the staged filesxargs -0 basename For each of those paths, extract the file nametr -d '\n' Removes the newline characterswc -c Returns the number of characters in the file nameThis example works if you have only one staged file. You'll have to develop it further by running the same check in a loop for all staged paths.