0

How can I create a copy of a file and make it so that git understands where it is coming from? If I just do a copy and add it to the branch, git is not able to figure it out:

$ git log --oneline --graph --name-status master
* 70f03aa (master) COpying file straight
| A     new_file.txt
* efc04f3 (first) First commit for file
  A     hello_world.txt
$ git diff master:new_file.txt master:hello_world.txt 
$ git blame -s master -- hello_world.txt
^efc04f3 1) I am here
^efc04f3 2) 
^efc04f3 3) Yes I am
$ git blame -s master -- new_file.txt
70f03aab 1) I am here
70f03aab 2) 
70f03aab 3) Yes I am
$ git blame -s --follow master -- new_file.txt
70f03aab 1) I am here
70f03aab 2) 
70f03aab 3) Yes I am
eftshift0
  • 26,375
  • 3
  • 36
  • 60
  • 1
    The notion of "keeping its history" is slightly misleading - git always performs copy and rename detection when _reading_ history. So the real question is "how can I persuade `git blame` to follow my file rename", because `git log --follow` *does* follow it. – IMSoP Apr 06 '23 at 14:54
  • I was not aware of it. Will narrow down the scope of the question Thanks for bringing it up, @IMSoP – eftshift0 Apr 07 '23 at 12:28

1 Answers1

0

This can be done with some additional work on a separate branch.

git checkout -b rename-branch
git mv a.txt b.txt
git commit -m "Renaming file"
# if you did a git blame of b.txt, it would _follow_ a.txt history, right?
git checkout main
git merge --no-ff --no-commit rename-branch
git checkout HEAD -- a.txt # get the original file back
git commit -m "Not really renaming file"

Using the rename on the side and getting the file back when merging on the original files that I used for the question, we get:

$ git log --oneline --graph master2 --name-status
*   30b76ab (HEAD, master2) Not really renaming
|\  
| * 652921f Renaming file
|/  
|   R100        hello_world.txt new_file.txt
* efc04f3 (first) First commit for file
  A     hello_world.txt
$ git log --oneline --graph --name-status master2 -- new_file.txt
* 652921f Renaming file
  A     new_file.txt
$ git log --oneline --graph --follow --name-status master2 -- new_file.txt
... 
| * 652921f Renaming file
|/  
|   R100        hello_world.txt new_file.txt
* efc04f3 (first) First commit for file
  A     hello_world.txt
$ git blame -s master2 -- new_file.txt
^efc04f3 hello_world.txt 1) I am here
^efc04f3 hello_world.txt 2) 
^efc04f3 hello_world.txt 3) Yes I am
$ git blame -s master2 -- hello_world.txt
^efc04f3 1) I am here
^efc04f3 2) 
^efc04f3 3) Yes I am

Rationale is that if you want to see history of the original file git will do it without issues.... if you want to do it on the copy, then git will have to follow the separate branch used for moving the file (as that is where the file is coming from) and then it will be able to jump to the original file when going back in time.

eftshift0
  • 26,375
  • 3
  • 36
  • 60