drxd54816
2019-08-06 23:30 阅读 149
已采纳

有没有办法一次构建多个基于Go模块的项目?

Previous to using Go modules I could compile everything in my GOPATH with go build ./....

If I try this in the root of a directory with multiple module based Go projects, it doesn't download the dependencies specified in go.mod and fails to find the packages the code depends on because it is looking for them in GOPATH.

I have 126 modules based projects and I'd rather not have to write a script to handle building them.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongweiben5229 dongweiben5229 2019-08-07 14:43

    No, there isn't a way to do this using only the go command. Scripting this or using replace directives is the way to go. A simple script might be:

    find "$(go env GOPATH)/src" \
      -name vendor -prune -o \
      -name go.mod -exec bash -c 'cd "$(dirname {})" && go build ./...' \;
    

    Each go.mod file defines a workspace, and go build, go test, go list, go get commands only apply to packages within that workspace.

    Within a module, it's possible to build packages provided by other modules. For example, if you have a module with the path example.com/foo, and you require the module example.com/bar, you can go build example.com/bar/some/pkg. However, this will not use your local copy of example.com/bar; it will download that module into your module cache ($GOPATH/pkg/mod) and will build from there.

    You can use a local copy of another module using a replace directive. This is good for short term forks and co-development of related modules (usually in the same repository). However, replace directives only apply in the module where they are written. If another module requires your module, your replace directives are ignored.

    The goal of all of this is to make builds reproducible. Developers that use your modules will only be able to download your dependencies at specific versions.

    点赞 评论 复制链接分享

相关推荐