How can I move a directory in a Git repo for all commits?

mipadi picture mipadi · Jun 29, 2010 · Viewed 27.2k times · Source

Let's say I have a repo that includes this directory structure:

repo/
  blog/
    _posts/
      some-post.html
  another-file.txt

I want to move _posts to the top level of the repo, so the structure will look like this:

repo/
  _posts/
    some-post.html
  another-file.txt

This is simple enough with git mv, but I want to make the history look as though _posts always existed at the root of the repo, and I want to be able to get the entire history of some-post.html via git log -- _posts/some-post.html. I imagine I can use some magic with git filter-branch to accomplish this, but I haven't figured out exactly how to do that. Any ideas?

Answer

artagnon picture artagnon · Jun 29, 2010

You can use the subdirectory filter to achieve this

 $ git filter-branch --subdirectory-filter blog/ -- --all

EDIT 1: If you don't want to effectively make _posts the root, use a tree-filter instead:

 $ git filter-branch --tree-filter 'mv blog/_posts .' HEAD

EDIT 2: If blog/_posts did not exist in some of the commits, the above will fail. Use this instead:

 $ git filter-branch --tree-filter 'test -d blog/_posts && mv blog/_posts . || echo "Nothing to do"' HEAD