我如何从一个git回购签出一个文件?


当前回答

如果你需要一个来自远程Git存储库的特定分支的特定文件,命令如下:

git archive --remote=git://git.example.com/project.git refs/heads/mybranch path/to/myfile |tar xf -

剩下的可以从@VonC的回答中得到:

如果你需要一个来自主分支的特定文件,它是:

git archive --remote=git://git.example.com/project.git HEAD path/to/myfile |tar xf -

如果你需要一个标签的特定文件,它是:

git archive --remote=git://git.example.com/project.git mytag path/to/myfile |tar xf -

其他回答

如果你已经有了一个git回购的副本,你可以使用git日志签出一个文件的版本来找出哈希id(例如3cdc61015724f9965575ba954c8cd4232c8b42e4),然后你只需输入:

git checkout hash-id path-to-file

下面是一个实际的例子:

git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /var/www/css/page.css

在codecommit (git版本的Amazon AWS)中,你可以这样做:

aws codecommit \
  get-file --repository-name myrepo \
  --commit-specifier master \
  --file-path path/myfile \
  --output text \
  --query fileContent | 
base64 --decode > myfile

另一个解决方案,类似于使用——filter=blob:none的解决方案是使用——filter=tree:0(你可以在这里阅读关于区别的解释)。

这种方法通常比blob-one更快,因为它不下载树结构,但有一个缺点。考虑到您延迟了树的检索,当您进入repo目录时将受到惩罚(取决于repo的大小和结构,它可能比简单的浅克隆大许多倍)。

如果你是这种情况,你可以通过不进入回购来解决:

git clone -n --filter=tree:0 <repo_url> tgt_dir
git -C tgt_dir checkout <branch> -- <filename>
cat tgt_dir/<filename> # or move it to another place and delete tgt_dir ;)

请考虑到,如果您必须签出多个文件,树填充也会影响您的性能,因此我建议仅在回购足够大的情况下才对单个文件执行此操作。

首先使用-n选项和——depth 1选项克隆repo,前者抑制所有文件的默认签出,后者意味着它只获取每个文件的最新修订

git clone -n git://path/to/the_repo.git --depth 1

然后签出你想要的文件,就像这样:

cd the_repo
git checkout HEAD name_of_file

如果您只需要下载文件,则不需要使用Git签出。

GitHub Mate更容易做到这一点,它是一个Chrome扩展,让你点击文件图标下载它。也是开源的