Running commands against every module in a Go multi-module project
I've recently been migrating oapi-codegen to a multi-module project.
As part of it I've seen that running an innocuous "test all the packages below this one":
go test ./...
Does not work any more, as go test
will only traverse packages that the current module knows about.
We could write something like the following find
command:
# β don't use this!
find . -iname "go.mod" -exec sh -c 'cd $(dirname {}) && go test ./...' \;
However, as this StackExchange mentions, this doesn't fail if any of the exec
s fails, which means we could be lulled into a false sense of security if we're not actively watching the output of go test
for errors.
Instead, we can use find | xargs
, or in a slightly better version git ls-files | xargs
to do the same, but set a failure exit code if any commands fail:
# find the top-level, and all child Go modules
# -x to show what commands are being run, to give an idea of which module is being tested
git ls-files go.mod '**/*go.mod' -z | xargs -0 -I{} bash -xc 'cd $(dirname {}) && go test -cover ./...'