在当前目录的根目录下,仅克隆Git存储库中的一个子目录

5

我在Git仓库中有几个文件夹:

folder1/suba
folder2/subb
folder3/subc

在本地,我有一个位于我的Web服务器上的公共文件夹。

http://domain.com/ 

指向该文件夹。
~/apps/appname/public

我想有效地将 folder3/subc 的内容克隆到服务器上的 public 文件夹中。我知道稀疏检出,但它会保留文件夹层次结构(例如 ~/apps/appname/public/folder3/subc)。我不想要那种层次结构,希望直接将 folder3/subc 的内容检出到 public 文件夹中。是否可能?

在本地执行 git clone 命令,然后将文件夹移动到 Web 服务器上。 - Ritesh Karwa
1
我需要定期进行git pull以更新服务器上的代码,移动它将会破坏Git功能。 - Vallieres
创建一个新目录,然后将内容复制到其中。 - Ritesh Karwa
3个回答

3
如果~/apps/appname/public在共享文件系统上,并且您的Web服务器不会更改签出的文件,则可以维护其内容的专用索引,并只使用git read-tree -um从任何提交中更新文件系统:
( 
  export GIT_INDEX_FILE=/path/to/repo/.git/appname-public-manifest
  export GIT_WORK_TREE=~/apps/appname/public
  git read-tree -um `git write-tree` master:folder3/subc
)

git write-tree会为git read-tree检查并写入一棵树,而read-tree则将现有内容和指定树之间的差异应用于索引和工作区。

如果该目录中还没有任何内容,则无需初始化,否则:

( 
  export GIT_INDEX_FILE=/path/to/repo/.git/appname-public-manifest
  export GIT_WORK_TREE=~/apps/appname/public
  git read-tree --empty   # start from nothing
  git add .               # index what's there now
)

将设置清单以匹配已有内容。


在执行导出和 git read-tree 命令之前,我需要先执行 git clone 吗? - Vallieres
你需要在某个具有文件系统访问权限的存储库中执行此操作,该存储库可以访问 ~/apps/appname/public 并且具有您获取内容的提交,但是您不需要为此使用专用存储库,只需维护单独的索引即可,该索引包含工作树中的内容(而不是存储库的默认内容)。 - jthill
GIT_INDEX_FILE文件路径名改为绝对路径,这样它就可以和git add .一起使用了,因为它首先会cd到工作树。 - jthill

0

你无法克隆子目录。但是,你可以创建浅层克隆。这些浅层克隆仅适用于部署。

也就是说,你不能使用这些克隆进行提交、拉取、推送和变基操作。浅层克隆可帮助你减少克隆的大小占用。


0

如果您使用git write-tree来自jthill答案, 请确保使用Git 2.41+。

在Git 2.41(2023年第二季度)中, "git write-tree"(man) 学会了更好地与稀疏索引一起工作。

查看 提交1a65b41 (2023年4月3日) 由Shuqi Liang (none)提交。
(由Junio C Hamano -- gitster --提交d47ee0a中合并,于2023年4月17日)

write-tree: 与稀疏索引集成

签署者:Shuqi Liang

Update 'git write-tree'(man) to allow using the sparse-index in memory without expanding to a full one.

The recursive algorithm for update_one() was already updated in 2de37c5 ("cache-tree: integrate with sparse directory entries", 2021-03-03, Git v2.32.0-rc0 -- merge listed in batch #13) to handle sparse directory entries in the index.
Hence we can just set the requires-full-index to false for "write-tree".

The p2000 tests demonstrate a ~96% execution time reduction for 'git write-tree' using a sparse index:

Test                                           before  after 
-----------------------------------------------------------------
2000.78: git write-tree (full-v3)              0.34    0.33 -2.9% 
2000.79: git write-tree (full-v4)              0.32    0.30 -6.3% 
2000.80: git write-tree (sparse-v3)            0.47    0.02 -95.8% 
2000.81: git write-tree (sparse-v4)            0.45    0.02 -95.6%

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接