Created
February 15, 2024 14:57
-
-
Save jogerj/69fb301e3183d843afb43d68817673cf to your computer and use it in GitHub Desktop.
This script adds a pre-commit hook to your Git repository that checks for any filenames that contain characters illegal in Windows. Whenever you attempt to commit changes, this hook will run and prevent commits that include such filenames.
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 | |
# add-illegal-windows-filename-check-pre-commit.sh: Sets up a pre-commit hook to check for illegal Windows filename characters | |
# Author: Jonathan Joewono (jogerj) | |
# Date: 12 Feb 2024 | |
# Version: 0.1.0 | |
# DESCRIPTION: | |
# This script adds a pre-commit hook to your Git repository that checks for any filenames that contain | |
# characters illegal in Windows. Whenever you attempt to commit changes, this hook will run and prevent | |
# commits that include such filenames. | |
# USAGE: | |
# 1. Add this file to your git repo folder and run `chmod +x add-illegal-windows-filename-check-pre-commit.sh` | |
# 2. Run `./add-illegal-windows-filename-check-pre-commit.sh` | |
# 3. You may delete this setup script from the repo after running it. Subsequent commits will trigger the pre-commit check. | |
# The script will output an error message if it detects any illegal filename characters, and the commit will be aborted. | |
# No further action is required once the pre-commit hook is set up. | |
HOOKS_DIR=".git/hooks" | |
if [ ! -d "$HOOKS_DIR" ]; then | |
mkdir -p "$HOOKS_DIR" | |
fi | |
PRE_COMMIT_HOOK="$HOOKS_DIR/pre-commit" | |
if [ ! -f "$PRE_COMMIT_HOOK" ]; then | |
# Add shebang header if new file | |
echo -e '#!/bin/sh' >> "$PRE_COMMIT_HOOK" | |
fi | |
cat << 'EOF' >> "$PRE_COMMIT_HOOK" | |
# Command to check for invalid characters in filenames in Windows | |
ILLEGAL_FILENAMES=$(git diff --cached --name-only | grep -vP '^(?!(?:PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d)(?:\..+)?$)[^\x00-\x1F\xA5\\?*:"";|\/<>]+(?<![\s.])$') | |
if [ ! -z "$ILLEGAL_FILENAMES" ]]; then | |
echo "These filenames contain characters which are not allowed on Windows!\n$ILLEGAL_FILENAMES" | |
exit 1 | |
fi | |
EOF | |
chmod +x "$PRE_COMMIT_HOOK" | |
echo "Pre-commit hook added successfully." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment