Git Hooks

Git Hooks

git hooks, are like local scripts to be executed before or after any git activity.These scripts are written in shell.

There are few sample hook scripts within .git\hooks\ directory.Git hooks are classified into two categories,

  1. Client side hooks: is run before the git operation is sent to the server
  2. Server side hooks: to validate or enforce policies after git operation received from client.

Below is shell script for a hugo site to rsync the contents of public/ to a remote directory for deployment saved as pre-push,which is executed before git push, only when --deploy argument is passed along with git push command.

pre-push
#!/bin/sh

# Set the remote server and directory
REMOTE_SERVER="REMOTE_SERVER_ADDRESS"
REMOTE_DIR="directory_of_remote_server"

# Set the local public directory
PUBLIC_DIR="public"

# Function to copy files to remote server
copy_files() {
  rsync -avz --delete ${PUBLIC_DIR}/ ${REMOTE_SERVER}:${REMOTE_DIR}/
}

# Check if we're in a Git repository
if [ ! -d .git ]; then
  echo "Not a Git repository"
  exit 1
fi

# Copy files to remote server before pushing
echo "Pre-push hook: copying files to remote server..."
copy_files