Git hook to reject commits where filename is longer than specified limit

Viewed 193

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).

1 Answers

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 files
  • xargs -0 basename For each of those paths, extract the file name
  • tr -d '\n' Removes the newline characters
  • wc -c Returns the number of characters in the file name

This 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.

Related