我有一个 github 仓库 github.com/user/somerepo .
我通过执行 go mod init **github.com/user/somerepo**
来初始化它
我需要更改此依赖项并使其指向另一个 github 存储库。比方说: github.com/user/a-different-repo .
是否有任何 go 命令可以更新所有文件中的所有导入语句?
最佳答案
go mod edit -replace
是你的 friend 。
来自文档(Source):
The -replace=old[@v]=new[@v] flag adds a replacement of the given module path and version pair. If the @v in old@v is omitted, a replacement without a version on the left side is added,
这是重要的部分:
which applies to all versions of the old module path. If the @v in new@v is omitted, the new path should be a local module root directory, not a module path. Note that -replace overrides any redundant replacements for old[@v], so omitting @v will drop existing replacements for specific versions.
这里是 AddReplace func它负责更换。
现在要实现它,您的每个存储库都必须映射到您的 GOPATH。
对 GOPATH 的一点记忆:
当您希望存储库成为“go gettable”包时,您应该将此存储库映射到您的 GOPATH。
As explained here当你这样做
go get
,它将首先在您的 $GOPATH
中查找获取软件包的最新版本(或者如果您在 go.mod 文件中指定了特定版本)然后您可以通过执行以下命令来实现您的编辑:
go mod edit -replace github.com/UserA/foo@v0.1=github.com/UserA/bar@v0.1
另一种方法(也许更好)是在 go.mod 文件中执行此操作,如下所示:
module foo.bar
replace github.com/UserA/foo => github.com/UserA/bar
require (
github.com/UserA/foo v0.0.1
)
当然,这只有在每个存储库都映射到您的 GOPATH 时才有效。
更多解释请参见此处:when-should-i-use-the-replace-directive
关于go - 如何更改 Go 模块路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62243083/