Skip to content

Instantly share code, notes, and snippets.

@frimik
Created May 11, 2025 17:44
Show Gist options
  • Save frimik/214b36042b4197f567c8e6aa970cbbf8 to your computer and use it in GitHub Desktop.
Save frimik/214b36042b4197f567c8e6aa970cbbf8 to your computer and use it in GitHub Desktop.
Git plugin: hash-and-add - Hashes a file and adds to index. Convenient for hashing a filename for use in content delivery and caching (CDN)
#!/bin/bash
# git-hash-and-add: A Git plugin to hash a file, rename it with a hash suffix, and add it to the index.
# Supports two modes: default short SHA, and full SHA with --no-abbrev-commit.
# Check if a file argument is provided
if [ $# -lt 1 ]; then
echo "Usage: git hash-and-add <file> [--no-abbrev-commit]"
echo " Hashes the file, renames it with a hash suffix, and adds it to Git."
echo " --no-abbrev-commit: Use full SHA instead of short SHA."
exit 1
fi
# Get the input file
FILE="$1"
shift
# Check if the file exists
if [ ! -f "$FILE" ]; then
echo "Error: File '$FILE' not found."
exit 1
fi
# Determine hash mode
FULL_SHA=false
if [ "$1" = "--no-abbrev-commit" ]; then
FULL_SHA=true
shift
fi
# Compute the hash using git hash-object
if $FULL_SHA; then
HASH=$(git hash-object "$FILE")
else
HASH=$(git hash-object "$FILE" | cut -c1-7) # Short SHA (first 7 characters)
fi
# Extract the original filename and extension
FILENAME=$(basename "$FILE")
EXTENSION="${FILENAME##*.}"
NAME="${FILENAME%.*}"
# Create new filename with hash suffix
NEW_FILENAME="${NAME}-${HASH}.${EXTENSION}"
# Rename the file
cp "$FILE" "$NEW_FILENAME"
if [ $? -ne 0 ]; then
echo "Error: Failed to rename file."
exit 1
fi
# Add the new file to Git
git add "$NEW_FILENAME"
if [ $? -ne 0 ]; then
echo "Error: Failed to add file to Git."
exit 1
fi
echo "Successfully hashed, renamed to '$NEW_FILENAME', and added to Git."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment