3

I have a situation where someone started a file in one folder and made several commits and then committed a copy of it in another folder and made more commits. I would like to merge or combine this files into a single file and preserve the history.

The second copy is newer and correct but in the wrong folder. The older file can be overwritten by the newer file.

I could copy and paste the content but I would lose the history.

HappyDude
  • 310
  • 3
  • 11

1 Answers1

1
git rm <good-location/file>
git commit -m 'Removing bad file from good location'
git mv <bad-location/file> <good-location/file>
git commit -m 'Moving file to correct location'

After doing this, the following commands will show the appropriate history.

git log --follow -- <good-location/file>

Use the -C<some number>% argument to increase the chance of your file being tracked across copies. See the Git documentation for diff, log, and blame more details.

If you are using a GUI, such as Eclipse's Git plugin, this may work as expected.

There is nothing that you can do to force Git to recognize a copy at commit time. Git only stores snapshot, but has very good after the fact heuristics, at least with the command line.

Some sample usage and output:

$ git log --format="%h" master.. --name-status  -M100% --follow  -- temp3
0d15571

R100    temp10  temp3
e55bab3

M       temp10
6f16545

M       temp10
0a849e3

M       temp10
1a06161

C100    temp3   temp10
95c8a20

A       temp3
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Joseph K. Strauss
  • 4,683
  • 1
  • 23
  • 40
  • It seems that git log --follow -- shows me the history of the file that I moved and git log -- shows me the history of the file I deleted plus the git mv commit. I'm still fairly new to git. Thanks for the help – HappyDude Jan 16 '15 at 17:43
  • Given the issue @HappyDude notes in the comment, this doesn’t seem like a satisfactory solution. Yes, the histories are preserved. But it requires special knowledge of the history to get a combined log, meaning it’s not easily discoverable for future developers. There are other approaches that mitigate this ([example](https://stackoverflow.com/a/58702049/3025856))—though, unfortunately, they’re also a lot more complicated. – Jeremy Caney Dec 07 '21 at 16:27