Push commits affecting a given path to a new origin?
Asked Answered
git
R

1

6

I currently have a file structure that looks like this:

# C:\Repositories\VisualStudio\MyProject
.git # repository is one level above clientapp and includes other folders/paths than clientapp
afolder
clientapp
file1
file2

Now I want to move the clientapp folder to a new location and rename it to frontend. Then I want to create a new repository only for the frontend. No problem until here:

# inside C:\Repositories\MyProject\frontend (no more VisualStudio in the path!)
.git
<all the frontend folders and files>

Now comes the problem: Of course I now loose the history for the original clientapp (now: frontend) folder, because I created a new repository. Any way to copy the commits concerning the original clientapp folder to my new repository for the frontend?

Reverse answered 12/12, 2020 at 9:58 Comment(1)
See Also: Move directory to another repository while keeping the historyBlalock
R
13

TLDR: Filter original repository to the folder that one wants to keep, then pull it in from the new repository.


  1. Download and use git-filter-repo which git filter-branch officially recommends.

    *Windows Users - see Install git-filter-repo on Windows

  2. Filter repository to relevant files (make sure to have a backup before!):

    git filter-repo --path clientapp
    
  3. Move the files inside clientapp to the root

    git filter-repo --subdirectory-filter clientapp/
    
  4. Go to your new repository, add a remote to the original repository:

    git remote add repo-A <path to original repo, e.g. ../repo-A>
    
  5. Pull files and history from this branch into repository B (containing only the directory you want to move) .

    git pull repo-A master
    
  6. Remove the remote connection to repository A.

    git remote rm repo-A
    
  7. Push from your new repository

    git push
    
  8. Delete the copy of your original repository (that only contains the filtered folder). If needed, clone it again. Happily work with your new repository with a full commit history.

Further Reading: Medium article on how to move files from one repository to another, preserving git history, especially the section on Merge the files into the new repository B.

Reverse answered 12/12, 2020 at 13:10 Comment(1)
minor addition: if the git repository you want to clone is on the same machine, git would not use its default transport protocol to clone the repository and git filter-repo --path clientapp would give you this error: If Aborting: Refusing to destructively overwrite repo history since this does not look like a fresh clone.. To avoid that, force git to use its default transport protocol even when cloning local repos. You can do that using git clone --no-local instead of just git cloneNotecase

© 2022 - 2024 — McMap. All rights reserved.