如何从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文件夹,而不是克隆整个测试项目。
当前回答
将git存储库文件夹下载到当前目录并删除git文件。
#!/bin/sh
function download_git_folder() {
repo_url=$1
branch=$2
repo_subfolder_path=$3
repo_folder=$(basename $repo_url)
git init
git remote add -f origin ${repo_url}
git config core.sparseCheckout true
echo "${repo_subfolder_path}" >> .git/info/sparse-checkout
git pull origin ${branch}
mv "${repo_subfolder_path}"/* ./
readarray -td/ root_subfolder <<<"${repo_subfolder_path}"; declare -p root_subfolder;
rm -rf ./.git ${root_subfolder[0]}
}
用法
download_git_folder "git@github.com:foobar/Test.git" "master" "Test/bar"
其他回答
你不能;不同于Subversion,每个子目录都可以单独检出,Git在整个存储库的基础上运行。
对于需要更细粒度访问的项目,可以使用子模块——每个子模块都是一个单独的Git项目,因此可以单独克隆。
可以想象,Git前端(例如GitHub的web界面或gitweb)可以选择为您提供一个界面来提取给定的文件夹,但据我所知,他们中没有一个这样做(尽管他们确实允许您下载单个文件,所以如果文件夹不包含太多文件,这是一个选项)
编辑-GitHub实际上提供了通过SVN的访问,这将允许您执行此操作(根据评论)。看见https://github.com/blog/1438-improved-svn-here-to-stay-old-svn-going-away有关如何执行此操作的最新说明
最简单的方法是使用fetcher
首先,使用以下命令安装fetcher:
npm安装-ggithub文件获取器
然后您可以下载带有URL的文件或文件夹:
fetcher--url=resource_url--out=output_directory
例如:
fetcher--url=“https://github.com/Gyumeijie/github-files-fetcher/blob/master/CHANGELOG.md“--out=/tmp
将git存储库文件夹下载到当前目录并删除git文件。
#!/bin/sh
function download_git_folder() {
repo_url=$1
branch=$2
repo_subfolder_path=$3
repo_folder=$(basename $repo_url)
git init
git remote add -f origin ${repo_url}
git config core.sparseCheckout true
echo "${repo_subfolder_path}" >> .git/info/sparse-checkout
git pull origin ${branch}
mv "${repo_subfolder_path}"/* ./
readarray -td/ root_subfolder <<<"${repo_subfolder_path}"; declare -p root_subfolder;
rm -rf ./.git ${root_subfolder[0]}
}
用法
download_git_folder "git@github.com:foobar/Test.git" "master" "Test/bar"
对于通用git Repo:
如果您想下载文件,而不是克隆具有历史记录的存储库,可以使用gitarchive来完成此操作。
gitarchive生成git存储库的压缩zip或tar存档。让它与众不同的一些东西:
您可以选择git存储库中要归档的文件或目录。它不会将.git/文件夹或其运行的存储库中任何未跟踪的文件归档。您可以归档特定的分支、标记或提交。使用git管理的项目通常使用它来生成项目版本(beta、release、2.0等)的存档,供用户下载。
使用ssh从远程存储库创建docs/usage目录归档的示例:
# in terminal
$ git archive --format tar --remote ssh://server.org/path/to/git HEAD docs/usage > /tmp/usage_docs.tar
更多信息请参阅本博客文章和git文档。
GitHub Repos注意事项:
GitHub不允许git存档访问。☹️
您可以简单地下载目录树:
git archive --remote git@github.com:foobar/Test.git HEAD:foo | tar xf -
但如果你想检查一下,并且能够提交并将它们推回去,那么你就不能这样做。