Duplicate git changes across repositories

Published: 1 year ago web dev

Sometimes I need to duplicate commits across multiple git repositories. As with a lot of things in git, there's more than one way to do this.

The first way is to:

  • Add your source repo to the target repo with git remote <name> <remote-url>
  • Fetch your other repository with git fetch <remote-name> <branch>
  • From here you can view a log of that repo with git log <remote-name>/<branch>
  • Use git cherry-pick to pick specific commits from that repo with git cherry-pick <sha-1>
  • Push your changes to target remote.

The second way is to use format-patch. This way avoids the need of adding an extra remote and you can 'sign off' the patch:

  • You can generate a patch file with git format-patch —stdout -1 <sha1> > file.patch
  • If you have multiple non-sequential commits you can put multiple commits into one patch files: { git format-patch —stdout -1 <sha1> > file.patch & git format-patch —stdout -1 <sha1> > file.patch > all.patch & git format-patch —stdout -1 <sha1> > file.patch ; } > file.patch
  • In your target repository, you can import that patch file: git am —signoff < file.patch. A bonus of doing it this way is you can 'sign off' your patch. GitHub will display your sign off within the commit message.
  • I did have some problems applying one particular patch and it turned out the target repo had some differences in its whitespace formatting that prevented git from cleanly applying the patch. Passing --ignore-whitespace to git am fixed this issue.
  • As an interesting aside, git diff output can be used as a patch file provided you add the mail headers to make it look like an email.