VMx

vmx.im
啥都学一点的填坑人
  1. 首页
  2. 未分类
  3. 正文

golang - 将顶级模块及其子模块之一作为单独的版本分别导入时,如何解决冲突的go模块依赖关系?

2021年3月19日 1782点热度 0人点赞 0条评论

我的项目中有两个依赖项。
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中整个仓库的文件内容,包括带有自己的api文件的go.mod文件夹。
${GOPATH}/pkg/mod/github.com/shared/dependency/api@v1.2.0:

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

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

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)

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

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

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

 

最佳答案

先使用

go mod tidy

如果不能解决,继续:

原来的问题是,依赖项之一是引用的github.com/shared/dependency/api版本是前置模块。

这导致go工具具有一个模块,该模块引用了github.com/shared/dependency/api子模块,而且还为该模块提供了黑匣子,用于导入整个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 +)。

Post Views: 1,248
标签: 暂无
最后更新:2021年3月19日

huifei

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2021 vmx.im. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang