6 个最佳的 Git 仓库管理实践
Git 仓库

> 
> 抵制在 Git 中添加一些会增加管理难度的东西的冲动；这里有替代方法。
> 
> 
> 


![](/data/attachment/album/202103/13/225927c3mvm5x275vano5m.jpg "Working from home at a laptop")


有权访问源代码使对安全性的分析以及应用程序的安全成为可能。但是，如果没有人真正看过代码，问题就不会被发现，即使人们主动地看代码，通常也要看很多东西。幸运的是，GitHub 拥有一个活跃的安全团队，最近，他们 [发现了已提交到多个 Git 仓库中的特洛伊木马病毒](https://securitylab.github.com/research/octopus-scanner-malware-open-source-supply-chain/)，甚至仓库的所有者也偷偷溜走了。尽管我们无法控制其他人如何管理自己的仓库，但我们可以从他们的错误中吸取教训。为此，本文回顾了将文件添加到自己的仓库中的一些最佳实践。


### 了解你的仓库


![Git 仓库终端](/data/attachment/album/202103/13/225940n43xi8xzq8pq3i3e.png "Git repository ")


这对于安全的 Git 仓库来可以说是头号规则。作为项目维护者，无论是你自己创建的还是采用别人的，你的工作是了解自己仓库中的内容。你可能无法记住代码库中每一个文件，但是你需要了解你所管理的内容的基本组成部分。如果在几十个合并后出现一个游离的文件，你会很容易地发现它，因为你不知道它的用途，你需要检查它来刷新你的记忆。发生这种情况时，请查看该文件，并确保准确了解为什么它是必要的。


### 禁止二进制大文件


![终端中 Git 的二进制检查命令](/data/attachment/album/202103/13/225940tbbb6u8tnitvenoz.jpg "Git binary check")


Git 是为文本而生的，无论是用纯文本编写的 C 或 Python 还是 Java 文本，亦或是 JSON、YAML、XML、Markdown、HTML 或类似的文本。Git 对于二进制文件不是很理想。


两者之间的区别是：



```
$ cat hello.txt
This is plain text.
It's readable by humans and machines alike.
Git knows how to version this.

$ git diff hello.txt
diff --git a/hello.txt b/hello.txt
index f227cc3..0d85b44 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1,2 +1,3 @@
 This is plain text.
+It's readable by humans and machines alike.
 Git knows how to version this.

```

和



```
$ git diff pixel.png
diff --git a/pixel.png b/pixel.png
index 563235a..7aab7bc 100644
Binary files a/pixel.png and b/pixel.png differ

$ cat pixel.png
�PNG
▒
IHDR7n�$gAMA��
              �abKGD݊�tIME�

                          -2R��
IDA�c`�!�3%tEXtdate:create2020-06-11T11:45:04+12:00��r.%tEXtdate:modify2020-06-11T11:45:04+12:00��ʒIEND�B`�

```

二进制文件中的数据不能像纯文本一样被解析，因此，如果二进制文件发生任何更改，则必须重写整个内容。一个版本与另一个版本之间唯一的区别就是全部不同，这会快速增加仓库大小。


更糟糕的是，Git 仓库维护者无法合理地审计二进制数据。这违反了头号规则：应该对仓库的内容了如指掌。


除了常用的 [POSIX](https://opensource.com/article/19/7/what-posix-richard-stallman-explains) 工具之外，你还可以使用 `git diff` 检测二进制文件。当你尝试使用 `--numstat` 选项来比较二进制文件时，Git 返回空结果：



```
$ git diff --numstat /dev/null pixel.png | tee
-     -   /dev/null => pixel.png
$ git diff --numstat /dev/null file.txt | tee
5788  0   /dev/null => list.txt

```

如果你正在考虑将二进制大文件（BLOB）提交到仓库，请停下来先思考一下。如果它是二进制文件，那它是由什么生成的。是否有充分的理由不在构建时生成它们，而是将它们提交到仓库？如果你认为提交二进制数据是有意义的，请确保在 `README` 文件或类似文件中指明二进制文件的位置、为什么是二进制文件的原因以及更新它们的协议是什么。必须谨慎对其更新，因为你每提交一个二进制大文件的变化，它的存储空间实际上都会加倍。


### 让第三方库留在第三方


第三方库也不例外。尽管它是开源的众多优点之一，你可以不受限制地重用和重新分发不是你编写的代码，但是有很多充分的理由不把第三方库存储在你自己的仓库中。首先，除非你自己检查了所有代码（以及将来的合并），否则你不能为第三方完全担保。其次，当你将第三方库复制到你的 Git 仓库中时，会将焦点从真正的上游源代码中分离出来。从技术上讲，对库有信心的人只对该库的主副本有把握，而不是对随机仓库的副本有把握。如果你需要锁定特定版本的库，请给开发者提供一个合理的项目所需的发布 URL，或者使用 [Git 子模块](https://git-scm.com/book/en/v2/Git-Tools-Submodules)。


### 抵制盲目的 git add


![Git 手动添加命令终端中](/data/attachment/album/202103/13/225940s8v8ushl38fzz885.jpg "Git manual add")


如果你的项目已编译，请抵制住使用 `git add .` 的冲动（其中 `.` 是当前目录或特定文件夹的路径），因为这是一种添加任何新东西的简单方法。如果你不是手动编译项目，而是使用 IDE 为你管理项目，这一点尤其重要。用 IDE 管理项目时，跟踪添加到仓库中的内容会非常困难，因此仅添加你实际编写的内容非常重要，而不是添加项目文件夹中出现的任何新对象。


如果你使用了 `git add .`，请在推送之前检查暂存区里的内容。如果在运行 `make clean` 或等效命令后，执行 `git status` 时在项目文件夹中看到一个陌生的对象，请找出它的来源，以及为什么仍然在项目的目录中。这是一种罕见的构建工件，不会在编译期间重新生成，因此在提交前请三思。


### 使用 Git ignore


![终端中的  命令](/data/attachment/album/202103/13/225941q00e77a0wk4dz38a.jpg "Git ignore")


许多为程序员打造的便利也非常杂乱。任何项目的典型项目目录，无论是编程的，还是艺术的或其他的，到处都是隐藏的文件、元数据和遗留的工件。你可以尝试忽略这些对象，但是 `git status` 中的提示越多，你错过某件事的可能性就越大。


你可以通过维护一个良好的 `gitignore` 文件来为你过滤掉这种噪音。因为这是使用 Git 的用户的共同要求，所以有一些入门级的 `gitignore` 文件。[Github.com/github/gitignore](https://github.com/github/gitignore) 提供了几个专门创建的 `gitignore` 文件，你可以下载这些文件并将其放置到自己的项目中，[Gitlab.com](https://about.gitlab.com/releases/2016/05/22/gitlab-8-8-released) 在几年前就将`gitignore` 模板集成到了仓库创建工作流程中。使用这些模板来帮助你为项目创建适合的 `gitignore` 策略并遵守它。


### 查看合并请求


![Git 合并请求](/data/attachment/album/202103/13/225941xzydtc355g3i3fz5.png "Git merge request")


当你通过电子邮件收到一个合并/拉取请求或补丁文件时，不要只是为了确保它能正常工作而进行测试。你的工作是阅读进入代码库的新代码，并了解其是如何产生结果的。如果你不同意这个实现，或者更糟的是，你不理解这个实现，请向提交该实现的人发送消息，并要求其进行说明。质疑那些希望成为版本库永久成员的代码并不是一种社交失误，但如果你不知道你把什么合并到用户使用的代码中，那就是违反了你和用户之间的社交契约。


### Git 责任


社区致力于开源软件良好的安全性。不要鼓励你的仓库中不良的 Git 实践，也不要忽视你克隆的仓库中的安全威胁。Git 功能强大，但它仍然只是一个计算机程序，因此要以人为本，确保每个人的安全。




---


via: <https://opensource.com/article/20/7/git-repos-best-practices>


作者：[Seth Kenlon](https://opensource.com/users/seth) 选题：[lujun9972](https://github.com/lujun9972) 译者：[stevenzdg988](https://github.com/stevenzdg988) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Having access to source code makes it possible to analyze the security and safety of applications. But if nobody actually looks at the code, the issues won’t get caught, and even when people are actively looking at code, there’s usually quite a lot to look at. Fortunately, GitHub has an active security team, and recently, they [revealed a Trojan that had been committed into several Git repositories](https://securitylab.github.com/research/octopus-scanner-malware-open-source-supply-chain/), having snuck past even the repo owners. While we can’t control how other people manage their own repositories, we can learn from their mistakes. To that end, this article reviews some of the best practices when it comes to adding files to your own repositories.

## Know your repo

![Git repository Git repository terminal](https://opensource.com/sites/default/files/uploads/git_repo.png)

This is arguably Rule Zero for a secure Git repository. As a project maintainer, whether you started it yourself or you’ve adopted it from someone else, it’s your job to know the contents of your own repository. You might not have a memorized list of every file in your codebase, but you need to know the basic components of what you’re managing. Should a stray file appear after a few dozen merges, you’ll be able to spot it easily because you won’t know what it’s for, and you’ll need to inspect it to refresh your memory. When that happens, review the file and make sure you understand exactly why it’s necessary.

## Ban binary blobs

![Git binary check Git binary check command in terminal](https://opensource.com/sites/default/files/uploads/git-binary-check.jpg)

Git is meant for text, whether it’s C or Python or Java written in plain text, or JSON, YAML, XML, Markdown, HTML, or something similar. Git isn’t ideal for binary files.

It’s the difference between this:

```
$ cat hello.txt
This is plain text.
It's readable by humans and machines alike.
Git knows how to version this.
$ git diff hello.txt
diff --git a/hello.txt b/hello.txt
index f227cc3..0d85b44 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1,2 +1,3 @@
This is plain text.
+It's readable by humans and machines alike.
Git knows how to version this.
```


and this:

```
$ git diff pixel.png
diff --git a/pixel.png b/pixel.png
index 563235a..7aab7bc 100644
Binary files a/pixel.png and b/pixel.png differ
$ cat pixel.png
�PNG
▒
IHDR7n�$gAMA��
�abKGD݊�tIME�
-2R��
IDA�c`�!�3%tEXtdate:create2020-06-11T11:45:04+12:00��r.%tEXtdate:modify2020-06-11T11:45:04+12:00��ʒIEND�B`�
```


The data in a binary file can’t be parsed in the same way plain text can be parsed, so if anything is changed in a binary file, the whole thing must be rewritten. The only difference between one version and the other is everything, which adds up quickly.

Worse still, binary data can’t be reasonably audited by you, the Git repository maintainer. That’s a violation of Rule Zero: know what’s in your repository.

In addition to the usual [POSIX](https://opensource.com/article/19/7/what-posix-richard-stallman-explains) tools, you can detect binaries using `git diff`

. When you try to diff a binary file using the `--numstat`

option, Git returns a null result:

```
$ git diff --numstat /dev/null pixel.png | tee
- - /dev/null => pixel.png
$ git diff --numstat /dev/null file.txt | tee
5788 0 /dev/null => list.txt
```



If you’re considering committing binary blobs to your repository, stop and think about it first. If it’s binary, it was generated by something. Is there a good reason not to generate them at build time instead of committing them to your repo? Should you decide it does make sense to commit binary data, make sure you identify, in a README file or similar, where the binary files are, why they’re binary, and what the protocol is for updating them. Updates must be performed sparingly, because, for every change you commit to a binary blob, the storage space for that blob effectively doubles.

## Keep third-party libraries third-party

Third-party libraries are no exception to this rule. While it’s one of the many benefits of open source that you can freely re-use and re-distribute code you didn’t write, there are many good reasons not to house a third-party library in your own repository. First of all, you can’t exactly vouch for a third party, unless you’ve reviewed all of its code (and future merges) yourself. Secondly, when you copy third party libraries into your Git repo, it splinters focus away from the true upstream source. Someone confident in the library is technically only confident in the master copy of the library, not in a copy lying around in a random repo. If you need to lock into a specific version of a library, either provide developers with a reasonable URL the release your project needs or else use [Git Submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules).

## Resist a blind git add

![Git manual add Git manual add command in terminal](https://opensource.com/sites/default/files/uploads/git-cola-manual-add.jpg)

If your project is compiled, resist the urge to use `git add .`

(where `.`

is either the current directory or the path to a specific folder) as an easy way to add anything and everything new. This is especially important if you’re not manually compiling your project, but are using an IDE to manage your project for you. It can be extremely difficult to track what’s gotten added to your repository when an IDE manages your project, so it’s important to only add what you’ve actually written and not any new object that pops up in your project folder.

If you do use `git add .`

, review what’s in staging before you push. If you see an unfamiliar object in your project folder when you do a `git status`

, find out where it came from and why it’s still in your project directory after you’ve run a `make clean`

or equivalent command. It’s a rare build artifact that won’t regenerate during compilation, so think twice before committing it.

## Use Git ignore

![Git ignore Git ignore command in terminal](https://opensource.com/sites/default/files/uploads/git-ignore.jpg)

Many of the conveniences built for programmers are also very noisy. The typical project directory for any project, programming, or artistic or otherwise, is littered with hidden files, metadata, and leftover artifacts. You can try to ignore these objects, but the more noise there is in your `git status`

, the more likely you are to miss something.

You can Git filter out this noise for you by maintaining a good gitignore file. Because that’s a common requirement for anyone using Git, there are a few starter gitignore files available. [Github.com/github/gitignore](https://github.com/github/gitignore) offers several purpose-built gitignore files you can download and place into your own project, and [Gitlab.com](https://about.gitlab.com/releases/2016/05/22/gitlab-8-8-released) integrated gitignore templates into the repo creation workflow several years ago. Use these to help you build a reasonable gitignore policy for your project, and stick to it.

## Review merge requests

![Git merge request Git merge request](https://opensource.com/sites/default/files/uploads/git_merge_request.png)

When you get a merge or pull request or a patch file through email, don’t just test it to make sure it works. It’s your job to read new code coming into your codebase and to understand how it produces the result it does. If you disagree with the implementation, or worse, you don’t comprehend the implementation, send a message back to the person submitting it and ask for clarification. It’s not a social faux pas to question code looking to become a permanent fixture in your repository, but it’s a breach of your social contract with your users to not know what you merge into the code they’ll be using.

## Git responsible

Good software security in open source is a community effort. Don’t encourage poor Git practices in your repositories, and don’t overlook a security threat in repositories you clone. Git is powerful, but it’s still just a computer program, so be the human in the equation and keep everyone safe.

## 3 Comments