Git Hooks For Pre-Commit

Git Hooks Pre-Commit Custom Scripts

Live stream set for 2025-05-20 at 14:00:00 Eastern Ask questions in the live chat about any programming or lifestyle topic. This live stream will be on YouTube or you can watch below.

Custom Action Scripts

Git hooks are scripts that automatically execute at specific stages of the Git workflow, allowing for customized actions and automated workflows. The hooks are stored in the hooks directory within a Git repository. These hooks can be used for various tasks, such as enforcing code standards, running tests, or performing actions before or after commits, pushes, or merges.

The git merge is a command used to integrated changes between 2 versions of a file or between 2 commits in a Git Repository. Git also allows a user to set their preferred merge tool using the git mergetoolcommand.

Client-side hooks are triggered by commit and merge operations, while server-side hooks run on remote operations such as received pushes.

The pre-commit hook executes before a commit is made, allowing for actions like formatting code or running tests.

The focus of this tutorial will be creating a pre-commit hook to inspect the code. Exiting non-zero from the pre-commit hook aborts the commit.

  1. Setting up a local repository and initializing your project.
  2. Create a pre-commit hook.
  3. Making changes, staging files, and committing with meaningful messages.
  4. Observe the output of the pre-commit hook script.

Requirements For Using Git

Glossary:

Distributed Version Control System

(DVCS) tracks versions of files.

Software Collaboration

Teams working together on projects.

Repository

Project storage space where all changes to files are tracked.

Branch

Enables developers to work on different versions of the project.

Stage

Prepare for a commit by adding files to a staging area.

Commit

Captures staged changes as a snapshot to add to repository’s history.

Diff

Generate set of differences between 2 files or folders.

Patch

Apply a set of differences to update files.

Merge

Combines changes from different branches of repositories into a single version.

Hooks

Programs placed in a hooks directory to trigger actions at certain points of the Git workflow.

Tools

Programming Tools
Name Description Example
Text editor For creating and editing source code Apache Netbeans IDE
SSH Secure Shell Client OpenSSH
Shell Access Access to the command line. Terminal
Git Distributed version control system. Git
Name Description Example

Create Local Repository

# Create New Project Folder If Applicable #
mkdir localproject
# Enter Project Folder #
cd localproject
# Initialize Local Repository As Working Folder #
git init

Add Pre-Commit Hook

# Create Pre-Commit Hook #
cat .git/hooks/pre-commit << 'EOF'
echo "You are about to commit" $(git diff --cached --name-only --diff-filter=ACM)
echo "to" $(git branch --show-current)

files=$(git status --porcelain | cut -b4-)
for file in $files; do
   if [[ ! -s $file ]]; then
      echo "$file is empty"
      exit 1
   elif [[ $file == *.php ]]; then
      chksyntax="$(php -l $file)"
      if [[ "$chksyntax" == *"No syntax errors"* ]]; then
         echo "$file has no syntax errors"
      else
         echo "$file has syntax errors"
         exit 1
      fi
   elif [[ $file == *.py ]]; then
      python -B $file
      exit_code=$?
      if [[ exit_code -eq 0 ]]; then
         echo "$file has no syntax errors"
      else
         echo "$file has syntax errors"
         exit 1
      fi
   fi
done
exit 0
EOF

# Make Script Executable #
chmod +x .git/hooks/pre-commit

Download And Install Git

Download

Git can be downloaded from Distributed Version Control System. Then the downloaded file is extracted directly on the server or locally before individual files are uploaded if applicable.

Explanation:

  1. The remote repository is created with bare because a working folder is not needed or it might be elsewhere such as for websites.
  2. The add command stages the desired files.
  3. The commit command will record a snapshot.
  4. The status command displays the state of the working folder and staging area.
  5. The Git pre-commit hook performs tests specified in a script file.

The remote repository is normally hosted on a remote location and accessed through SSH or a platform-specific method. During the commit, a message that clearly explains the changes made and why they were made helps future developers understand the context.

Git Local Repository Hooks Folder
File Browser Displaying A Local Git Repository Hooks Folder

Git Pre-Commit Default Sample
Text Editor Displaying Default Git Pre-Commit Default Sample File

Git Pre-Commit Custom Script
Text Editor Displaying Default Git Pre-Commit Custom Script File

Git Local Repository
File Browser Displaying A Local Repository Files And Folders

Git Pre-Commit Hook Ignored
Results Of Commit Condition Where Pre-Commit Hook Is Ignored

Git Pre-Commit Empty File Check
Results Of Commit Condition Where Pre-Commit Hook Checks For Empty Files

Git Pre-Commit Empty File And PHP File
Results Of Commit Condition Where Pre-Commit Hook Checks For Empty File And PHP File
Git Pre-Commit PHP File Syntax Check
Results Of Commit Condition Where Pre-Commit Hook Checks For Correct PHP File Syntax

Git Pre-Commit Python File Syntax Check
Results Of Commit Condition Where Pre-Commit Hook Checks For Correct Python File Syntax


Usage

You can use any IDE or text editor and the command-line or a web browser (if applicable) to run Git commands. For this tutorial, Git was used for source code management. Git is cross-platform compatible (Unix, Linux, MacOS and Windows). Git pre-commit hook was used for code style enforcement.

Open Source

Git is licensed under the GNU General Public License Version 2.0. The copyleft license comes with strict rules and requirements to ensure the software remains free and open-source. It allows commercial use, modification, distribution, and allows making derivatives proprietary, consult the license for more specific details.

Conclusion:

Git is a popular source code management system. Git is a distributed revision control system because every “working directory” contains the complete history and therefore revision tracking capabilities.

Git can work on remote servers or local machines to push committed changes and clone. The Git pre-commit hook executes before a commit is completed, allowing for actions like formatting code or running tests.

If you enjoy this article, consider supporting me by purchasing one of my WordPress Ojambo.com Plugins or programming OjamboShop.com Online Courses or publications at Edward Ojambo Programming Books or become a donor here Ojambo.com Donate

References:

Leave a Reply

Your email address will not be published. Required fields are marked *