我有我的 Git 存储库,在根目录下有两个子目录:
/finisht
/static
这是在 SVN 中的时候, /finisht
在一个地方 checkout ,而 /static
在别处 checkout ,像这样:
svn co svn+ssh://admin@domain.example/home/admin/repos/finisht/static static
有没有办法用 Git 做到这一点?
最佳答案
您尝试执行的操作称为稀疏 checkout ,该功能已添加到 Git 1.7.0(2012 年 2 月)中。执行稀疏克隆的步骤如下:
mkdir <repo>
cd <repo>
git init
git remote add -f origin <url>
这会用您的 Remote 创建一个空的存储库,并获取所有对象但不会 check out 它们。然后做:
git config core.sparseCheckout true
现在您需要定义要实际 check out 的文件/文件夹。这是通过在 .git/info/sparse-checkout
中列出它们来完成的,例如:
echo "some/dir/" >> .git/info/sparse-checkout
echo "another/sub/tree" >> .git/info/sparse-checkout
最后但同样重要的是,用远程状态更新你的空仓库:
git pull origin master
您现在将在您的文件系统上“ checkout ”some/dir
和 another/sub/tree
的文件(这些路径仍然存在),而没有其他文件存在路径。
您可能想看看 extended tutorial你可能应该阅读官方 documentation for sparse checkout和 read-tree .
作为函数:
function git_sparse_clone() (
rurl="$1" localdir="$2" && shift 2
mkdir -p "$localdir"
cd "$localdir"
git init
git remote add -f origin "$rurl"
git config core.sparseCheckout true
# Loops over remaining args
for i; do
echo "$i" >> .git/info/sparse-checkout
done
git pull origin master
)
用法:
git_sparse_clone "http://github.com/tj/n" "./local/location" "/bin"
请注意,这仍然会从服务器下载整个存储库——只是 checkout 的大小有所减少。目前不可能只克隆一个目录。但是,如果您不需要存储库的历史记录,您至少可以通过创建浅克隆来节省带宽。参见 udondan's answer下面是关于如何结合浅层的信息 clone和稀疏 checkout 。
从 Git 2.25.0(2020 年 1 月)开始,实验性 sparse-checkout在 Git 中添加命令:
git sparse-checkout init
# same as:
# git config core.sparseCheckout true
git sparse-checkout set "A/B"
# same as:
# echo "A/B" >> .git/info/sparse-checkout
git sparse-checkout list
# same as:
# cat .git/info/sparse-checkout
关于git - 如何仅克隆 Git 存储库的子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/600079/