Keep Your Code Clean With Git Pre-Commit Hooks

  • 17th Jul, 2024
  • Parth P.
Share
  • LinkedIn-icon
  • WhatsApp-icon

Keep Your Code Clean With Git Pre-Commit Hooks

17th Jul, 2024 | Parth P.

  • Software Development
Pre-Commit

Have you ever been on a quest to make your code the best it can be, only to find out later that you accidentally let some sneaky bugs slip in?

It's like trying to build the perfect sandcastle, only to have it crumble because you missed a step!

But fear not, intrepid coder! There's a magical tool called Git pre-commit hooks that can help you keep your code kingdom safe and tidy.

Imagine Git pre-commit hooks as your loyal guardians, standing at the gates of your code kingdom, checking every change you make before it's allowed to enter.

They're like friendly dragons that sniff out any potential problems and warn you before it's too late!

Advantages

1. Error Prevention

Pre-commit hooks catch potential errors before they're committed, helping you avoid headaches down the line.

2. Consistency

By enforcing coding standards and best practices, pre-commit hooks ensure that your codebase remains consistent and easy to maintain.

3. Time Saving

Automating checks with pre-commit hooks saves you time that would otherwise be spent manually reviewing code.

4. Quality Assurance

Pre-commit hooks provide instant feedback, empowering you to make improvements and ensure the highest quality for your code.

Disadvantages

1. Setup Complexity

Configuring and maintaining pre-commit hooks may require some initial setup and ongoing maintenance, especially for larger projects.

2. False Positives

Overly strict hooks may occasionally flag legitimate changes as errors, leading to frustration for developers.

3. Local Dependencies

Pre-commit hooks only run on developers' local machines, so issues may still slip through if hooks aren't set up uniformly across the team.

4. Potential Overhead

Depending on the complexity of the checks performed, pre-commit hooks may introduce overhead and slow down the commit process.

For example, let's say you're working on a new feature to make your website more visually appealing.

With Git pre-commit hooks, you can ensure that every piece of code you write meets the highest quality standards before it's added to your main codebase.

This prevents accidentally adding code that could cause problems or degrade the website's functionality instead of enhancing it.

Prerequisites

We will explore setup procedures using Python.

1. Install Git

If you haven't already, install Git on your system. You can download and install Git from the official website: Git Downloads.

2. Create a Python Virtual Environment

Navigate to your Python project directory and create a virtual environment using venv or virtualenv:

python3  -m  venv  venv

Activate the virtual environment:

source  venv/bin/activate

Setting Up Pre-Commit Hooks

1. Install Required Packages

Install the necessary Python packages, including pre-commit, which provides the framework for managing pre-commit hooks:

pip install pre-commit

2. Define Pre-Commit Configuration

Create a ".pre-commit-config.yaml" file in the root of your project directory and define the pre-commit hooks you want to use. Here's an example configuration:

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
  rev: v3.4.0
  hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
  • a. repos: This is the top-level key that lists all repositories from which pre-commit hooks are fetched.

  • b. repo: This specifies the URL of the repository that contains the pre-commit hooks you want to use. In this case, it points to the pre-commit-hooks repository on GitHub.

  • c. rev: This indicates the specific version (or revision) of the repository to use. Here, v3.4.0 is the tag or version of the pre-commit-hooks repository that will be used.

  • d. hooks: This is a list of individual hooks from the specified repository that will be run. Each hook has an id that uniquely identifies it.

    • i. trailing-whitespace: This hook removes any trailing whitespace from the ends of lines in your files. Trailing whitespace can cause unnecessary changes and issues in version control, so it's good practice to remove it.

    • ii. end-of-file-fixer: This hook ensures that a file ends with exactly one new line. Many text editors and version control systems expect this convention, and it helps avoid unnecessary diffs and potential issues with certain tools.

    • iii. check-yaml: This hook checks YAML files for syntax errors. YAML is a common configuration file format, and syntax errors can lead to hard-to-debug issues. This hook helps ensure your YAML files are properly formatted.

3. Install Pre-Commit Hooks

Run the following command to install the pre-commit hooks defined in your configuration file:

pre-commit install  

4. Run Pre-Commit Hooks

To run pre-commit hooks on all files in your project, use:

pre-commit run --all-files

To run pre-commit hooks on a single file, specify the path to the file:

pre-commit run --files path/to/file.py

To skip a particular hook during the pre-commit check, use the --skip option followed by the hook ID:

pre-commit run --all-files --skip trailing-whitespace

To run a specific hook, use the --hook option followed by the hook ID:

pre-commit run --all-files --hook check-yaml

5. Commit Changes

Make some changes to your Python files and commit them using Git. The pre-commit hooks will automatically run before the commit is finalized.

6. Create Custom Pre-Commit Hooks

To create a custom pre-commit hook, create a Python script in your project directory. For example, create a file named "my_custom_hooks.py" with the following contents:

# my_custom_hooks.py

def my_custom_hook():
	# Your custom hook logic goes here
	pass

7. Register Custom Pre-Commit Hooks

In your ".pre-commit-config.yaml" file, add an entry for your custom hook, specifying the path to the script and any additional configuration options:

- repo: local
  hooks:
    - id: my-custom-hook
      name: My Custom Pre-Commit Hook
      entry: python -m my_custom_hooks.my_custom_hook
      language: python
      types: [ python ]
  • a. id: This is a unique identifier for your custom hook. In this case, it is my-custom-hook.

  • b. name: This is a human-readable name for the hook. It is My Custom Pre-Commit Hook. This name is used for display purposes, such as in pre-commit output logs.

  • c. entry: This specifies the command that runs the hook. Here, it uses the python -m command to run a Python module named my_custom_hooks.my_custom_hook. This command should execute your custom hook logic.

  • d. language: This indicates the programming language in which the hook is written. Here, it is set to Python, indicating that the hook is a Python script.

  • e. types: This is a list specifying the types of files the hook should run on. In this case, it is set to [Python], meaning the hook will run only on Python files.

This code block configures a custom pre-commit hook that is defined locally within your project.

The custom hook is a Python script identified by my-custom-hook and named My Custom Pre-Commit Hook.

When pre-commit runs, it will execute the specified Python module my_custom_hooks.my_custom_hook on Python files in your repository.

This allows you to implement and enforce custom checks or formatting rules specific to your project's needs, enhancing your code quality and consistency.

By following these setup procedures and using the provided commands, developers can effectively configure and manage Git pre-commit hooks for Python projects, while also having flexibility in running hooks on specific files and controlling hook execution.

Although setting up these tools requires some initial effort, the long-term benefits are significant.

Reduced bugs, improved code readability, and streamlined development workflows make the investment well worth it.

Embrace these practices to elevate your coding standards and enjoy a smoother, more efficient development experience.

More blogs in "Software Development"

Object Detection
  • Software Development
  • 16th Jul, 2021
  • Kinjal D.

Three Ways of Object Detection on Android

Object detection on Android has evolved significantly over the years, and with the advent of powerful machine learning models and improved hardware capabilities, developers now...
Keep Reading
DevOps
  • Software Development
  • 18th Nov, 2023
  • Aarav P.

Mastering DevOps: A Comprehensive Guide to Essential Tools

DevOps, a mix of "development" and "operations," is a modern wonder that brings teams together, makes work easier, and speeds up software delivery. But what are...
Keep Reading
ICT
  • Software Development
  • 24th Apr, 2024
  • Kinjal D.

Saudi Arabia's ICT Potential in a Growing Digital Landscape

Saudi Arabia has been witnessing rapid growth and development in its Information and Communication Technology (ICT) sector, driven by the government's vision to diversify its...
Keep Reading