如何从 git 中的提交 ID 中提取提交文件?

How to extract commit file from commit id in git?

我想在提交前和提交后仅使用一个提交 ID 提取提交文件。有没有办法提取这个?

commit 471d4d60dc21fbccb8c6b4616a00238c245f78f6
Author: Gilles Sadowski <gilles@harfang.homelinux.org>
Date:   Mon Oct 28 01:51:42 2019 +0100

MATH-1500 (unit tests).
src/test/ ... linalg/FieldLUDecompositionTest.java

commit 9988a5b3c4779eadfad9ea0c4925f5b327317814
Author: Gilles Sadowski <gilles@harfang.homelinux.org>
Date:   Sun Oct 27 15:11:56 2019 +0100

Code upgraded following MATH-1500.
src/main/... nonstiff/AdamsNordsieckTransformer.java

在这种情况下,我想在提交之前和提交之后提取文件名 "FieldLUDecompositionTest",仅使用一个提交 ID,即“471d4d60dc21fbccb8c6b4616a00238c245f78f6”

您只需将头移到所需的提交并将文件复制到另一个位置。 程序如下:

  1. git checkout 471d4d60dc21fbccb8c6b4616a00238c245f78f6 - 您现在处于文件未被修改的位置
  2. 将文件复制到另一个位置。
  3. git checkout 9988a5b3c4779eadfad9ea0c4925f5b327317814 - 这是您历史记录中的最新提交
  4. 将修改后的文件复制到新位置。

如果您想了解更多关于在树枝上移动头部的信息,您可以阅读

从提交中 extract/restore 文件的正确方法是 Git 2.23+(2019 年 8 月)使用 git restore (less confusing than git checkout)

git restore <SHA1>

要从旧提交中仅恢复一个特定文件:

git restore <SHA1> -- path/to/file

默认情况下只会更新您的工作树。


获取前一个 SHA1 很容易:

471d4d60dc21fbccb8c6b4616a00238c245f78f6~

Git next SHA1 更复杂:见“How do I find the next commit in git? (child/children of ref)”:

git log --format=%H --reverse --ancestry-path ${1:-HEAD}..${2:\"$(git rev-parse --abbrev-ref HEAD)\"} | head -1

更多内容在 torek's answer)

git rev-list --topo-order --ancestry-path --reverse <id1>...<id2> | head -1

所以你可以制作一个脚本来获取给定提交的父项和子项,并使用 git restore 到 get/see 这些提交的文件。