I'm using Flutter for mobile development and, coming from the JavaScript world, I'm used to having Git hooks running checks before a commit or a push using husky and lint-staged.
To accomplish the same with Flutter, I've decided to use Lefthook - the fastest polyglot Git hooks manager out there. Read the introduction post to find out more details about it.
Without further ado, let's see how to use it in our projects.
- Install Lefthook via gem, npm or from source or your OS package manager;
- Define your hooks in the file
lefthook.yml
:
pre-push:
parallel: true
commands:
tests:
run: flutter test
linter:
run: flutter analyze
pre-commit:
commands:
pretty:
glob: '*.dart'
run: flutter format {staged_files} && git add {staged_files}
- Run
lefthook install
to finish the setup.
And that's it! Now, whenever you commit something, flutter format
will run in the staged files and whenever you push commits, flutter test
and flutter analyze
will run in parallel.
If any of these commands throws an error, the action will be aborted.
Notes
Even though I've demonstrated it with Flutter, Lefthook is "polyglot" and can be used with many other languages and frameworks. It can also run scripts! Check out their documentation for more.
Don't forget to check the Git documentation for more hooks.
If you're using a different solution or have any suggestions to improve this example, feel free to share it in the comments.
I hope you enjoyed this post and follow me on any platform for more.
Top comments (2)
Hi Arthur. This seems cool but if another developper commits on my project without having properly setup lefthook (lefthook install) hooks won't run, right? Thanks!
Hi Hugo! I'm glad you liked it. Yes, the hooks won't run in this case.
An improvement to this workflow is to run the checks on a pipeline. I've written about how to do it with GitHub Actions and GitLab CI.