【问题标题】:How do I clone, fetch or sparse checkout a single directory or a list of directories from git repository?如何从 git 存储库克隆、获取或稀疏检出单个目录或目录列表?
【发布时间】:2020-05-28 03:41:19
【问题描述】:

如何从 git 存储库克隆、获取或稀疏签出单个文件或目录或文件或目录列表,避免下载整个历史记录或至少保持历史下载最少?

为了方便人们登陆这里,这些是对其他类似问题的参考:

这些类似的问题很久以前就被问过了,从那时起 git 就不断发展,最终导致了大量不同的答案,有些更好,有些更糟,具体取决于所考虑的 git 版本。问题在于,上述问题中没有一个答案符合所有这些问题的所有要求,这意味着您必须阅读所有答案并在脑海中编制自己的答案,最终满足所有要求。

这里的这个问题扩展了前面提到的问题,提出了比所有其他问题加起来更灵活和更严格的要求。所以,再一次:

如何从 git 存储库克隆、获取或稀疏签出单个文件或目录或文件或目录列表,避免下载整个历史记录或至少保持历史下载最少?

【问题讨论】:

  • @phd :不,不是真的。作为您提到的答案的一部分,我们可以看到的功能拉动了所有分支的整个历史记录。我的实现只提取了一个分支的历史,而 AFAIK 只提取了历史的一角。
  • @phd :您的第二条评论的链接已损坏。
  • 链接的副本有很多答案。提到了git clone --depth 以及git clone --filter。第二个搜索链接对我有用。

标签: git git-checkout git-fetch revision-history git-sparse-checkout


【解决方案1】:

下面这个bash 函数可以解决问题。

function git_sparse_checkout {
    # git repository, e.g.: http://github.com/frgomes/bash-scripts
    local url=$1
    # directory where the repository will be downloaded, e.g.: ./build/sources
    local dir=$2
    # repository name, in general taken from the url, e.g.: bash-scripts
    local prj=$3
    # tag, e.g.: master
    local tag=$4
    [[ ( -z "$url" ) || ( -z "$dir" ) || ( -z "$prj" ) || ( -z "$tag" ) ]] && \
        echo "ERROR: git_sparse_checkout: invalid arguments" && \
        return 1
    shift; shift; shift; shift

    # Note: any remaining arguments after these above are considered as a
    # list of files or directories to be downloaded.
    
    mkdir -p ${dir}
    if [ ! -d ${dir}/${prj} ] ;then
        mkdir -p ${dir}/${prj}
        pushd ${dir}/${prj}
        git init
        git config core.sparseCheckout true
        local path="" # local scope
        for path in $* ;do
            echo "${path}" >> .git/info/sparse-checkout
        done
        git remote add origin ${url}
        git fetch --depth=1 origin ${tag}
        git checkout ${tag}
        popd
    fi
}

这是一个如何使用它的示例:

function example_download_scripts {
  url=http://github.com/frgomes/bash-scripts
  dir=$(pwd)/sources
  prj=bash-scripts
  tag=master
  git_sparse_checkout $url $dir $prj $tag "user-install/*" sysadmin-install/install-emacs.sh
}

在上面的示例中,请注意目录后面必须跟/*,并且必须在单引号或双引号之间。

更新:可以在以下位置找到改进的版本:https://github.com/frgomes/bash-scripts/blob/master/bin/git_sparse_checkout

【讨论】:

    【解决方案2】:

    如果你只想要没有历史记录的文件,你可以使用 svn:

    SUBDIR=foo
    svn export https://github.com/repository.git/trunk/$SUBDIR
    

    【讨论】:

      猜你喜欢
      • 2019-03-02
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 2012-10-23
      相关资源
      最近更新 更多