ivand58
ivand58

Reputation: 811

How to rearange commits in few independed branches in git?

I need to rearrange a "linear structure"

temp       -C1-C2-C3-C4-C5-C6-C7-C8-C9-C10
         /
master -C0

to "fork-like structure".

branch-1   -C1-C2-C3-C4-C5
         /
master -C0
         \
branch-2   -C6-C7-C8-C9-C10

Example: Let's start from one branch (let's name it temp), derived from the master, and then let's put few commits - C1 .. C10. Instead of this I'd like to have two branches based on master (one per feature). I can create these two branches by referring the commit before C1. Than, how to reshuffle (merge?) all commits in a way to get commits from C1 to C5 in branch-1 (derived from master) and branches from C6 to C10 in branch-2 also derived from master? As result in the log of branch-2 I expect to have C0, C6..C10 (where C0 is the last commit in the master branch).

Probably the branch-1 can be retrieved by renaming temp and doing

git reset --hard  HEAD~5 #or 4 (?)

But for the branch-2 how to remove C1..C5 and keep the rest?

EDIT: Here is the test script that can be used to reproduce the case:

#!/bin/bash

## file names
file1='file1'
file2='file2'

## clean-up for fresh start
if [ -d .git ] 
then
    rm -rf .git
fi
## create files
echo start1 > $file1
echo start2 > $file2

## start the repository creation 
git init
git add $file1 $file2
git commit -am 'C0'

## linear branch
git checkout -b temp

## implement features 1 & 2 in files 1 & 2
for i in {1..10}
do
    if [ $i -le 5 ]
    then
    file=$file1
    else
    file=$file2
    fi
    msg='line '$i
    echo $msg >> $file
    git commit -m "C$i" $file
done

Upvotes: 1

Views: 74

Answers (1)

Vampire
Vampire

Reputation: 38669

git branch branch-1 C5
git branch -m temp branch-2
git rebase --onto C0 branch-1 branch-2

Upvotes: 1

Related Questions