Search code examples
gitgithubforkrepogit-fork

Git/Github: fixing repos history


I have this repos on GitHub:

  • [user 1] original
  • [user 2] copy(original)
  • \ -> [ME] fork(copy(original))

copy has added some commits on top of original, and my fork has other commits on top of copy (chronologically sequential, there is no time overlapping between repos)

I want to preserve the structure of the forks in order to put, in the future, my commits to original, like making a fork of original, then add to it the copy commits, then add the fork commits, preserving the authors of them and hopefully also the timestamps. Something like this:

  • [user 1] original
  • \ -> [ME] fork(original) <-- but with the commits that user 2 has on his own copy(original), and my commits on top of them

Is there a way to do this?


Solution

  • Yes, its possible. First, clone your current fork, add original repo as a remote and fetch all data

    git clone [email protected]:YOUR-USERNAME/fork.git
    cd fork
    git remote add upstream [email protected]:user1/original.git
    git fetch --all
    

    Then, create a new branch and add user2's repo as another remote

    git checkout -b restructured upstream/main
    git remote add user2repo [email protected]:user2/copy.git
    git fetch --all
    

    Then, cherry-pick user2's commits and your own commits from your fork.

    git log user2repo/main
    git cherry-pick FIRST_COMMIT^..LAST_COMMIT
    git cherry-pick YOUR_FIRST_COMMIT^..YOUR_LAST_COMMIT
    

    Finally push the restructured branch to your fork

    git push -u origin restructured
    

    It will create a new branch with the exact structure you want: original base + user2's commits + your commits, all with proper attribution and timestamps

    You can then use this restructured branch as the base for your future pull request to the original repository. The commit history will be clean and linear, making it easier to review and merge.

    Thank you.