Search code examples
gitgit-mv

How do I move files to a new location in my Git repository without losing their history?


Last week I created a new Git repository, and got to work. Now I noticed that all files I've created are in the root and not in a src folder. I've been searching since last night for a way to move the files without losing its history.

Manually moving them means Git will consider them to be new files without any history.

Using git mv means the files at the new location will still be considered new files. The only difference is the history still exists, but is associated to the file in the old location.

I figured Git must store an index of where files are stored somewhere. I found the aptly named file index in the .git folder contained the file names. After adding a test file in a subfolder, I saw that the path is stored along with the file name. So I manually edited index and moved the file.

In my Git client, I saw that the moved file is not considered a change. So far, so good. However, if I look at the commit history, the file is still considered to be located in the root.

Next, I read that there's such a thing as a Git cache. Supposedly, you can clear it using git rm --cache. However, this doesn't work on Windows, returning a cryptic error: fatal: No pathspec was given. Which files should I remove?.

At this point, I'm out of ideas. How do I solve this problem?


Solution

  • To do this, you can use a tool called git-filter-repo. It's hosted at https://github.com/newren/git-filter-repo