Setting Up Pre-Push Git Hooks for Code Formatting

Sun Apr 07 2024

Introduction

Ensuring that your codebase is consistently formatted before pushing changes to your repository is crucial for maintaining code quality and readability. Git hooks provide a powerful way to automate this process. In this post, we'll explore how to set up a pre-push Git hook that runs a format script on your code before each push to the repository.

Creating a Pre-Push Hook

To create a pre-push hook, you first need to write a script that Git will execute before each push. Here's an example of a pre-push script that runs a formatting command:

#!/bin/sh

# Run npm format command
npm run format

# Optional: Check if there are files to be committed after formatting.
# If there are none, cancel the commit.
if ! git diff --cached --exit-code --quiet; then
    echo "Code was formatted. Please review changes and commit again."
    exit 1
fi

This script runs the npm run format command and checks if any files have been modified by the formatter. If so, it exits with an error, prompting the user to review and commit the changes.

Manually Setting the Pre-Push Script

To set this script as a pre-push hook:

  1. Navigate to the .git/hooks directory in your repository.
  2. Create a file named pre-push with no extension.
  3. Paste the script into this file.
  4. Make the script executable by running chmod +x pre-push in your terminal.

Once these steps are completed, the pre-push hook is set up, and the format script will run before each push.

Setting the Format Script in package.json

To specify what the format command does, define it in your project's package.json file under the scripts section:

{
  "scripts": {
    "format": "prettier --write ."
  }
}

Replace "prettier --write ." with the command that runs your preferred code formatter. This command is what will be executed when the pre-push hook calls npm run format.

Conclusion

Automating code formatting using pre-push Git hooks can significantly improve code quality and consistency across your team. By following the steps outlined above, you can ensure that every push adheres to your project's formatting standards, making your codebase cleaner and easier to maintain.