我在进行本地开发时使用“替换”语句。所以我的 go.mod 看起来像这样:
require (
gorm.io/gorm v1.21.11
github.com/mypackages/session v1.1.0
)
replace (
github.com/mypackages/session => ./../session
)
但是当我
git commit
我的更改并将代码部署到生产环境时,我不需要“替换”,所以我需要在每个git commit
上注释这行替换代码,然后取消注释。有没有办法在生产环境中忽略“替换”语句?
虽然@Adrian 是正确的,因为在 Go 中无法实现这一点,但我认为这个问题不是关于 Go 而更多是关于 Git。您可以使用内容过滤器忽略文件的特定部分。有关更多信息,请参见这个 SO answer。
replace
在 environment 中不能被忽略,因为它在依赖解析时间使用,该时间在构建之前,这比它在生产中执行之前很久。但要回答根本问题,不,您不能“忽略”该指令。如果它在那里,它就在那里。
有一个本地版本的 mod 文件(例如 go.local.mod)然后你可以告诉 go 命令使用它:
go build -modfile=go.local.mod main.go
您可以编写一个预提交挂钩,它将检测您的 go.mod 文件是否包含替换。
预提交挂钩代码 -> https://gist.github.com/MohitVachhani/e331321bb6f8c3e5e26b0cb4ab792c55
请检查一下,如果您有任何改进,请告诉我!
配方:
将此添加到您项目的
.git/config
[filter "goreplace"]
smudge = sed 's~//replace~replace~'
clean = sed 's~replace~//replace~'
替代添加全局:
git config --global filter.goreplace.smudge "sed 's~//replace~replace~'"
git config --global filter.goreplace.clean "sed 's~replace~//replace~'"
然后添加(到)
.gitattributes
*.mod filter=goreplace
注意它只对你有效,而不对所有贡献者有效。此外,它只会注释掉“替换”语句,您也可以将其删除,但这需要更多的 sed 魔法;)。