Use husky to manage git hooks for your Dart and Flutter projects
Both Flutter and Dart have provided some convenient commands in their command line tools.
For example, flutter analyze and dart analyze can analyze code, flutter format and dart format can format code and flutter test and dart test can run tests.
How to automatically run these commands every time before making a commit to the git repository is troublesome. Yes, git hook is the first thing coming into our mind.
But git hooks exist under .git/hooks folder by default, which is not checked into git. The problem becomes how to share git hooks to teammates.
Now with husky, sharing git hooks is easy as only three steps are needed.
First, add husky to dev_dependencies in project’s pubspec.yaml
dev_dependencies:
husky: latestSecondly, install husky under your project. This will generate .husky directory under the project, make sure to check in .husky to the git.
dart pub get # or flutter pub get
dart run husky instlal # or flutter pub run husky installFinaly, add git hooks you need to .huskyfolder.
For example, add a pre-commit git hook to run dart test every time before a commit.
dart run husky add .husky/pre-commit 'dart test' # or flutter pub run husky add .husky/pre-commitNow, every time making a commit, dart test will be executed first. If dart test failed, this commit would not be committed.
If youwant to do more, just open .husky/pre-commit, and add your scripts
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
dart test
# add analyze and format check
dart analyze . --fatal-infos
dart format . --output=none --set-exit-if-changedAfter committing the .husky directory to git repository, others pull the code, run these two scripts will setup the shared git hooks locally.
dart pub get # or flutter pub get
dart run husky install # or flutter pub run husky install