3

I want to extract the commit file before the commit and the after the commit only using one commit id. Is there any way to extract this?

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

In this case i want to extract file name "FieldLUDecompositionTest" before the commit and after the commit only using one commit id which is "471d4d60dc21fbccb8c6b4616a00238c245f78f6"

DDDam
  • 33
  • 5
  • 1
    Note that you can also use `git show :` to extract a particular file from a particular commit without checking it out. Be aware that this sometimes skips line-ending conversions and smudge filters. – torek Nov 11 '19 at 16:53

2 Answers2

2

The proper way to extract/restore a file from a commit is, with Git 2.23+ (August 2019) to use git restore (less confusing than git checkout)

git restore <SHA1>

To restore only one specific file from that old commit:

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

That would update only your working tree by default.


Getting the previous SHA1 is easy:

471d4d60dc21fbccb8c6b4616a00238c245f78f6~

Git the next SHA1 is more complex: see "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

More in torek's answer)

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

So you can make a script which will get the parent and child of a given commit, and use git restore to get/see the files of those commits.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • This is does not get **a file** from a previous commit. It restores **all the files**. – SandRock Jun 01 '22 at 14:21
  • 1
    @SandRock I agree. I have edited the answer to add the case where you want to restore **a file** from a previous commit. – VonC Jun 01 '22 at 18:13
0

You just move your head to the desired commit and copy the file to another location. The procedure would be the following:

  1. git checkout 471d4d60dc21fbccb8c6b4616a00238c245f78f6 - you are now at the point where the file was not modified
  2. Copy the file to another location.
  3. git checkout 9988a5b3c4779eadfad9ea0c4925f5b327317814 - this is the latest commit from your history
  4. Copy the modified file to new location.

If you want more information about moving the head on a branch, you can read here.

Daniel
  • 2,320
  • 1
  • 14
  • 27