DEV Community

Artem Ptushkin
Artem Ptushkin

Posted on

How to migrate a directory from git repository to another one preserving git history. Bitbucket example

Assume we migrate:

  • The folder2 from git@bitbucket.org:myproject/myrepo.git
  myrepo
  │   README.md
  └───folder1
  └───folder2
Enter fullscreen mode Exit fullscreen mode
  • to git@bitbucket.org:newrepo.git

How to do this:

  1. To make it safe, clone myrepo.git into a new directory

    mkdir myrepo-folder2-migration
    cd myrepo-folder2-migration
    
    git clone 
    git@bitbucket.org:myproject/myrepo.git
    
    cd myrepo
    
    #prevent pushing into it
    git remote rm origin
    
  2. Filter git history to keep only files in folder2

    git filter-branch --subdirectory-filter folder2 -- --all
    
  3. Clean unwanted data

    git reset --hard
    git gc --aggressive 
    git prune
    git clean -fd
    
  4. It should contain only the files from folder2 in the root git directory now

  5. Go back and prepare to work for the newrepo

    cd ..
    
    pwd
    #make sure you're in myrepo-folder2-migration
    
  6. Clone the empty repository

    git clone git@bitbucket.org:newrepo.git
    
    cd newrepo
    
  7. Create a connection to local repository, we're going to pull from it

    git remote add old-repo ../myrepo
    
  8. Pull files from the old repo

    git pull old-repo master --allow-unrelated-histories
    
  9. Remove the connection with local

    git remote remove old-repo
    
  10. Push the changes to the remote origin

    git push
    

The new remote repository should contain files from folder2 inside the root directory now.

I followed https://medium.com/@ayushya/move-directory-from-one-repository-to-another-preserving-git-history-d210fa049d4b with adjustments I found important and clear for understanding.

Top comments (2)

Collapse
 
pandrew profile image
Andrew • Edited

Didn't work, I tried twice, it adds the files at the root of the repo, just making a mess, the "folder2" is not created.

Collapse
 
art_ptushkin profile image
Artem Ptushkin

something might change, I know people that followed this and it did work