如何从GitHub上托管的远程Git repo中仅下载特定文件夹或目录?
举个GitHub repo的例子:
git@github.com:foobar/Test.git
其目录结构:
Test/
├── foo/
│ ├── a.py
│ └── b.py
└── bar/
├── c.py
└── d.py
我只想下载foo文件夹,而不是克隆整个测试项目。
如何从GitHub上托管的远程Git repo中仅下载特定文件夹或目录?
举个GitHub repo的例子:
git@github.com:foobar/Test.git
其目录结构:
Test/
├── foo/
│ ├── a.py
│ └── b.py
└── bar/
├── c.py
└── d.py
我只想下载foo文件夹,而不是克隆整个测试项目。
当前回答
有一个名为githubdl的Python3pip包可以做到这一点*:
export GIT_TOKEN=1234567890123456789012345678901234567890123
pip install githubdl
githubdl -u http://github.com/foobar/test -d foo
项目页面在此处
*免责声明:这个包裹是我写的。
其他回答
如果要下载的目录是一个单独的库,最好创建其他git repo,然后使用git子模块函数。
当然,你必须是你想要的初始回购的所有者
在要加载的目录中:
git init
git remote add origin -f repoUrl // folder url
touch .git/info/sparse-checkout
git pull origin master
只有4行代码
如果您想使用Python和SVN下载特定的GitHub目录,请使用以下代码:
import validators
from svn.remote import RemoteClient
def download_folder(url):
if 'tree/master' in url:
url = url.replace('tree/master', 'trunk')
r = RemoteClient(url)
r.export('output')
if __name__ == '__main__':
url = input('Enter folder URL: ')
if not validators.url(url):
print('Invalid url')
else:
download_folder(url)
您可以在本教程中查看有关此代码和其他GitHub搜索和下载提示的更多详细信息:https://python.gotrained.com/search-github-api/
如果您熟悉unix命令,则不需要特殊的依赖项或web应用程序。您可以将回购文件下载为tarball,并只下载您需要的内容。
示例(font真棒中的子目录中的woff2文件):
curl -L https://api.github.com/repos/FortAwesome/Font-Awesome/tarball | tar xz --wildcards "*/web-fonts-with-css/webfonts/*.woff2" --strip-components=3
有关链接格式的详细信息:https://developer.github.com/v3/repos/contents/#get-存档链接(包括如何获取zip文件或特定分支/refs)保留路径的初始部分(*/)以匹配任何目录。Github创建了一个包装器目录,名称中包含commit ref,因此无法知道。您可能希望--strip组件与路径中斜杠(/)的数量相同(上一个参数)。
这将下载整个tarball。如果必须避免这种情况,或者如果您想对GitHub服务器友好,请使用其他答案中提到的SVN方法。
gitclone--筛选器仅下载所需文件
例如,要仅克隆此存储库的子目录big/所需的对象:https://github.com/cirosantilli/test-git-partial-clone-big-small我可以做到:
git clone --depth 1 --filter=blob:none --sparse \
https://github.com/cirosantilli/test-git-partial-clone-big-small
cd test-git-partial-clone-big-small
git sparse-checkout set small
--filter选项是与远程协议的更新一起添加的,它确实防止了从服务器下载对象。
我在下面的文章中详细介绍了这一点:如何仅克隆Git存储库的子目录?
2021 1月在git 2.30.0上测试。