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

举个GitHub repo的例子:

git@github.com:foobar/Test.git

其目录结构:

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

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


当前回答

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

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

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

其他回答

另一个具体示例:

就像我想从url下载“iOS Pro Geo”文件夹

https://github.com/alokc83/APRESS-Books-Source-Code-/tree/master/%20Pro%20iOS%20Geo

我可以通过

svn checkout https://github.com/alokc83/APRESS-Books-Source-Code-/trunk/%20Pro%20iOS%20Geo

注意路径中的主干

编辑:(根据Tommie C的评论)

是的,使用导出而不是签出将提供一个干净的副本,而无需额外的git存储库文件。

svn export https://github.com/alokc83/APRESS-Books-Source-Code-/trunk/%20Pro%20iOS%20Geo

已编辑:如果树/主节点不在url中,则分叉它,它将在分叉的url中。

我使用linux,所以把它放在~/.bashrc中,甚至称为:D$HOME/.bashrc

git-dowloadfolder(){
a="$1"
svn checkout ${a/tree\/master/trunk}

}

然后用

source ~/.bashrc 

然后将其与git downloadfolder blablabla:D一起使用

无论出于什么原因,svn解决方案对我来说都不起作用,而且由于我不需要svn来做任何其他事情,所以花时间尝试它是没有意义的,所以我使用我已经拥有的工具来寻找一个简单的解决方案。该脚本只使用curl和awk来下载GitHub目录中的所有文件,该目录描述为“/:user:repo/contents/:path”。

GitHub REST API调用的返回主体“GET/repos/:user:repo/contents/:path”命令返回一个对象,该对象包含目录中每个文件的“download_url”链接。

该命令行脚本使用curl调用REST API,并通过AWK发送结果,AWK过滤掉除“download_url”行之外的所有行,删除链接中的引号和逗号,然后使用另一个对curl的调用下载链接。

curl -s https://api.github.com/repos/:user/:repo/contents/:path | awk \
     '/download_url/ { gsub("\"|,", "", $2); system("curl -O "$2"); }'

试试看。

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"

我们的团队为此编写了一个bash脚本,因为我们不想在我们的裸机服务器上安装SVN。

https://github.com/ojbc/docker/blob/master/java8-karaf3/files/git-download.sh

它使用github API,可以从如下命令行运行:

git-download.sh https://api.github.com/repos/ojbc/main/contents/shared/ojb-certs