如何从GitHub上托管的远程Git repo中仅下载特定文件夹或目录?

举个GitHub repo的例子:

git@github.com:foobar/Test.git

其目录结构:

Test/
├── foo/ 
│   ├── a.py
│   └── b.py   
└── bar/
    ├── c.py
    └── d.py

我只想下载foo文件夹,而不是克隆整个测试项目。


当前回答

试试看。

https://github.com/twfb/git-directory-download

usage: gitd [-h] [-u URL] [-r] [-p] [--proxy PROXY]

optional arguments:
  -h, --help         show this help message and exit
  -u URL, --url URL  github url, split by ",", example: "https://x, http://y"
  -r, --raw          download from raw url
  -p, --parse        download by parsing html
  --proxy PROXY      proxy config, example "socks5://127.0.0.1:7891"

Example:
  1. download by raw url: gitd -u "https://github.com/twfb/git-directory-download"
  2. download by raw url: gitd -r -u "https://github.com/twfb/git-directory-download"
  3. dowmload by parsing: gitd -p -u "https://github.com/twfb/git-directory-download"
  4. download by raw url with proxy: gitd -r -u "https://github.com/twfb/git-directory-download" --proxy "socks5://127.0.0.1:7891"

其他回答

你不能;不同于Subversion,每个子目录都可以单独检出,Git在整个存储库的基础上运行。

对于需要更细粒度访问的项目,可以使用子模块——每个子模块都是一个单独的Git项目,因此可以单独克隆。

可以想象,Git前端(例如GitHub的web界面或gitweb)可以选择为您提供一个界面来提取给定的文件夹,但据我所知,他们中没有一个这样做(尽管他们确实允许您下载单个文件,所以如果文件夹不包含太多文件,这是一个选项)

编辑-GitHub实际上提供了通过SVN的访问,这将允许您执行此操作(根据评论)。看见https://github.com/blog/1438-improved-svn-here-to-stay-old-svn-going-away有关如何执行此操作的最新说明

我找到的最简单的方法是如何仅克隆Git存储库的子目录?

我在gitclone命令中添加了-b<branch>--singlebranch以下载特定的分支。所以我使用的命令是:

git clone --depth 1 --single-branch -b <branch> --filter=blob:none --sparse <url>
git sparse-checkout set <directory>

您可以简单地下载目录树:

git archive --remote git@github.com:foobar/Test.git HEAD:foo | tar xf -

但如果你想检查一下,并且能够提交并将它们推回去,那么你就不能这样做。

使用此函数,第一个参数是文件夹的url,第二个参数是下载文件夹的位置:

function github-dir() {
    svn export "$(sed 's/tree\/master/trunk/' <<< "$1")" "$2"  
}

为了放大上面的答案,一个从真正的GitHub存储库到本地目录的真实示例是:

svn ls https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces

svn export https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces  /temp/SvnExport/Washburn

有时,一个具体的例子有助于澄清所提出的替代方案。