Formatting Dart code before every git commit

Dart's dartfmt tool is a really neat utility to automatically format your code. Use the dartfmt tool in your workflow to ensure your code complies with the Dart style guide.

Of course, you don't want to manually run dartfmt. Instead, you want to automate it. Use git's pre-commit hook to ensure your code is formatted, before it is committed.

Add the following code to your .git/hooks/pre-commit script for your local repo, and make sure the script is executable.

#!/bin/bash

DARTFMT_OUTPUT=`dartfmt -w . | grep Formatted`

if [ -n "$DARTFMT_OUTPUT" ]; then
  echo $DARTFMT_OUTPUT
  echo "Re-attempt commit."
  exit 1
else
  echo "All Dart files formatted correctly. Yay!"
  exit 0

fi

If your code needs formatting, it will be formatted and written to disk. The commit will fail, so you have a chance to inspect the changes.

You can enforce formatting with your Continuous Integration system. Try these instructions to use dartfmt with Travis CI, and fail a build if a file isn't formatted.

Have you integrated dartfmt into your workflow? Let us know in the comments below!

Popular posts from this blog

Lists and arrays in Dart

Converting Array to List in Scala

Null-aware operators in Dart