如果指令指向本地模块,是否应该使用”commit replace”指令替换它?

huangapple go评论83阅读模式
英文:

Should commit replace directive if it's pointing to a local module?

问题

据我理解,replace 指令在测试已发布的第三方包时非常有用。如果我使用它来指向一个本地模块,只是为了让 Go 知道它的位置,将它提交到代码仓库是否安全?这样做有哪些潜在问题?我正在使用 v1.18.x 版本。

更新

这是我的项目结构:

app/
|---lambdaFuncOne/
|   |---go.mod
|---lambdaFuncTwo/
|   |---go.mod
|---pkg/
|   |---customOne/
|   |   |---go.mod
|---go.work

pkg/customOnelambdaFuncOnelambdaFuncTwo 中都被使用,所以它们的 go.mod 文件中有以下内容:

replace github.com/user/proj/app/pkg/customOne => ../pkg/customOne

这是一个相对路径,所以我猜它总是有效的?

go.work 文件中有以下内容:

go 1.18

use (
   ./lambdaFuncOne
   ./lambdaFuncTwo
   ./pkg/customOne 
)
英文:

As far as I understand, replace directive is useful to test published 3rd party packages. What if I'm using it to point to a local module just so Go is aware of its location, is it safe to commit it to the repo? What are the pitfalls in doing so? I'm using v1.18.x.

UPDATE

Here's how my project looks

app/
|---lambdaFuncOne/
|   |---go.mod
|---lambdaFuncTwo/
|   |---go.mod
|---pkg/
|   |---customOne/
|   |   |---go.mod
|---go.work

pkg/customOne is used in both lambdaFuncOne and lambdaFuncTwo, so their go.mod file has this

replace github.com/user/proj/app/pkg/customOne => ../pkg/customOne

It's a relative path so I guess it's always valid?

go.work has this

go 1.18

use (
   ./lambdaFuncOne
   ./lambdaFuncTwo
   ./pkg/customOne 
)

答案1

得分: 3

简而言之,只要你也提交了被重定向的内容,你就可以提交replace。我们经常在将代码推送到GitHub之前在本地工作时使用它。如果你修改了一个开源包但不想分享这些更改,也可以使用它。

最初,replace 的常见用途是临时测试或尝试一个包的替代版本。但是,许多人会意外地将临时的replace子句与go.mod一起提交,这就是为什么Go 1.18引入了工作区文件的原因。

因此,使用workspace进行本地临时实验。使用replace进行(半)永久重定向。始终提交你的go.mod文件,但不要提交工作区文件。

这是我的理解。如果我理解错了,我相信会有人纠正我。

英文:

In brief you can commit the replace as long as you also commit the things it is redirecting to. We often do this to work on a package locally before pushing to github. You might also use it if you have modified an open source package but don't want to share the changes.

Originally, a common use for replace was for temporarily testing or trying an alternative version of a package. But many people were accidentally committing go.mod with the temporary replace clause so that is why Go 1.18 introduced the workspace file.

So use workspace for local temporary experiments. Use replace for (semi)permanent redirection. Always commit your go.mod file but never commit the workspace file.

This is my understanding. I'm sure someone will correct me if I'm wrong.

huangapple
  • 本文由 发表于 2022年6月13日 16:27:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/72599789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定