Productivity2023-05-25

8 Pre-commit Git Hooks You Must Know for Improved Productivity

Enhance your Git workflow with Git Worktree. Simplify branch management, switch effortlessly, and optimize your development process.
8 Pre-commit Git hooks you must know for improved productivity

One of the key features of Git is the ability to use pre-commit hooks to automate tasks and enforce standards before a commit is made. Pre-commit hooks are scripts that are executed before a commit is made to the repository. They can be used to validate code, check for formatting errors, ensure that tests pass, and much more. Code formatting and style guidelines can vary widely between projects and teams. However, enforcing these standards is important to ensure that the code remains consistent and easy to read. With pre-commit hooks, you can enforce code formatting and standards, saving hours of development time and ensuring that the code is consistent and easy to understand across the codebase.

For example, pre-commit hooks can be used to check for indentation, spacing, line breaks, and naming conventions. They can also be used to enforce specific formatting styles, such as the use of single or double quotes for strings, or the placement of braces in conditional statements. By using pre-commit hooks to enforce these standards, developers can avoid time-consuming code reviews and ensure that code remains consistent over time. Another benefit of using pre-commit hooks for code formatting and standards is that they can be customized to meet the specific needs of a project or team. For example, pre-commit hooks can be used to enforce specific coding conventions or to check for common mistakes that developers may make. By tailoring pre-commit hooks to the needs of a project or team, developers can ensure that code remains consistent and high-quality.

Overall, using pre-commit hooks to enforce code formatting and standards can save time and ensure that code remains consistent and easy to understand. By customizing pre-commit hooks to the needs of a project or team, developers can ensure that code quality remains high over time. In this article, we will explore eight pre-commit Git hooks that you should know to improve productivity.

8 Pre-Commit Git Hooks You Should Know

1. Linting

Linting is the process of checking code for errors and potential problems. It is a popular way to ensure that code meets a certain level of quality and consistency. Linting can be used to enforce coding standards, such as indentation, naming conventions, and code structure. There are many linting tools available for different programming languages, including ESLint for JavaScript/Typescript and Flake8 for Python.

2. Formatting

Code formatting refers to the way code is structured, including things like indentation, line breaks, and spacing. Consistent code formatting makes code easier to read and understand. A pre-commit hook can be used to automatically format code before it is committed to the repository. Popular tools for code formatting include Prettier for JavaScript/Typescript and Black for Python.

3. Spell Check

Spelling mistakes can be embarrassing and can also make code difficult to understand. A spell check pre-commit hook can be used to ensure that code and commit messages are free from spelling errors. Hunspell is another popular tool for spell-checking.

- repo: https://github.com/pre-commit/pre-commit-hooks

    rev: v3.4.0

    hooks:

      - id: markdown-spellcheck

        args: [--ignore-numbers, --check-filenames, --check-hidden, --check-acronyms, --check-case, --check-urls]

        files: '\.md$'

Using the pre-commit-hooks repository to perform the spell check. We've specified that we want to use the markdown-spellcheck hook, which checks for spelling errors in Markdown files. We've also provided some arguments to the hook to specify that we want to ignore numbers, check filenames, check hidden files, check acronyms, check cases, and check URLs. Finally, we've specified that the hook should only be run on files with a .md extension.

4. Static Code Analysis

Static code analysis involves analyzing code without actually running it. It is useful for detecting potential security vulnerabilities and performance issues. Static code analysis can be done using tools like SonarQube and CodeClimate. By integrating static code analysis into the pre-commit hook, developers can catch potential issues before they are committed to the repository.

5. Security Checks

Security is a critical consideration in software development. A pre-commit hook can be used to ensure that code is free from common security vulnerabilities. Tools like Brakeman for Ruby on Rails and OWASP Dependency Check for Java can be used to check for security issues in code.

6. Unit Tests

Unit tests are automated tests that check the functionality of a specific piece of code. By running unit tests before a commit, developers can ensure that their changes do not break existing functionality. Pre-commit hooks can be used to automatically run unit tests before a commit is made.

7. Commit Message Formatting

A well-formatted commit message makes it easier for others to understand what changes were made and why. A pre-commit hook can be used to enforce commit message formatting standards. Tools like Commitlint and Husky can be used to enforce commit message formatting rules.

8. Code Complexity

Code complexity refers to how difficult it is to understand and maintain code. High code complexity can make it difficult to maintain and update code over time. Pre-commit hooks can be used to check for code complexity and enforce limits on things like function length and cyclomatic complexity. Tools like McCabe IQ and CodeClimate can be used to analyze code complexity.

[ Read more: Use Git Hooks for Streamlined Software Development ]

When Should You Use Pre-commit Hooks?

Pre-commit hooks can be incredibly useful for automating tasks and ensuring code quality. Here are some of the best ways to use pre-commit hooks:

Enforce Code Formatting and Standards

Pre-commit hooks can be used to ensure that code adheres to specific formatting and style guidelines. This can include enforcing indentation, spacing, line breaks, and naming conventions. By using pre-commit hooks for code formatting and standards, developers can ensure that code is consistent and easy to read.

