概述

最近有同事做了一个简单的分享,其中介绍到了一个 bare repo 的东西,使用 Git 也有些年头了,但是还真对 Bare Repo 没有印象,所以就简单了解了一下。

什么是 bare repo

对于一个常见的 Git 项目,我们知道在项目的目录中有一个目录 .git,然后其他才是我们的项目文件。但是,对于 Bare Repository(裸仓库),它却是一个没有工作目录(working directory)的 Git 仓库,对比一下一个普通的 Git 项目和 Bare Repo 就会发现,Bare Repo 的目录就是 Git 项目中的 .git 目录下的内容:

  1. [root@liqiang.io]# tree -d # bare repo 根目录
  2. .
  3. ├── branches
  4. ├── hooks
  5. ├── info
  6. ├── objects
  7. └── refs
  8. [root@liqiang.io]# tree -d .git
  9. .git
  10. ├── branches
  11. ├── hooks
  12. ├── info
  13. ├── logs
  14. ├── objects
  15. └── refs

从这里可以看到,Bare Repo 就是没有 working directory(工作目录)的一个 Git 项目,那么它有什么用呢?

Bare Repository 通常用于共享、协作和作为中央存储库(central repository),也就是说经常用作服务端使用。

创建 Bare Repository

创建 Bare Repository 可以直接在 git init 命令中使用--bare选项,例如:

  1. [root@liqiang.io]# git init --bare test-repo.git

这将创建一个名为 test-repo.git 的Bare Repository。

在协作和远程协同工作中,开发者通常将他们的更改推送到 Bare Repository,而其他开发者则从 Bare Repository 拉取最新的更改。这种中央存储库的模型是 Git 中常见的一种工作流程。

使用 bare repo

其他人推送到 Bare Repository(裸仓库)时,通常需要使用 git push 命令。推送的目标是 Bare Repository 的地址,通常是通过 SSH 或 HTTP 协议访问的 URL。

一般的操作过程为:

  1. 在克隆 Bare Repo

    在本地仓库中,其他人可以将 Bare Repo 克隆过来:

    1. [root@liqiang.io]# git clone /tmp/bare-repo/test-repo.git

    这和平时使用远程的 Repo 没有太大区别。

  2. 创建本地分支并提交更改:

    在本地仓库中创建一个修改,并且进行提交。例如:

    1. [root@liqiang.io]# echo "This is a test file." > test.txt
    2. [root@liqiang.io]# git add test.txt
    3. [root@liqiang.io]# git commit -m "Initial commit."
    4. [root@liqiang.io]# git push origin master
  3. 推送更改到 Bare Repository:

    使用 git push 命令将本地的更改推送到 Bare Repository。通常,推送的命令如下:

    1. [root@liqiang.io]# git push origin master

这就是一个简单实用 Bare Repo 的实例了。