Git: Merge Repositories/replay commits on other repo

Posted . Visible to the public.

Scenario: You have edited some code from a tarball-snapshot, creating a fresh git repository in the source tree alongthe way. Now you want to merge your edits into the original repository, but you do not have the original history in the fresh repo. You also want to selectively squash or reorder some commits.

A word of warning beforehand: Be very careful if those repositories have different roots (e.g. one has just a subdirectory of the other repo).

The repo created from the tarball will be called tmprepo in what follows. Making a backup of your repo in case you mess something up is also a good idea.

  1. Check out the main repo, where you want to integrate your changes

  2. add the tmprepo repo as a remote repository (assuming it's local here)

    git remote add tmprepo path/to/tmprepo
    
  3. get the tmprepo commits

    git remote update
    
  4. examine the whole tree to find the commits of interest (helps if you copy the output to a scratch filet to keep track of the commits you have already picked and easy copy/paste of the sha-IDs)

    git log --all --oneline --graph --decorate --abbrev-commit
    
  5. pick your commits in the order you want; make sure everything is as expected before checking in. Note the -n option to cherry-pick: It allows to squash multiple commits before you explicitly commit them together manually in a single commit. Without it commits are immediately and automatically committed to the main repository after they have been picked (barring any conflicts).

    git cherry-pick -n sha-of-commit-one-to-squash
    git cherry-pick -n sha-of-commit-two-to-squash
    git cherry-pick -n sha-of-commit-three-to-squash
    git cherry-pick sha-of-commit-four-to-copy-over-as-is
    
  6. examine the whole tree again to check if everything is fine

    git log --all --oneline --graph --decorate --abbrev-commit
    
  7. (optional) compare the working copies of the two repositories using a diff tool (e.g. WinMerge)

  8. push the changes to the main repo

    git push origin master
    
  9. remove the refence to tmprepo

    git remote remove tmprepo
    
Markus
Last edit
Markus
Posted by Markus to Markus's deck (2017-11-09 10:43)