#!/bin/sh

echo "[extensions]" >> $HGRCPATH
echo "graphlog=" >> $HGRCPATH
echo "rebase=" >> $HGRCPATH

BASE=`pwd`

addcommit () {
    echo $1 > $1
    hg add $1
    hg commit -d "${2} 0" -m $1
}

commit () {
    hg commit -d "${2} 0" -m $1
}

createrepo () {
    cd $BASE
    rm -rf a
    hg init a
    cd a
    addcommit "A" 0
    addcommit "B" 1

    hg update -C 0
    addcommit "C" 2

    hg update -C 0
    addcommit "D" 3

    hg merge -r 2
    commit "E" 4

    hg update -C 3
    addcommit "F" 5
}

createrepo > /dev/null 2>&1
hg glog  --template '{rev}: {desc}\n'

echo '% Rebasing'
echo '% B onto F - simple rebase'
hg rebase -s 1 -d 5 2>&1 | sed 's/\(saving bundle to \).*/\1/'
hg glog  --template '{rev}: {desc}\n'

createrepo > /dev/null 2>&1
echo '% B onto D - intermediate point'
hg rebase -s 1 -d 3 2>&1 | sed 's/\(saving bundle to \).*/\1/'
hg glog  --template '{rev}: {desc}\n'

createrepo > /dev/null 2>&1
echo '% C onto F - skip of E'
hg rebase -s 2 -d 5 2>&1 | sed 's/\(saving bundle to \).*/\1/'
hg glog  --template '{rev}: {desc}\n'

createrepo > /dev/null 2>&1
echo '% D onto C - rebase of a branching point (skip E)'
hg rebase -s 3 -d 2 2>&1 | sed 's/\(saving bundle to \).*/\1/'
hg glog  --template '{rev}: {desc}\n'

createrepo > /dev/null 2>&1
echo '% E onto F - merged revision having a parent in ancestors of target'
hg rebase -s 4 -d 5 2>&1 | sed 's/\(saving bundle to \).*/\1/'
hg glog  --template '{rev}: {desc}\n'

createrepo > /dev/null 2>&1
echo '% D onto B - E maintains C as parent'
hg rebase -s 3 -d 1 2>&1 | sed 's/\(saving bundle to \).*/\1/'
hg glog  --template '{rev}: {desc}\n'

echo '% These will fail (using --source)'
createrepo > /dev/null 2>&1
echo '% E onto D - rebase onto an ancestor'
hg rebase -s 4 -d 3
echo '% D onto E - rebase onto a descendant'
hg rebase -s 3 -d 4
echo '% E onto B - merge revision with both parents not in ancestors of target'
hg rebase -s 4 -d 1

echo
echo '% These will abort gracefully (using --base)'
echo '% E onto E - rebase onto same changeset'
hg rebase -b 4 -d 4
echo '% E onto D - rebase onto an ancestor'
hg rebase -b 4 -d 3
echo '% D onto E - rebase onto a descendant'
hg rebase -b 3 -d 4

exit 0