Create a pre-commit-config.yml file, that specifies the hook which should be run, in which order, and with which settings.

  - repo: https://github.com/pre-commit/pre-commit-hooks

  rev: v4.0.1

    hooks:

      - id: trailing-whitespace

      - id: end-of-file-fixer

      - id: check-yaml

        args: [--allow-multiple-documents]

      - id: check-added-large-files

        args: [--maxkb=100]

[ Read more: Automating Documentation Workflow with GitHub Actions ]

Run Linters and Static Code Analysis

Linters and static code analysis tools can be used to detect potential issues in code, such as syntax errors, security vulnerabilities, and performance problems. By using pre-commit hooks to run these tools, developers can catch potential issues before they make it into the codebase. This can save a lot of time and effort down the road, as issues can be much harder to fix once they are in the codebase.

Run Unit Tests 

Unit tests are automated tests that check the functionality of a specific piece of code. By running unit tests before a commit, developers can ensure that their changes do not break existing functionality. Pre-commit hooks can be used to automatically run unit tests before a commit is made.

In our pre-commit.yml file, add the following code:

- repo: local

    hooks:

      - id: run-unit-tests

        name: Run unit tests

        entry: npm run test

        language: system

        stages: [commit]

Enforce Commit Message Standards

Commit messages are an important part of the development process, as they provide context and information about changes made to the codebase. By using pre-commit hooks to enforce commit message standards, developers can ensure that commit messages are consistent and provide useful information.

Check for Code Complexity

Code complexity can make it difficult to understand and maintain code over time. Pre-commit hooks can be used to check for code complexity and enforce limits on things like function length and cyclomatic complexity. By doing so, developers can ensure that code remains easy to understand and maintain over time.

In our pre-commit.yml file, the following code uses the SonarQube platform to perform code complexity analysis and static code analysis. The sonar-scanner command runs a scan on the project, which will generate a report with various metrics such as code complexity, and code coverage.

#!/bin/bash

# Check code complexity and perform static analysis using SonarQube

sonar-scanner -Dsonar.projectKey=my-project -Dsonar.sources=.

# Check that code complexity and static analysis meet the requirements

SONAR_URL="https://sonarqube.mycompany.com"

SONAR_API="/api/measures/component"

SONAR_PROJECT_KEY="my-project"

SONAR_METRIC="ncloc,complexity,bugs,vulnerabilities"

SONAR_QG_STATUS="OK"

# Retrieve the latest analysis ID

ANALYSIS_ID=$(curl -s -u $SONAR_TOKEN: ${SONAR_URL}${SONAR_API}?component=${SONAR_PROJECT_KEY}&metricKeys=${SONAR_METRIC} | jq '.component.measures[].periods[0].value' | tr '\n' ',' | sed 's/,$//')

# Retrieve quality gate status for the latest analysis

QUALITY_GATE=$(curl -s -u $SONAR_TOKEN: ${SONAR_URL}/api/qualitygates/project_status?analysisId=${ANALYSIS_ID} | jq '.projectStatus.status')
if [ "$QUALITY_GATE" != "\"$SONAR_QG_STATUS\"" ]; then

  echo "Quality gate failed - please fix code complexity and static analysis issues before committing"

  exit 1

fi

Conclusion

Pre-commit Git hooks can be used to automate tasks and ensure that code meets a certain level of quality and consistency. By using pre-commit hooks, developers can catch potential issues before they are committed to the repository, saving time and improving productivity. The eight pre-commit Git hooks discussed in this article are just a few examples of the many ways in which pre-commit hooks can be used to improve the software development process.

Subscribe to the Hatica blog today to read more about unblocking developers, and boosting productivity with engineering analytics.

FAQs

1. What is Git pre-commit hook?

Pre-commit hooks are scripts that are executed before a commit is made to the repository.

2. Are pre-commit hooks a good idea?

Yes, pre-commit hooks are used to automate tasks and ensure that code meets a certain level of quality and consistency.

3. Where are Git pre-commit hooks stored?

The Git pre-commit hooks are stored in the hooks subdirectory of Git.

Share this article:
Table of Contents
  • 8 Pre-Commit Git Hooks You Should Know
  • 1. Linting
  • 2. Formatting
  • 3. Spell Check
  • 4. Static Code Analysis
  • 5. Security Checks
  • 6. Unit Tests
  • 7. Commit Message Formatting
  • 8. Code Complexity
  • When Should You Use Pre-commit Hooks?
  • Enforce Code Formatting and Standards
  • Run Linters and Static Code Analysis
  • Run Unit Tests 
  • Enforce Commit Message Standards
  • Check for Code Complexity
  • Conclusion
  • FAQs
  • 1. What is Git pre-commit hook?
  • 2. Are pre-commit hooks a good idea?
  • 3. Where are Git pre-commit hooks stored?

Ready to dive in? Start your free trial today

Overview dashboard from Hatica