从远程git存储库获取单个文件内容的最有效机制(就传输的数据和使用的磁盘空间而言)是什么?

到目前为止,我已经想出了:

git clone --no-checkout --depth 1 git@github.com:foo/bar.git && cd bar && git show HEAD:path/to/file.txt

这似乎还是有些过分。

从回购中获取多个文件呢?


当前回答

在我看来,使用以下方法是最简单的:

wget https://github.com/name/folder/file.zip?raw=true

其他回答

下面两个命令对我来说很有用:

Git存档——remote={remote_repo_git_url} {branch} {file_to_download} -o {tar_out_file}

从远程存储库的分支(url为remote_repo_git_url)下载file_to_download作为tar归档文件,并存储在tar_out_file中

Tar -x -f {tar_out_file}.tar从tar_out_file中提取file_to_download文件

如果有web界面部署(如gitweb, cgit, Gitorious, ginatra),你可以使用它来下载单个文件('raw'或'plain'视图)。

如果其他方启用了它,你可以使用git存档的'——remote=<URL>'选项(可能限制它到给定文件所在的目录),例如:

$ git archive --remote=git@github.com:foo/bar.git --prefix=path/to/ HEAD:path/to/ |  tar xvf -

下面是Jakub的回答。Git存档生成tar或zip存档,所以你需要通过tar管道输出以获得文件内容:

git archive --remote=git://git.foo.com/project.git HEAD:path/to/directory filename | tar -x

将在当前目录中保存远程存储库HEAD中的'filename'的副本。

:path/to/directory部分是可选的。如果排除,提取的文件将保存到<当前工作目录>/path/to/directory/filename

此外,如果你想在git-daemon托管的git存储库上启用git archive——remote,你需要启用守护进程。Uploadarch配置选项。参见https://kernel.org/pub/software/scm/git/docs/git-daemon.html

如果你的Git存储库托管在Azure-DevOps (VSTS)上,你可以使用Rest API检索单个文件。

这个API的格式是这样的:

 https://dev.azure.com/{organization}/_apis/git/repositories/{repositoryId}/items?path={pathToFile}&api-version=4.1?download=true

例如:

 https://dev.azure.com/{organization}/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/items?scopePath=/MyWebSite/MyWebSite/Views/Home/_Home.cshtml&download=true&api-version=4.1

这是特定于托管在GitHub上的git回购

尝试Github的命令行应用程序gh的“api”命令,对Github的“获取存储库内容”端点进行身份验证调用。

基本命令是:

$gh api /repos/{owner}/{repo}/contents/<path_to_the_file>

作为额外的奖励,当您从包含您试图从中获取文件的repo副本的目录中执行此操作时,{owner}和{repo}部分将自动填充。

https://docs.github.com/en/rest/reference/repos#get-repository-content

响应将是一个JSON对象。如果<path_to_the_file>确实指向一个文件,JSON将包括一个'size', 'name',几个访问文件的url字段,以及一个'content'字段,这是文件内容的base64编码版本。

要获得文件内容,你可以卷曲“download_url”的值,或者只是解码“content”字段。你可以通过管道base64命令来做到这一点,就像这样:

$gh api /repos/{owner}/{repo}/contents/<path-to-the-file> --jq '.content' | base64 -d