当顶级模块及其子模块之一作为单独的版本单独导入时,如何解决 go 模块依赖冲突的问题?



我的项目中有两个依赖项。

go.mod

module github.com/test-org/test-repo
go 1.12
require (
github.com/foo/bar v1.0.0
github.com/raz/mataz v1.0.0
)

运行go mod download后,这两个依赖项会导致下载两个不同版本的github.com/shared/dependency。有趣的是,github.com/shared/dependency包含子模块,例如:

dependency
-- go.mod
-- api
-- go.mod

检查下载的模块显示两个版本已下载到我的本地计算机:

ls ${GOPATH}/pkg/mod/github.com/shared

[dir] dependency    [dir] dependency@v1.1.0

ls ${GOPATH}/pkg/mod/github.com/shared/dependency

[dir] api@v1.2.0

查看这些目录的内容:

${GOPATH}/pkg/mod/github.com/shared/dependency@v1.1.0

v1.1.0 中整个仓库的文件内容,包括带有自己的go.mod文件的api文件夹。

${GOPATH}/pkg/mod/github.com/shared/dependency/api@v1.2.0

v1.2.0 中存储库的api文件夹的文件内容,包括go.mod文件。


最后,我的test-repo中有一个具有以下设置的.go文件:

package test-package
import (
"github.com/foo/bar"
)
func MyFunc() {...bar.NewBar()...}

当我尝试运行MyFunc测试(存在于其他地方(时,我收到一条unknown import path...ambiguous import...错误消息。

例如go test github.com/test-org/test-repo/test-package -test.run=TestMyFunc -v

unknown import path "github.com/shared/dependency/api": ambiguous import: found github.com/shared/dependency/api in multiple modules:
github.com/shared/dependency v1.1.0 (${GOPATH}/pkg/mod/github.com/shared/dependency@v1.1.0/api)
github.com/shared/dependency v1.2.0 (${GOPATH}/pkg/mod/github.com/shared/dependency/api@v1.2.0)

该错误指向github.com/foo/bar存储库中.go文件导入github.com/shared/dependency/apiimport行。它不知道在我的本地${GOPATH}/pkg/mod文件夹中选择哪个api,因为有两个可用的版本:

  1. ${GOPATH}/pkg/mod/github.com/shared/dependency@v1.1.0/api
  2. ${GOPATH}/pkg/mod/github.com/shared/dependency/api@v1.2.0

有什么方法可以使该go test调用起作用(解决依赖冲突(?我的两个依赖项都没有明确要求下载完整的shared/dependency@v1.1.0,但由于某种原因它被拉入。如果不存在,它似乎可以解决问题。

问题原来是其中一个依赖项引用了预go-modulegithub.com/shared/dependency/api版本。

这导致 go 工具具有对github.com/shared/dependency/api子模块的模块引用,但也具有对预 go-modules 版本的整个github.com/shared/dependency存储库的黑盒导入。在这个例子中,这意味着v1.2.0有 go 模块(有一个go.mod文件(,而v1.1.0没有。

将以下行添加到我的go.mod文件中能够解决问题,并且此解决方案适用于我在此类冲突中遇到的多个依赖项:

replace (
github.com/shared/dependency => github.com/shared/dependency v1.2.0
)

请注意,此解决方案之所以有效,是因为我们强制引用共享依赖项以使用启用 go-module 的版本 (v1.2.0+(。

为了将来参考,我发现当上面的replace方法不起作用时,运行go get github.com/shared/dependency/api@latest似乎有效。

据推测,这迫使两个模块都使用最新版本的依赖项。

我只是解决了ambiguous import: found package time in multiple modules:的问题

只需删除mod文件,然后使用与任何现有模块名称不匹配的其他名称再次go mod init

go mod init time-不正确

go mod init gotime-正确

相关内容

最新更新