git rewrite commit parent?

I have two commits based on some parent: P -> A -> B

I'd like for them to be based on another parent: P' -> A' -> B'

EDIT: My situation is that I'm working with other team members. We have a central git repository. In my configuration, 'git pull' does rebase while for the others it creates a merge. Every now and then, when I issue 'git pull', git starts rebasing commits that I didn't do and I need to resolve conflicts for code I didn't write. This is long and error prone.

I assume the reason is that something similar to this happens:

        /--A--B---- // my repository
       /
--C1--C2--------M-  // the remote
   \   M       /
    \-D-M'-E--/     // another developer

So a developer merges C2 and then pushes his changes which makes git think some commits are new (my guess only). What I end up with is having to rebase other people commits.


Solution 1:

Let's assume this as the situation:

        A---B (topic1)
       /
...---P---C---D (topic2)

If your current branch is 'topic1', you can move commits A and B into topic2 branch by issuing git rebase topic2 topic1(or just git rebase topic2). Then the repo graph would look like

                A'--B' (topic1)
               /
...---P---C---D (topic2)

where commit D is what you considered as P'. Note, that the new parent commit needn't to be changed.

Or, more generally, if you need to move some commit(s) as descendant(s) of any commit (not necessarily the head of branch), you can use --onto parameter:

         A---B (topic1)
        /
...Q---P---C---D (topic2)

git rebase --onto topic2~3 topic1~2 topic1 or git rebase --onto Q P topic1 where Q and P are commits' SHA1s.

     A'--B' (topic1)
    /
...Q---P---C---D (topic2)

If these weren't what you intended, care to explain your situation a bit more?