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


当前回答

非常简单:

git checkout from-branch-name -- path/to/the/file/you/want

这将不会签出from-branch-name分支。您将停留在您所在的分支上,并且只有该文件将从指定的分支签出。

下面是git-checkout手册的相关部分

git checkout [-p|--patch] [<tree-ish>] [--] <pathspec>...
       When <paths> or --patch are given, git checkout does not switch
       branches. It updates the named paths in the working tree from the
       index file or from a named <tree-ish> (most often a commit). In
       this case, the -b and --track options are meaningless and giving
       either of them results in an error. The <tree-ish> argument can be
       used to specify a specific tree-ish (i.e. commit, tag or tree) to
       update the index for the given paths before updating the working
       tree.

向Ariejan de Vroom致敬,他在这篇博客文章中教会了我这些。

其他回答

Git checkout branch_or_version——path/file

示例:git checkout HEAD——main.c

另一个解决方案,类似于使用——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 ;)

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

我没有看到在这里列出的对我有用的东西,所以我将包括它,如果有人在我的情况下。

My situation, I have a remote repository of maybe 10,000 files and I need to build an RPM file for my Linux system. The build of the RPM includes a git clone of everything. All I need is one file to start the RPM build. I can clone the entire source tree which does what I need but it takes an extra two minutes to download all those files when all I need is one. I tried to use the git archive option discussed and I got “fatal: Operation not supported by protocol.” It seems I have to get some sort of archive option enabled on the server and my server is maintained by bureaucratic thugs that seem to enjoy making it difficult to get things done.

最后我进入了bitbucket的网页界面,看到了我需要的一个文件。我右键点击链接下载文件的原始副本,并从弹出的结果中选择“复制快捷方式”。我不能只是下载原始文件,因为我需要自动化操作,而且我的Linux服务器上没有浏览器界面。

为了便于讨论,结果是URL:

https://ourArchive.ourCompany.com/projects/ThisProject/repos/data/raw/foo/bar.spec?at=refs%2Fheads%2FTheBranchOfInterest

我不能直接从bitbucket存储库下载这个文件,因为我需要先登录。经过一番挖掘,我发现这个方法有效: 在Linux上:

echo "myUser:myPass123"| base64
bXlVc2VyOm15UGFzczEyMwo=

curl -H 'Authorization: Basic bXlVc2VyOm15UGFzczEyMwo=' 'https://ourArchive.ourCompany.com/projects/ThisProject/repos/data/raw/foo/bar.spec?at=refs%2Fheads%2FTheBranchOfInterest' > bar.spec

这种组合允许我下载构建其他所有内容所需的一个文件。

这听起来像是你试图从集中式版本控制中继承一个想法,而git本质上不是这样的——它是分布式的。如果你想使用git存储库,你可以克隆它。然后,您就拥有了工作树的所有内容和所有历史记录(好吧,至少是指向当前分支顶端的所有内容),而不仅仅是单个文件或单个提交的快照。

 git clone /path/to/repo
 git clone git://url/of/repo
 git clone http://url/of/repo

Git checkout <other-branch>—<single-file>适用于我的Git .2.37.1。 然而,该文件是(git-魔术)提交的,我不能看到正确的git diff。 然后运行git restore——staging db/structure。SQL来取消它。

这样我就有了我想要的确切版本的文件,我可以看到该文件与其他版本的区别。