Git 系列（七）：使用 Git 管理二进制大对象
Git blob
通过这系列的前六篇文章，我们已经学会使用 Git 来对文本文件进行版本控制的管理。我们不禁要问，还有二进制文件呢，也可进行进行版本控制吗？答案是肯定的，Git 已经有了可以处理像多媒体文件这样的二进制大对象块（blob）的扩展。因此，今天我们会学习使用 Git 来管理所谓的二进制资产。


![](/data/attachment/album/201611/29/175130yorx11s7oo4s9r7o.png)


似乎大家都认可的事就是 Git 对于大的二进制对象文件支持得不好。要记住，二进制大对象与大文本文件是不同的。虽然 Git 对大型的文本文件版本控制毫无问题，但是对于不透明的二进制文件起不了多大作用，只能把它当作一个大的实体黑盒来提交。


设想这样的场景，有一个另人兴奋的第一人称解密游戏，您正在为它制作复杂的 3D 建模，源文件是以二进制格式保存的，最后生成一个 1GB 大小的的文件。您提交过一次，在 Git 源仓库历史中有一个 1GB 大小的新增提交。随后，您修改了下模型人物的头发造型，然后提交更新，因为 Git 并不能把头发从头部及模型中其余的部分离开来，所以您只能又提交 1GB 的量。接着，您改变了模型的眼睛颜色，提交这部分更新：又是 GB 级的提交量。对一个模型的一些微小修改，就会导致三个 GB 级的提交量。对于想对一个游戏所有资源进行版本控制这样的规模，这是个严重的问题。


不同的是如 `.obj` 这种格式的文本文件，和其它类型文件一样，都是一个提交就存储所有更新修改状态，不同的是 `.obj` 文件是一系列描述模型的纯文本行。如果您修改了该模型并保存回 `.obj` 文件，Git 可以逐行读取这两个文件，然后创建一个差异版本，得到一个相当小的提交。模型越精细，提交就越小，这就是标准的 Git 用例。虽然文件本身很大，但 Git 使用覆盖或稀疏存储的方法来构建当前数据使用状态的完整描述。


然而，不是所有的都是纯文本的，但都要使用 Git，所以需要解决方案，并且已经出现几个了。


