Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x-yuri/9907d5b9cbf29e84d510902a776741df to your computer and use it in GitHub Desktop.
Save x-yuri/9907d5b9cbf29e84d510902a776741df to your computer and use it in GitHub Desktop.
Copying commits between unrelated repositories

Copying commits between unrelated repositories

Consider 2 unrelated (no common commits) repositories (and histories), in dirs a and b.

$ cd b
$ git remote add a ../a
$ git fetch a
$ git --no-pager log --oneline --graph --all
* 4b68cfa (HEAD -> master) 11,2,3
* 79591c1 (a/master) 3 -> 33
* 6a41c8b 1,2,3

Repository a, file f, commit 6a41c8b:

1
2
3

The following commit (79591c1) changes 3 to 33.

Repository b, file f, commit 4b68cfa (a root node that starts a separate branch):

11
2
3

Cherry-picking or rebasing 3 -> 33 onto 11,2,3 succeeds. Merging of the 2 branches/repositories fails. (proof)

format-patch + am succeeds provided that you have commits from both repositories/branches (1):

$ cd b
$ git remote add a ../a
$ git fetch a

and that you supply -3 to git am (2). (proof)

So it does within a single repository (copying 3 -> 33 onto 1 -> 11):

* 9987dd0 (dev) 3 -> 33
| * dcd467c (HEAD -> master) 1 -> 11
|/  
* a56b04a 1,2,3

The first precondition is met automatically, the second one is still needed. (proof)

set -eux
rm -rf a b
mkdir a
(cd a
git init
echo '1
2
3' > f
git add f
git commit -m 1,2,3
git --no-pager log --oneline --graph --all
sed -Ei 's/3/33/' f
git add f
git commit -m '3 -> 33')
mkdir b
(cd b
git init
echo '11
2
3' > f
git add f
git commit -m 11,2,3
git remote add a ../a
git fetch a
cat f
git --no-pager log --oneline --graph --all
git cherry-pick a/master
# git branch b a/master; git rebase --onto master b~ b
# git merge --allow-unrelated-histories a/master
git --no-pager log --oneline --graph --all)
set -eux
rm -rf a b
mkdir a
(cd a
git init
echo '1
2
3' > a
git add a
git commit -m 1,2,3
sed -Ei 's/3/33/' a
git add a
git commit -m '3 -> 33'
git format-patch -1 HEAD)
mkdir b
(cd b
git init
echo '11
2
3' > a
git add a
git commit -m 11,2,3
git remote add a ../a
git fetch a
cat a
cat ../a/0001-3-33.patch
git --no-pager log --oneline --graph --all
git am "$@" ../a/0001-3-33.patch
git --no-pager log --oneline --graph --all)
set -eux
rm -rf r
mkdir r
(cd r
git init
echo '1
2
3' > a
git add a
git commit -m 1,2,3
git checkout -b dev
sed -Ei 's/3/33/' a
git add a
git commit -m '3 -> 33'
git format-patch -1 HEAD
git checkout master
sed -Ei 's/1/11/' a
git add a
git commit -m '1 -> 11'
cat a
cat 0001-3-33.patch
git --no-pager log --oneline --graph --all
git am "$@" 0001-3-33.patch
git --no-pager log --oneline --graph --all)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment