Suppose I have a file a.txt
. One day, I deleted it, committed, and pushed.
The next day, I wanted like to revert the last commit, bringing back a.txt
. I tried using git revert
, but when I did git blame
, all lines are showing the revert commit hash. The original blame history is lost.
Can I recover the file and preserve the file history, i.e., as if the file has not been deleted before? Note that I must not change the history as the commit has been pushed.
Thanks!
You CAN do this! Here's how:
git merge <sha> -s ours
.git diff <sha>^..<sha> | git apply
.git checkout -p
may work well for you).This produces a history with two branches; one in which the file was deleted, and one in which it was never deleted. As a result, git is able to track the file history without resorting to heroics such as -C -C -C
. (In fact, even with -C -C -C
, the file isn't "restored", because what git sees is that a new file was created as a copy of a previously existing file. With this technique, you are reintroducing the same file to the repository.)
Run git blame with the -C
option specified three times:
git blame -C -C -C
This causes git blame
to look for content copied from files in previous commits.
From the documentation for git blame
:
-C|<num>|
In addition to
-M
, detect lines moved or copied from other files that were modified in the same commit. This is useful when you reorganize your program and move code around across files. When this option is given twice, the command additionally looks for copies from other files in the commit that creates the file. When this option is given three times, the command additionally looks for copies from other files in any commit.
<num>
is optional but it is the lower bound on the number of alphanumeric characters that Git must detect as moving/copying between files for it to associate those lines with the parent commit. And the default value is 40. If there are more than one-C
options given, the<num>
argument of the last-C
will take effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With