如何正确获取 go build 的 return 代码?

How to properly get return code of go build?

我想将 go build 添加到预提交挂钩中,以免发布无法构建的代码。

如果构建成功,我想继续提交,否则失败并拒绝提交。

我该如何正确操作?

任何 pre-commit 钩子都将由 git bash 执行(即使在 Windows 上),因此您可以通过常规 bash 编写脚本脚本。

Git Hooks

Exiting non-zero from this hook aborts the commit, although you can bypass it with git commit --no-verify.

#!/bin/bash
set -e
go build

(来自“Checking Bash exit status of several commands efficiently”)
这样,您可以链接多个命令(如 go vet, other go linters)。如果其中任何一个失败,pre-commit 挂钩将阻止提交。