我的Git存储库在根目录下有两个子目录:

/finisht
/static

当这是在SVN中时,/finisht在一个地方签出,而/static在其他地方签出了,如下所示:

svn co svn+ssh://admin@domain.example/home/admin/repos/finisht/static static

有没有办法用Git做到这一点?


当前回答

Git1.7.0有“稀疏签出”。看见git-config手册页中的“core.sparceCheckout”,git read树手册页中的“稀疏签出”,以及git更新索引手册页中的“跳过工作树位”。

界面不如SVN方便(例如,在初始克隆时无法进行稀疏签出),但可以构建更简单界面的基本功能现在可用。

其他回答

下面是我为单个子目录稀疏签出用例编写的shell脚本

co子目录.sh

localRepo=$1
remoteRepo=$2
subDir=$3


# Create local repository for subdirectory checkout, make it hidden to avoid having to drill down to the subfolder
mkdir ./.$localRepo
cd ./.$localRepo
git init
git remote add -f origin $remoteRepo
git config core.sparseCheckout true

# Add the subdirectory of interest to the sparse checkout.
echo $subDir >> .git/info/sparse-checkout

git pull origin master

# Create convenience symlink to the subdirectory of interest
cd ..
ln -s ./.$localRepo/$subDir $localRepo

对于macOS用户

对于zsh用户(特别是macOS用户)使用ssh克隆Repos,我只需要根据@Ciro Santilli的回答创建一个zsh命令:

要求:git的版本很重要。由于--sparse选项,它在2.25.1上不起作用。尝试将git升级到最新版本。(例如测试2.36.1)

示例用法:

git clone git@github.com:google-research/google-research.git etcmodel

代码:

function gitclone {
    readonly repo_root=${1?Usage: gitclone repo.git sub_dir}
    readonly repo_sub=${2?Usage: gitclone repo.git sub_dir}
    echo "-- Cloning $repo_root/$repo_sub"
    git clone \
      --depth 1 \
      --filter=tree:0 \
      --sparse \
      $repo_root \
    ;
    repo_folder=${repo_root#*/}
    repo_folder=${repo_folder%.*}
    cd $repo_folder
    git sparse-checkout set $repo_sub
    cd -
}


gitclone "$@"

对于其他只想从github下载文件/文件夹的用户,只需使用:

svn export <repo>/trunk/<folder>

e.g.

svn export https://github.com/lodash/lodash.com/trunk/docs

(是的,这里是svn。显然在2016年,您仍然需要svn来下载一些github文件)

提供:从GitHub repo下载单个文件夹或目录

重要信息-请确保更新github URL并将/tree/master/替换为'trunk/'。

作为bash脚本:

git-download(){
    folder=${@/tree\/master/trunk}
    folder=${folder/blob\/master/trunk}
    svn export $folder
}

笔记此方法下载文件夹,但不克隆/签出它。您不能将更改推回到存储库。另一方面,与稀疏签出或浅签出相比,这导致下载量较小。

它对我有用-(git版本2.35.1)

git init
git remote add origin <YourRepoUrl>
git config core.sparseCheckout true
git sparse-checkout set <YourSubfolderName>
git pull origin <YourBranchName>

我不知道是否有人成功拉取了特定目录,这是我的经验:gitclone--filter=blob:none--singlebranch<repo>,下载对象时立即取消,输入repo,然后gitcheckoutorigin/master<dir>,忽略错误(sha1),输入dir,对每个子目录重复签出(使用新的dir)。我设法以这种方式快速获取源文件