Build an exercise git repository with stage branches

You may want to build separately several branches of your repository with different contents in each “stage” of your exercise.

For example stage-0 will contain the begining of the exercise and each stage-$i will incrementally add some implementations and exercise corrections.

The thing that is uncomfortable when these stages are on the same commit tree is when you realize that you missed an important part at stage-0.
I can try to rebase, but I don’t want to repeat that operation for each missing thing in stage-0.

So here I am suggesting to build orphan branches for every stage.

git checkout --orphan stage-1 will create a new branch without commit.

Once you are done with applying missing modifications in your steps, you can build a new commit tree in master with the additions of all the stages, stacked one after the other.

To do that, I have prepared a simple script for you. The only necessary pre-requisite is to have called your branches stage-i, where i is the number of your stage.

Filename :


if [ ! -d .git ];then
echo "this is not a git repo"
exit 1

if [ ! -z "$(git status --porcelain)" ];then
echo "changeset not empty, exiting"
exit 1

# list stage-i branches
SORTED_BRANCHES="$(git branch -a | tr '*' ' ' | sed 's/remotes\/origin\///' | grep stage- | sed 's/stage-//' | while read x; do printf "%04d stage-$x\n" $x;done | sort | uniq | cut -d ' ' -f2)"

# checkouting any branch to make sure we are not on master
git checkout $(echo "$SORTED_BRANCHES" | head -n 1)

# deleting master
git branch -D master

# building a new master and making sure there is no file on HEAD
git checkout --orphan master
git rm --cached -r .
rm $(find | grep -v '.git/')
rmdir $(find | grep -v '.git/' | sort -r)

# building a new HEAD with nothing
git commit --allow-empty -m "init"

# adding one commit for each stage
echo "$SORTED_BRANCHES" | while read branch; do
git diff HEAD..origin/$branch | git apply
git add .
git commit -m "$branch"

# you can then push using the command git push -u origin -f master

Go to your exercise repository, and just type :
When you are convinced that you are not erasing someone else’s master branch, you can just push your new master using the command git push -u origin -f master

Good luck.

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.