如何 gitignore Go 二进制文件?

How to gitignore Go binaries?

我有一个这样的 .gitignore 文件:

# no binaries
*/
!*.go/
!.gitignore

我认为*/意味着忽略所有子目录中的所有文件(所以每个文件),!*.go/意味着不忽略所有子目录中的所有*.go文件,!.gitignore表示不忽略.gitignore

但是,我现在遇到的问题是,当我在子目录中创建新的 *.go 文件时,它现在被忽略了。

如何正确地 git 忽略所有已编译的二进制文件,但不忽略 *.go 个文件?

我现在有

**/*  
!**/*.go
!.gitignore

但它仍然忽略了ch1 目录中的所有*.go 文件。还有其他人有想法吗?

您需要使用:

**/*.go

** 用于忽略任何文件夹中的文件,而不仅仅是当前文件夹中的文件。


git v2.7 中修复了一个小错误:

Allow a later !/abc/def to override an earlier /abc that
appears in the same .gitignore file to make it easier to express
everything in /abc directory is ignored, except for ....


来自 .gitignore 文档:

Two consecutive asterisks (**) in patterns matched against full pathname may have special meaning:

Leading **

A leading ** followed by a slash means match in all directories.
For example, **/foo matches file or directory foo anywhere, the same as pattern foo.
**/foo/bar matches file or directory "bar" anywhere that is directly under directory foo.

Trailing **

A trailing /** matches everything inside.
For example, abc/** matches all files inside directory abc, relative to the location of the .gitignore file, with infinite depth.

/**/

A slash followed by two consecutive asterisks then a slash matches zero or more directories.
For example, a/**/b matches a/b, a/x/b, a/x/y/b and so on.

这将忽略除 .go 文件之外的所有内容,并且也适用于子目录:

**/*
!**/*.go
!**/

您可能还想查看 this question,它问的问题非常相似。

默认情况下,Golang 编译器将以包含 .go 源文件的文件夹名称命名二进制文件。在您的 IDE 中,您可以使用构建选项指定 golang 编译命令。在我的例子中,当我在 OSX 上编译我的 .go 源文件时,我已经将我的 IDE 指定为 运行:

"env GOOS=darwin GOARCH=amd64 go build -v -o bin/$(basename $(pwd)) && go test -v && go vet"

请注意,在我的 go build 中,我使用 -o 指定二进制输出路径,并告诉编译器将所有二进制文件写入当前目录中的子文件夹 bin/ 并命名带有项目文件夹名称的二进制文件。然后在项目文件夹中的 .gitignore 文件中,添加 bin/* 并且 git 将忽略 bin/ 子文件夹中的所有文件。