Git Pre-Commit Hook: Unable to Run `dartfmt` (command not found) (Windows)

Viewed 1872

Ideally, I would like to have dartfmt to format my code on every commit, and I think that git hooks are ideal for this. So far, I've tried the code found in this link, but with no success, despite it appearing on multiple other websites — maybe it's outdated.

In the end, I think nothing much more complicated than this should work in most cases (inside the .git/hooks/pre-commit file):

#!/bin/bash

dartfmt -w . # or maybe `flutter format .` for Flutter

The errors I get are:

  • For dartfmt -w .: dartfmt: command not found
  • For flutter format .: find: ‘> bin [’: No such file or directory

Both of those commands do work if placed directly in the terminal.

3 Answers

to make dartfmt work, try running which dartfmt manually to get the path to the executable, and then use the absolute path when calling it in the script.

If which isn't able to find it, and assuming you know the complete path to the directory where dartfmt is located, try adding that directory to PATH in the script:

#!/bin/bash
PATH="/path/to/dart-sdk/bin:$PATH"
export PATH

Also, I'd suggest taking a moment double check what git will use for the working directory when it calls those hook scripts. There might be some undesired behavior by using . if the CWD isn't what is expected. See this post.

To format your dart code regularly, you can follow one of the two ways mentioned below:

Preferred way:

In IntelliJ Idea go to Settings -> Language & Frameworks -> Flutter -> Select Format Code on save option.

This will format your code every few seconds. This is preferred because you can customize your personal formatting settings such as max words in a line etc.

enter image description here

Alternatively

From Official website run dartfmt -w bin lib to format your code from the command line.

Add dartfmt reference in PATH, like this:

export PATH="/xxx/flutter/bin/cache/dart-sdk/bin:$PATH"
Related