[OSTree](https://ostree.readthedocs.io/en/latest/) 开始是作为 GNOME 项目出现的，旨在管理操作系统的二进制文件。它不适用于这里，所以我直接跳过。


[Git 大文件存储](https://git-lfs.github.com/)（LFS） 是放在 GitHub 上的一个开源项目，是从 git-media 项目中分支出来的。[git-media](https://github.com/alebedev/git-media) 和 [git-annex](https://git-annex.branchable.com/walkthrough/) 是 Git 用于管理大文件的扩展。它们是对同一问题的两种不同的解决方案，各有优点。虽然它们都不是官方的项目，但在我看来，每个都有独到之处：


* git-media 是集中模式，有一个公共资产的存储库。你可以告诉 git-media 大文件需要存储的位置，是在硬盘、服务器还是在云存储服务器，项目中的每个用户都将该位置视为大型文件的中心主存储位置。
* git-annex 侧重于分布模式。用户各自创建存储库，每个存储库都有一个存储大文件的本地目录 `.git/annex`。这些 annex 会定期同步，只要有需要，每个用户都可以访问到所有的资源。除非通过 annex-cost 特别配置，否则 git-annex 优先使用本地存储，再使用外部存储。


对于这些，我已经在生产中使用了 git-media 和 git-annex，那么下面会向你们概述其工作原理。


### git-media


git-media 是使用 Ruby 语言开发的，所以首先要安装 gem（LCTT 译注：Gem 是基于 Ruby 的一些开发工具包）。安装说明在[其网站](https://github.com/alebedev/git-media)上。想使用 git-meida 的用户都需要安装它，因为 gem 是跨平台的工具，所以在各平台都适用。


安装完 git-media 后，你需要设置一些 Git 的配置选项。在每台机器上只需要配置一次。



```
$ git config filter.media.clean "git-media filter-clean"
$ git config filter.media.smudge "git-media filter-smudge"

```

在要使用 git-media 的每个存储库中，设置一个属性以将刚刚创建的过滤器结合到要您分类为“<ruby> 媒体 <rp>  （ </rp> <rt>  media </rt> <rp>  ） </rp></ruby>”的文件类型里。别被这种术语混淆。一个更好的术语是“资产”，因为“媒体”通常的意思是音频、视频和照片，但您也可以很容易地将 3D 模型，烘焙和纹理等归类为媒体。


例如：



```
$ echo "*.mp4 filter=media -crlf" >> .gitattributes
$ echo "*.mkv filter=media -crlf" >> .gitattributes
$ echo "*.wav filter=media -crlf" >> .gitattributes
$ echo "*.flac filter=media -crlf" >> .gitattributes
$ echo "*.kra filter=media -crlf" >> .gitattributes

```

当您要<ruby> 暂存 <rp>  （ </rp> <rt>  stage </rt> <rp>  ） </rp></ruby>这些类型的文件时，文件会被复制到 `.git/media` 目录。


假设在服务器已经有了一个 Git 源仓库，最后一步就告诉源仓库“母舰”所在的位置，也就是，当媒体文件被推送给所有用户共享时，媒体文件将会存储的位置。这在仓库的 `.git/config` 文件中设置，请替换成您的用户名、主机和路径：



```
[git-media]
transport = scp
autodownload = false #默认为 true，拉取资源
scpuser = seth
scphost = example.com
scppath = /opt/jupiter.git

```

如果您的服务器上 SSH 设置比较复杂，例如使用了非标准端口或非默认 SSH 密钥文件的路径，请使用 `.ssh/config` 为主机设置默认配置。


git-media 的使用和普通文件一样，可以把普通文件和 blob 文件一样对待，一样进行 commit 操作。操作流程中唯一的不同就是，在某些时候，您应该将您的资产（或称媒体）同步到共享存储库中。


当要为团队发布资产或自己备份资料时，请使用如下命令：



```
$ git media sync

```

要用一个变更后的版本替换 git-media 中的文件时（例如，一个已经美声过的音频文件，或者一个已经完成的遮罩绘画，或者一个已经被颜色分级的视频文件），您必须明确的告诉 Git 更新该媒体。这将覆盖 git-media 不会复制远程已经存在的文件的默认设置：



```
$ git update-index --really-refresh

```

当您团队的其他成员（或是您本人，在其它机器上）克隆本仓库时，如果没有在 `.git/config` 中把 `autodownload` 选项设置为 `true` 的话，默认是不会下载资源的。但 git-media 的一个同步命令 `git media sync` 可解决所有问题。


### git-annex


git-annex 的处理流程略微的有些不同，默认是使用本地仓库的，但基本的思想都一样。您可以从你的发行版的软件仓库中安装 git-annex，或者根据需要从该网站上下载安装。与 git-media 一样，任何使用 git-annex 的用户都必须在其机器上安装它。


其初始化设置比 git-media 都简单。运行如下命令，其中替换成您的路径，就可以在您的服务器上创建好裸存储库：



```
$ git init --bare --shared /opt/jupiter.git

```

然后克隆到本地计算机，把它标记为 git-annex 的初始路径：



```
$ git clone seth@example.com:/opt/jupiter.clone
Cloning into 'jupiter.clone'... 
warning: You appear to have clonedan empty repository. 
Checking connectivity... done.
$ git annex init "seth workstation" 
init seth workstation ok

```

不要使用过滤器来区分媒体资源或大文件，您可以使用 `git annex` 命令来配置归类大文件：



```
$ git annex add bigblobfile.flac
add bigblobfile.flac
(checksum) ok
(Recording state in Git...)

```

跟普通文件一样进行提交操作：



```
$ git commit -m 'added flac source for sound fx'

```

但是推送操作是不同的，因为 `git annex` 使用自己的分支来跟踪资产。您首次推送可能需要 `-u` 选项，具体取决于您如何管理您的存储库：



```
$ git push -u origin master git-annex
To seth@example.com:/opt/jupiter.git
* [new branch] master -> master
* [new branch] git-annex -> git-annex

```

和 git-media 一样，普通的 `git push` 命令是不会拷贝资料到服务器的，仅仅只是发送了相关的消息，要真正共享文件，需要运行同步命令：



```
$ git annex sync --content

```

如果别人已经提交了共享资源，您需要拉取它们，`git annex sync` 命令将提示您要在本地检出你本机没有，但在服务器上存在的资源。


git-media 和 git-annex 都非常灵活，都可以使用本地存储库来代替服务器，所以它们也常用于管理私有的本地项目。


Git 是一个非常强大和扩展性非常强的系统应用软件，我们应该毫不犹豫的使用它。现在就开始试试吧！




---


via: <https://opensource.com/life/16/8/how-manage-binary-blobs-git-part-7>


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


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


OK
*Read:*

[Part 1: What is Git?](https://opensource.com/resources/what-is-git)*Part 2: Getting started with Git*[Part 3: Creating your first Git repository](https://opensource.com/life/16/7/creating-your-first-git-repository)*Part 4: How to restore older file versions in Git**Part 5: 3 graphical tools for Git**Part 6: How to build your own Git server**Part 7: How to manage binary blobs with Git*

In the previous six articles in this series we learned how to manage version control on text files with Git. But what about binary files? Git has extensions for handling binary blobs such as multimedia files, so today we will learn how to manage binary assets with Git.

One thing everyone seems to agree on is Git is not great for big binary blobs. Keep in mind that a binary blob is different from a large text file; you can use Git on large text files without a problem, but Git can't do much with an impervious binary file except treat it as one big solid black box and commit it as-is.

Say you have a complex 3D model for the exciting new first person puzzle game you're making, and you save it in a binary format, resulting in a 1 gigabyte file. You `git commit`

it once, adding a gigabyte to your repository's history. Later, you give the model a different hair style and commit your update; Git can't tell the hair apart from the head or the rest of the model, so you've just committed another gigabyte. Then you change the model's eye color and commit that small change: another gigabyte. That is three gigabytes for one model with a few minor changes made on a whim. Scale that across all the assets in a game, and you have a serious problem.

Contrast that to a text file like the `.obj`

format. One commit stores everything, just as with the other model, but an `.obj`

file is a series of lines of plain text describing the vertices of a model. If you modify the model and save it back out to `.obj`

, Git can read the two files line by line, create a diff of the changes, and process a fairly small commit. The more refined the model becomes, the smaller the commits get, and it's a standard Git use case. It is a big file, but it uses a kind of overlay or sparse storage method to build a complete picture of the current state of your data.

However, not everything works in plain text, and these days everyone wants to work with Git. A solution was required, and several have surfaced.

[Git Large File Storage](https://git-lfs.github.com) (LFS) is an open source project from GitHub that began life as a fork of git-media. Git-media and [git-annex](https://git-annex.branchable.com/walkthrough/) are extensions to Git meant to manage large files. They are two different approaches to the same problem, and they each have advantages. These aren't official statements from the projects themselves, but in my experience, the unique aspects of each are:

-
`Git-annex`

favors a distributed model; you and your users create repositories, and each repository gets a local`.git/annex`

directory where big files are stored. The annexes are synchronized regularly so that all assets are available to all users as needed. Unless configured otherwise with`annex-cost`

,`git-annex`

prefers local storage before off-site storage. -
`Git-portal`

is also distributed, and like Git-annex has the option to synchronize to a central location. It uses common utilities that you likely already have installed (specifally Bash, Git, rsync). -
`Git-LFS`

is a centralised model, a repository for common assets. You tell Git-LFS where your large files are stored, whether that's a hard drive, a server, or a cloud storage service, and each user on your project treats that location as the central master location for large assets.

## git-portal

Git-portal offers simplified blob management for Git using standard UNIX tools like Bash, Git itself, and optionally rsync. It copies big binary files to local or remote storage, replacing them with symlinks that you can commit along with the rest of your project files.

Git-portal is simple at the expense of being a little more manual sometimes (it doesn't have automated garbage collection, for instance). It's ideal for users who need to manage big files that aren't normally agreeable to Git management, but don't want to have to learn a whole new system. Git-portal mimics Git itself, so there's only a minimal learning curve.

You can install Git-portal from its project page on [Gitlab](https://gitlab.com/slackermedia/git-portal).

All Git-portal commands mirror Git itself. To use Git-portal in a project:

`$ git-portal init`


To add a file:

`$ git-portal add bigfile.png`


Once a file's been "sent through the portal" (in the project's terminology), your interactions with Git are exactly the same as usual. You add files as usual, relatively oblivious to the fact that some of them are secretly symlinks to the **_portal **directory.

Everything in the **_portal **directory, which is entirely ignored by Git, can be backed-up separately to any kind of storage you like, whether it's a USB drive or a remote server. Because Git-portal provides some Git hooks (automated scripts triggered by specific Git actions, like a push or a pull), you can even set up a special Git remote entry so your _portal directory is synchronized automatically with a remote location:

`$ git remote add _portal alice@myserver.com:/home/alice/umbrella.git/_portal`


Git-portal has the advantage of being a simple and Linux-native system. With a fairly minimal stack of common utilities and only a few extra commands to remember, you can manage large project dependencies and even share them between collaborators. Git-portal has been used on media projects, indie video games, and a gaming blog to manage everything from minor splash images to big PDFs to even bigger 3d models.

## git-annex

`git-annex`

has a slightly different workflow, and defaults to local repositories, but the basic ideas are the same. You should be able to install `git-annex`

from your distribution's repository, or you can get it from the website as needed. As with `git-media`

, any user using `git-annex`

must install it on their machine.

The initial setup is simpler than `git-media`

. To create a bare repository on your server run this command, substituting your own path:

`$ git init --bare --shared /opt/jupiter.git`


Then clone it onto your local computer, and mark it as a `git-annex`

location:

```
$ git clone seth@example.com:/opt/jupiter.clone
Cloning into 'jupiter.clone'... warning: You appear to have cloned
an empty repository. Checking connectivity... done.
$ git annex init "seth workstation" init seth workstation ok
```


Rather than using filters to identify media assets or large files, you configure what gets classified as a large file by using the `git annex`

command:

```
$ git annex add bigblobfile.flac
add bigblobfile.flac (checksum) ok
(Recording state in Git...)
```


Committing is done as usual:

`$ git commit -m 'added flac source for sound fx'`


But pushing is different, because `git annex`

uses its own branch to track assets. The first push you make may need the `-u`

option, depending on how you manage your repository:

```
$ git push -u origin master git-annex
To seth@example.com:/opt/jupiter.git
* [new branch] master -> master
* [new branch] git-annex -> git-annex
```


As with `git-media`

, a normal `git push`

does *not* copy your assets to the server, it only sends information about the media. When you're ready to share your assets with the rest of the team, run the sync command:

`$ git annex sync --content`


If someone else has shared assets to the server and you need to pull them, `git annex sync`

will prompt your local checkout to pull assets that are not present on your machine, but that exist on the server.

Git annex is a finely-tuned solution, flexible and user-friendly. It's robust and well-tested.

## git-lfs

`git-lfs`

is written in Go, and you can install it from source code or as a downloadable binary. Instructions are on the [website](https://git-lfs.github.com). Each user who wants to use `git-lfs`

needs to install it, but it is cross-platform, so that generally doesn't pose a problem.

After installing `git-lfs`

, you can set what filetypes you want Git to ignore and Git-LFS to manage. For example, for Git-LFS to track all** .png** files:

`$ git lfs track "*.png"`


Any time you add a filetype for Git-LFS tracking, you must add and then commit the file **.gitattributes**:

```
$ git add .gitattributes
$ git commit -m "LFS track *.png"
```


When you stage a file of those types, the file is copied to `.git/lfs`

.

Git-LFS is a project by Github and it's heavily tied in to Github's infrastructure. If you want to run a Git server that allows for Git-LFS integration, you can study up on the [Git-LFS server specification](https://github.com/git-lfs/lfs-test-server) (also written in Go) and implement the API.

Both `git-portal`

and `git-annex`

are flexible and can use local repositories instead of a server, so they're just as useful for managing private local projects, too.

## Large files and Git

While Git is meant for text files, that doesn't mean you can't use it just because you have binary assets. There are very good solutions to help you manage large files. There really aren't many excuses for not using Git if you want to, so try it out today!

## 8 Comments