Skip to content

Instantly share code, notes, and snippets.

@bgentry
Last active March 25, 2020 17:56
Show Gist options
  • Save bgentry/fd1ffef7dbde01857f66 to your computer and use it in GitHub Desktop.
Save bgentry/fd1ffef7dbde01857f66 to your computer and use it in GitHub Desktop.
Using gofmt or goimports on only my own Go files (excluding vendored deps)

In Travis CI, I want to check that my Go files are formatted properly via gofmt and goimports. During my CI builds, I only care about formatting issues in my own code, not in third-party repos.

Unfortunately, running a simple gofmt -l . in the root of my project does not work because I'm using Godep, which checks in all of my external dependencies at ./Godep/_workspace. While running go fmt ./... ignores underscore-prefixed subdirectories, the plain gofmt . does not. Neither gofmt nor goimports take the ./... arg:

➜  goimports -l ./...      
stat ./...: no such file or directory

Since I can use go list ./... to get a list of all subpackages in my project (exluding vendored imports in an underscore-prefixed directory), I'm using the following to run gofmt and goimports on each of my own Go files (including _test.go files):

$ OURGOFILES=($(go list -f '{{$p := .}}{{range $f := .GoFiles}}{{$p.Dir}}/{{$f}} {{end}} {{range $f := .TestGoFiles}}{{$p.Dir}}/{{$f}} {{end}}' ./... | xargs))
$ test -z "$(gofmt -l $OURGOFILES | tee /dev/stderr)"
$ test -z "$(goimports -l $OURGOFILES | tee /dev/stderr)"

EDIT

As Keith commented below, the following is a much simpler version. An unrelated bug caused the wildcards to not work for me the first time I tried them, but they do work.

$ dirs=$(go list -f {{.Dir}} ./...)
$ test -z "`for d in $dirs; do goimports -l $d/*.go | tee /dev/stderr; done`"
@kr
Copy link

kr commented Sep 2, 2014

How about:

$ dirs=$(go list -f {{.Dir}} ./...)
$ for d in $dirs; do goimports -w $d/*.go; done

p.s. goimports also gofmts, so you only need the one.

@VojtechVitek
Copy link

How about goimports -l ./?
// EDIT: This doesn't omit vendor/ dir.

Another solution:
goimports -d $(find . -type f -name '*.go' -not -path "./vendor/*")

@zgordan-vv
Copy link

zgordan-vv commented Mar 25, 2020

$ dirs=$(go list -f {{.Dir}} ./...)
$ for d in $dirs; do goimports -w $d/*.go; done

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment