Go fmt on a whole source tree

Go

Go Problem Overview


I have a project currently organized something like this:

~/code/go
/bin
/pkg
/src
/proj/main.go
/some_package/package.go
/some_other_package/some_other_package.go

Now if I want to use the go fmt tool on my whole project it seems that the only way is to do it separately for each directory in my projects source tree:

go fmt proj
go fmt proj/package
go fmt proj/some_other_package

Is there some way to tell the fmt command to run on the whole source tree?

Go Solutions


Solution 1 - Go

You can use three dots (...) as a wildcard. So for example, the following command will format all github.com packages:

go fmt github.com/...

This wildcard also works with other go commands like go list, go get and so. There is no need to remember such an ugly find command.

Solution 2 - Go

If you use gofmt instead of go fmt, it's recursive. For example, following command

gofmt -s -w .

(notice the little dot at end) recursively formats, simplifies, and saves result into every file under current directory. I have a shell alias gf defined as gofmt -s -w . and find it quite handy.

Try gofmt -l . (list files whose formatting differs from gofmt's) first if you want :-)

Solution 3 - Go

Also, you can try to run command:

go fmt ./...

from your project directory.

Solution 4 - Go

find proj -type f -iregex '.*\.go' -exec go fmt '{}' +
Explanation
  • find proj: find everything in this directory...
    • -type f: ...that is a file
    • -iregex '.*\.go': ...and case-insensitively matches the regular expression .*\.go
  • ...and execute go fmt followed by as many matched files as the operating system can handle passing to an executable in one go.

Solution 5 - Go

if you are using GoLand IDE, right click on project and you will find Go Tools. enter image description here

Solution 6 - Go

The command gofmt ./... mentioned by some, does not work on Windows (at least on my Win7).

Instead of it, I used gofmt -d .\ which works recursively. I use the -d flag because I want to list the changes I need to make in order to pass the check.

NB: golint ./... does work on Windows, just gofmt ./... doesn't.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisView Question on Stackoverflow
Solution 1 - Gotux21bView Answer on Stackoverflow
Solution 2 - GoSong GaoView Answer on Stackoverflow
Solution 3 - Gocn007bView Answer on Stackoverflow
Solution 4 - GoicktoofayView Answer on Stackoverflow
Solution 5 - GosgauriView Answer on Stackoverflow
Solution 6 - GoCsongor HalmaiView Answer on Stackoverflow