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

举个GitHub repo的例子:

git@github.com:foobar/Test.git

其目录结构:

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

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


当前回答

要从GitHub导出目录,请将目录url中的“/tree/master/”替换为“trunk/”。

例如,要从以下URL导出目录:

https://github.com/liferay/liferay-plugins/tree/master/portlets/sample-hibernate-portlet

运行以下命令:

svn export https://github.com/liferay/liferay-plugins/trunk/portlets/sample-hibernate-portlet

其他回答

我们的团队为此编写了一个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

将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存储库的子目录?

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

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

试试看。

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"

只需5步

从这里下载SVN。打开CMD并转到SVN bin目录,如:cd%ProgramFiles%\SlikSvn\bin假设我想下载这个目录URLhttps://github.com/ZeBobo5/Vlc.DotNet/tree/develop/src/Samples代替树/开发或树干的树/主现在启动最后一个命令以下载同一目录中的文件夹。

svn export https://github.com/ZeBobo5/Vlc.DotNet/trunk/src/Samples