1

I have file1.txt in my git repo, the initial repo structure was

repo/
     file1.txt
     directory1/

file1.txt had two commits (when I tried using following command it showed two commits)

git log -p file1.txt

later I moved file1.txt to directory1 using git command

git mv file1.txt directory1

then the new repo structure is

repo/

     directory1/file1.txt

but after moving that file, it does't show those two commits using

 git log -p directory1/file1.txt

Can anyone help how to preserve history while moving files like this, or there is some other way to move files?

Mahesh Uligade
  • 597
  • 8
  • 17

2 Answers2

3

Git does not record moves explicitly (like for instance SVN does). Each commit is a snapshot of the entire state. So, it does not matter if you moved the file using git mv A B or moved it using mv A B && git add A B, or moved it in any other way and added this change -- the result will be identical.

Git instead provides tools to view the history in various ways. Whether or not a particular change was a rename is determined on-the-fly as the data is viewed.

Using the --follow option to git log will enable rename detection.

git log --follow -- path/to/file

Sometimes when a file is renamed, one might also change its contents. Depending on how much of the content has changed, rename detection might not work -- it becomes the question of whether it is a rename, or a deletion and an unrelated addition. To change how much of the file that needs to match for it to be considered a rename, use the -M option.

git log -M40% --follow -- path/to/file

The -M option also works with other commands such as git diff and git show.

There is also -C which is equivalent to -M except it detects copies.

If a file needs to be renamed and its contents also change a lot, a trick is to, if possible, do the rename and the content modification in separate commits. That way the rename will be detected without the need for tweaking.

More info at man git-log, man git-diff, man git-show.

jsageryd
  • 4,234
  • 21
  • 34
1

The history is preserved, git log just doesn't show it by default. You can use the --follow flag to track changes beyond renaming or moving the file:

$ git log --follow -p directory1/file1.txt
Mureinik
  • 297,002
  • 52
  • 306
  • 350