Running commands against every module in a Go multi-module project

Featured image for sharing metadata for article

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 execs 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 ./...'

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #go.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.