Golang中如何让模块使用包的master分支

Golang中如何让模块使用包的master分支 0

我有一个Go模块需要导入项目foo。foo的最新标签显示为v1.4。

当我在项目中执行go build时,它会将go.mod更新为:

module github.com/myid/mymod

require (
   github.com/myid/foo v1.4
)

我希望使用master分支而非v1.4标签…于是我执行了go get github.com/myid/foo@master,它下载了master分支到pkg目录,并将go.mod更新为:

require (
    github.com/myid/foo v1-XXXXXXX-XXXXXXX
)

我确认哈希值与master分支一致。

但当我再次执行go build时,它又自动切换回最新的标签版本。

如何让它持续使用master分支而不再切换回v1.4?

谢谢


更多关于Golang中如何让模块使用包的master分支的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

只需在 go.mod 文件中的仓库名称后输入 master(而不是 v…)。

更多关于Golang中如何让模块使用包的master分支的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go模块中,要让模块持续使用master分支而不是自动回退到最新标签版本,需要使用go get命令并指定@master后缀,同时需要确保go.mod文件中的依赖项被正确锁定。

以下是具体步骤:

  1. 首先,明确指定使用master分支:
go get github.com/myid/foo@master
  1. 检查go.mod文件,应该包含类似这样的条目:
require (
    github.com/myid/foo v0.0.0-20230101000000-abcdef123456
)
  1. 如果Go工具仍然自动回退到标签版本,可能是因为存在间接依赖或其他模块要求特定版本。在这种情况下,可以使用replace指令强制使用本地或特定版本:
module github.com/myid/mymod

require (
    github.com/myid/foo v0.0.0-20230101000000-abcdef123456
)

replace github.com/myid/foo => github.com/myid/foo master

或者使用具体的commit哈希:

replace github.com/myid/foo => github.com/myid/foo v0.0.0-20230101000000-abcdef123456
  1. 另一种方法是使用go.mod中的伪版本格式直接指定master分支。首先获取最新的commit哈希:
go get github.com/myid/foo@master

然后检查生成的伪版本号,确保它被正确记录在go.mod中。

  1. 如果问题仍然存在,可以尝试清理模块缓存并重新获取:
go clean -modcache
go get github.com/myid/foo@master
  1. 验证依赖版本:
go list -m all | grep foo

这个命令应该显示你正在使用基于master分支的伪版本,而不是v1.4标签。

示例go.mod文件最终可能看起来像这样:

module github.com/myid/mymod

go 1.19

require (
    github.com/myid/foo v0.0.0-20230101000000-abcdef123456
)

replace github.com/myid/foo => github.com/myid/foo v0.0.0-20230101000000-abcdef123456

通过这种方式,Go工具链将始终使用master分支的代码,而不会自动回退到已发布的标签版本。

回到顶部