DDDam
DDDam

Reputation: 33

How to extract commit file from commit id in git?

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 <[email protected]>
Date:   Mon Oct 28 01:51:42 2019 +0100

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

commit 9988a5b3c4779eadfad9ea0c4925f5b327317814
Author: Gilles Sadowski <[email protected]>
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"

Upvotes: 3

Views: 2079

Answers (2)

VonC
VonC

Reputation: 1329712

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.

Upvotes: 3

Daniel
Daniel

Reputation: 2554

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.

Upvotes: 0

Related Questions