Unlock the Power of Git Hooks with Lefthook
Maintaining Code Quality with Git Hooks
As developers, we know how crucial it is to maintain code quality across a large codebase with multiple contributors. With the advent of linting, code formatting, and type checking, the importance of Git Hooks has never been more pronounced.
Introducing Lefthook
Lefthook is a polyglot Git Hooks manager developed using Go, making it compatible with Node.js and Ruby, as well as other stacks. Its single binary approach reduces the clutter in the node_modules directory. With Lefthook, you can execute tasks in parallel, choose which files to check, and separate local configurations.
Standout Features of Lefthook
Lefthook offers several features that set it apart from other Git Hook managers. These include:
- Parallel Execution: Utilize parallelization to speed up task execution, making it ideal for large-scale applications.
- File Selection: Execute commands on a limited set of files using prebuilt shorthands, glob and RegEx filters, and sub-directory options.
- Separate Local Configs: Manage hooks differently on your local machine with separate configuration files.
- Scripts and Runners: Create custom tasks with any programming language and select runners for these scripts.
- Piped Execution: Ensure smooth task completion with piped execution of commands.
- Inheritance of Configs: Extend configurations to ensure product or company-wide synchronization of commit messages, security audits, and other checks.
Implementing Lefthook in React and React Native
To demonstrate the power of Lefthook, let’s implement it in a React and React Native application.
Installation and Setup
npm install lefthook
lefthook init
We’ll create a lefthook.yml
file to hold our jobs and hooks.
Pre-Commit Hook
Our pre-commit hook will run quickly and in parallel to ensure our app’s code is always fit to be merged. We’ll divide the hook into four tasks: type checking, ESLint, code spell checker, and Markdown link check.
pre-commit:
parallel: true
scripts:
- yarn type-check
- yarn eslint
- yarn spell-check
- yarn markdown-link-check
Commit Message Hook
Next, we’ll set up a commit message hook to save us from the hassle of managing change logs and readability of commit messages. We’ll use commitlint, but you can always use another library or custom scripts with runners.
commit-msg:
- yarn commitlint
Pre-Push Hook
Finally, we’ll ensure that whenever code is pushed to our repository, it’s well tested for quality and security. Our pre-push hook will perform tasks in parallel, just like our pre-commit hook.
pre-push:
parallel: true
scripts:
- yarn test
- yarn security-audit
Check out our migration guide and gist to add hooks to your React and React Native apps.