Course contentsShow
← Software Engineering
Lesson 393 of 1,93311. Code Quality and ReadabilityFree lesson

Pre-commit Hooks and Git Hooks

Running automated checks before code is committed to catch issues early and maintain quality standards.

Pre-commit Hooks and Git Hooks

What you'll learn: How to automatically run quality checks before code enters your repository.

The Gatekeeper at the Door

Imagine a security checkpoint that inspects your luggage before you board a plane, not after. Pre-commit hooks work the same way for your code—they're automated scripts that run checks before your commits are finalized, catching problems early when they're cheapest to fix.

What Are Git Hooks?

Git hooks are scripts that Git executes automatically at specific points in your workflow. They live in your project's .git/hooks directory and can run before or after events like committing, pushing, or merging.

Pre-commit hooks are the most common type. They run when you type git commit but before the commit is actually created. If the hook finds issues, it can reject the commit entirely.

Why Use Pre-commit Hooks?

You've learned about linters, formatters, and static analysis tools. Pre-commit hooks ensure these tools actually run consistently across your team:

  • Enforce formatting before code enters version control
  • Run linters to catch style violations automatically
  • Check for common mistakes (forgotten debug statements, merge conflicts markers)
  • Prevent bad commits from polluting the repository history

Think of them as the final quality gate that complements your manual refactoring efforts. They catch what humans forget.

The Practical Flow

When you commit code with hooks enabled, the workflow becomes:

  1. You run git commit
  2. Pre-commit hook runs your code formatter
  3. Pre-commit hook runs your linter
  4. If everything passes → commit succeeds
  5. If anything fails → commit is rejected, you fix issues, try again

This automation transforms code quality from a suggestion into a requirement, maintaining the standards you've established through refactoring and naming conventions.

Key Takeaway: Pre-commit hooks automate code quality checks at the point of commit, ensuring that only properly formatted and validated code enters your repository—catching issues before they spread.