30e45237a2d9c126d9d3dd29737a09cb2de290a1
   1#!/bin/sh
   2#
   3# Copyright (c) 2006 Johannes E. Schindelin
   4
   5# SHORT DESCRIPTION
   6#
   7# This script makes it easy to fix up commits in the middle of a series,
   8# and rearrange commits.
   9#
  10# The original idea comes from Eric W. Biederman, in
  11# http://article.gmane.org/gmane.comp.version-control.git/22407
  12
  13OPTIONS_KEEPDASHDASH=
  14OPTIONS_SPEC="\
  15git-rebase [-i] [options] [--] <upstream> [<branch>]
  16git-rebase [-i] (--continue | --abort | --skip)
  17--
  18 Available options are
  19v,verbose          display a diffstat of what changed upstream
  20onto=              rebase onto given branch instead of upstream
  21p,preserve-merges  try to recreate merges instead of ignoring them
  22s,strategy=        use the given merge strategy
  23m,merge            always used (no-op)
  24i,interactive      always used (no-op)
  25 Actions:
  26continue           continue rebasing process
  27abort              abort rebasing process and restore original branch
  28skip               skip current patch and continue rebasing process
  29"
  30
  31. git-sh-setup
  32require_work_tree
  33
  34DOTEST="$GIT_DIR/rebase-merge"
  35TODO="$DOTEST"/git-rebase-todo
  36DONE="$DOTEST"/done
  37MSG="$DOTEST"/message
  38SQUASH_MSG="$DOTEST"/message-squash
  39REWRITTEN="$DOTEST"/rewritten
  40DROPPED="$DOTEST"/dropped
  41PRESERVE_MERGES=
  42STRATEGY=
  43ONTO=
  44VERBOSE=
  45
  46GIT_CHERRY_PICK_HELP="  After resolving the conflicts,
  47mark the corrected paths with 'git add <paths>', and
  48run 'git rebase --continue'"
  49export GIT_CHERRY_PICK_HELP
  50
  51warn () {
  52        echo "$*" >&2
  53}
  54
  55output () {
  56        case "$VERBOSE" in
  57        '')
  58                output=$("$@" 2>&1 )
  59                status=$?
  60                test $status != 0 && printf "%s\n" "$output"
  61                return $status
  62                ;;
  63        *)
  64                "$@"
  65                ;;
  66        esac
  67}
  68
  69run_pre_rebase_hook () {
  70        if test -x "$GIT_DIR/hooks/pre-rebase"
  71        then
  72                "$GIT_DIR/hooks/pre-rebase" ${1+"$@"} || {
  73                        echo >&2 "The pre-rebase hook refused to rebase."
  74                        exit 1
  75                }
  76        fi
  77}
  78
  79require_clean_work_tree () {
  80        # test if working tree is dirty
  81        git rev-parse --verify HEAD > /dev/null &&
  82        git update-index --ignore-submodules --refresh &&
  83        git diff-files --quiet --ignore-submodules &&
  84        git diff-index --cached --quiet HEAD --ignore-submodules -- ||
  85        die "Working tree is dirty"
  86}
  87
  88ORIG_REFLOG_ACTION="$GIT_REFLOG_ACTION"
  89
  90comment_for_reflog () {
  91        case "$ORIG_REFLOG_ACTION" in
  92        ''|rebase*)
  93                GIT_REFLOG_ACTION="rebase -i ($1)"
  94                export GIT_REFLOG_ACTION
  95                ;;
  96        esac
  97}
  98
  99last_count=
 100mark_action_done () {
 101        sed -e 1q < "$TODO" >> "$DONE"
 102        sed -e 1d < "$TODO" >> "$TODO".new
 103        mv -f "$TODO".new "$TODO"
 104        count=$(grep -c '^[^#]' < "$DONE")
 105        total=$(($count+$(grep -c '^[^#]' < "$TODO")))
 106        if test "$last_count" != "$count"
 107        then
 108                last_count=$count
 109                printf "Rebasing (%d/%d)\r" $count $total
 110                test -z "$VERBOSE" || echo
 111        fi
 112}
 113
 114make_patch () {
 115        parent_sha1=$(git rev-parse --verify "$1"^) ||
 116                die "Cannot get patch for $1^"
 117        git diff-tree -p "$parent_sha1".."$1" > "$DOTEST"/patch
 118        test -f "$DOTEST"/message ||
 119                git cat-file commit "$1" | sed "1,/^$/d" > "$DOTEST"/message
 120        test -f "$DOTEST"/author-script ||
 121                get_author_ident_from_commit "$1" > "$DOTEST"/author-script
 122}
 123
 124die_with_patch () {
 125        make_patch "$1"
 126        git rerere
 127        die "$2"
 128}
 129
 130die_abort () {
 131        rm -rf "$DOTEST"
 132        die "$1"
 133}
 134
 135has_action () {
 136        grep '^[^#]' "$1" >/dev/null
 137}
 138
 139pick_one () {
 140        no_ff=
 141        case "$1" in -n) sha1=$2; no_ff=t ;; *) sha1=$1 ;; esac
 142        output git rev-parse --verify $sha1 || die "Invalid commit name: $sha1"
 143        test -d "$REWRITTEN" &&
 144                pick_one_preserving_merges "$@" && return
 145        parent_sha1=$(git rev-parse --verify $sha1^) ||
 146                die "Could not get the parent of $sha1"
 147        current_sha1=$(git rev-parse --verify HEAD)
 148        if test "$no_ff$current_sha1" = "$parent_sha1"; then
 149                output git reset --hard $sha1
 150                test "a$1" = a-n && output git reset --soft $current_sha1
 151                sha1=$(git rev-parse --short $sha1)
 152                output warn Fast forward to $sha1
 153        else
 154                output git cherry-pick "$@"
 155        fi
 156}
 157
 158pick_one_preserving_merges () {
 159        fast_forward=t
 160        case "$1" in
 161        -n)
 162                fast_forward=f
 163                sha1=$2
 164                ;;
 165        *)
 166                sha1=$1
 167                ;;
 168        esac
 169        sha1=$(git rev-parse $sha1)
 170
 171        if test -f "$DOTEST"/current-commit
 172        then
 173                current_commit=$(cat "$DOTEST"/current-commit) &&
 174                git rev-parse HEAD > "$REWRITTEN"/$current_commit &&
 175                rm "$DOTEST"/current-commit ||
 176                die "Cannot write current commit's replacement sha1"
 177        fi
 178
 179        echo $sha1 > "$DOTEST"/current-commit
 180
 181        # rewrite parents; if none were rewritten, we can fast-forward.
 182        new_parents=
 183        pend=" $(git rev-list --parents -1 $sha1 | cut -d' ' -f2-)"
 184        while [ "$pend" != "" ]
 185        do
 186                p=$(expr "$pend" : ' \([^ ]*\)')
 187                pend="${pend# $p}"
 188
 189                if test -f "$REWRITTEN"/$p
 190                then
 191                        new_p=$(cat "$REWRITTEN"/$p)
 192                        test $p != $new_p && fast_forward=f
 193                        case "$new_parents" in
 194                        *$new_p*)
 195                                ;; # do nothing; that parent is already there
 196                        *)
 197                                new_parents="$new_parents $new_p"
 198                                ;;
 199                        esac
 200                else
 201                        if test -f "$DROPPED"/$p
 202                        then
 203                                fast_forward=f
 204                                pend=" $(cat "$DROPPED"/$p)$pend"
 205                        else
 206                                new_parents="$new_parents $p"
 207                        fi
 208                fi
 209        done
 210        case $fast_forward in
 211        t)
 212                output warn "Fast forward to $sha1"
 213                output git reset --hard $sha1 ||
 214                        die "Cannot fast forward to $sha1"
 215                ;;
 216        f)
 217                test "a$1" = a-n && die "Refusing to squash a merge: $sha1"
 218
 219                first_parent=$(expr "$new_parents" : ' \([^ ]*\)')
 220                # detach HEAD to current parent
 221                output git checkout $first_parent 2> /dev/null ||
 222                        die "Cannot move HEAD to $first_parent"
 223
 224                case "$new_parents" in
 225                ' '*' '*)
 226                        # redo merge
 227                        author_script=$(get_author_ident_from_commit $sha1)
 228                        eval "$author_script"
 229                        msg="$(git cat-file commit $sha1 | sed -e '1,/^$/d')"
 230                        # No point in merging the first parent, that's HEAD
 231                        new_parents=${new_parents# $first_parent}
 232                        if ! GIT_AUTHOR_NAME="$GIT_AUTHOR_NAME" \
 233                                GIT_AUTHOR_EMAIL="$GIT_AUTHOR_EMAIL" \
 234                                GIT_AUTHOR_DATE="$GIT_AUTHOR_DATE" \
 235                                output git merge $STRATEGY -m "$msg" \
 236                                        $new_parents
 237                        then
 238                                git rerere
 239                                printf "%s\n" "$msg" > "$GIT_DIR"/MERGE_MSG
 240                                die Error redoing merge $sha1
 241                        fi
 242                        ;;
 243                *)
 244                        output git cherry-pick "$@" ||
 245                                die_with_patch $sha1 "Could not pick $sha1"
 246                        ;;
 247                esac
 248                ;;
 249        esac
 250}
 251
 252nth_string () {
 253        case "$1" in
 254        *1[0-9]|*[04-9]) echo "$1"th;;
 255        *1) echo "$1"st;;
 256        *2) echo "$1"nd;;
 257        *3) echo "$1"rd;;
 258        esac
 259}
 260
 261make_squash_message () {
 262        if test -f "$SQUASH_MSG"; then
 263                COUNT=$(($(sed -n "s/^# This is [^0-9]*\([1-9][0-9]*\).*/\1/p" \
 264                        < "$SQUASH_MSG" | sed -ne '$p')+1))
 265                echo "# This is a combination of $COUNT commits."
 266                sed -e 1d -e '2,/^./{
 267                        /^$/d
 268                }' <"$SQUASH_MSG"
 269        else
 270                COUNT=2
 271                echo "# This is a combination of two commits."
 272                echo "# The first commit's message is:"
 273                echo
 274                git cat-file commit HEAD | sed -e '1,/^$/d'
 275        fi
 276        echo
 277        echo "# This is the $(nth_string $COUNT) commit message:"
 278        echo
 279        git cat-file commit $1 | sed -e '1,/^$/d'
 280}
 281
 282peek_next_command () {
 283        sed -n "1s/ .*$//p" < "$TODO"
 284}
 285
 286do_next () {
 287        rm -f "$DOTEST"/message "$DOTEST"/author-script \
 288                "$DOTEST"/amend || exit
 289        read command sha1 rest < "$TODO"
 290        case "$command" in
 291        '#'*|''|noop)
 292                mark_action_done
 293                ;;
 294        pick|p)
 295                comment_for_reflog pick
 296
 297                mark_action_done
 298                pick_one $sha1 ||
 299                        die_with_patch $sha1 "Could not apply $sha1... $rest"
 300                ;;
 301        edit|e)
 302                comment_for_reflog edit
 303
 304                mark_action_done
 305                pick_one $sha1 ||
 306                        die_with_patch $sha1 "Could not apply $sha1... $rest"
 307                make_patch $sha1
 308                git rev-parse --verify HEAD > "$DOTEST"/amend
 309                warn "Stopped at $sha1... $rest"
 310                warn "You can amend the commit now, with"
 311                warn
 312                warn "  git commit --amend"
 313                warn
 314                warn "Once you are satisfied with your changes, run"
 315                warn
 316                warn "  git rebase --continue"
 317                warn
 318                exit 0
 319                ;;
 320        squash|s)
 321                comment_for_reflog squash
 322
 323                has_action "$DONE" ||
 324                        die "Cannot 'squash' without a previous commit"
 325
 326                mark_action_done
 327                make_squash_message $sha1 > "$MSG"
 328                failed=f
 329                author_script=$(get_author_ident_from_commit HEAD)
 330                output git reset --soft HEAD^
 331                pick_one -n $sha1 || failed=t
 332                case "$(peek_next_command)" in
 333                squash|s)
 334                        EDIT_COMMIT=
 335                        USE_OUTPUT=output
 336                        MSG_OPT=-F
 337                        MSG_FILE="$MSG"
 338                        cp "$MSG" "$SQUASH_MSG"
 339                        ;;
 340                *)
 341                        EDIT_COMMIT=-e
 342                        USE_OUTPUT=
 343                        MSG_OPT=
 344                        MSG_FILE=
 345                        rm -f "$SQUASH_MSG" || exit
 346                        cp "$MSG" "$GIT_DIR"/SQUASH_MSG
 347                        rm -f "$GIT_DIR"/MERGE_MSG || exit
 348                        ;;
 349                esac
 350                echo "$author_script" > "$DOTEST"/author-script
 351                if test $failed = f
 352                then
 353                        # This is like --amend, but with a different message
 354                        eval "$author_script"
 355                        GIT_AUTHOR_NAME="$GIT_AUTHOR_NAME" \
 356                        GIT_AUTHOR_EMAIL="$GIT_AUTHOR_EMAIL" \
 357                        GIT_AUTHOR_DATE="$GIT_AUTHOR_DATE" \
 358                        $USE_OUTPUT git commit --no-verify $MSG_OPT "$MSG_FILE" $EDIT_COMMIT || failed=t
 359                fi
 360                if test $failed = t
 361                then
 362                        cp "$MSG" "$GIT_DIR"/MERGE_MSG
 363                        warn
 364                        warn "Could not apply $sha1... $rest"
 365                        die_with_patch $sha1 ""
 366                fi
 367                ;;
 368        *)
 369                warn "Unknown command: $command $sha1 $rest"
 370                die_with_patch $sha1 "Please fix this in the file $TODO."
 371                ;;
 372        esac
 373        test -s "$TODO" && return
 374
 375        comment_for_reflog finish &&
 376        HEADNAME=$(cat "$DOTEST"/head-name) &&
 377        OLDHEAD=$(cat "$DOTEST"/head) &&
 378        SHORTONTO=$(git rev-parse --short $(cat "$DOTEST"/onto)) &&
 379        if test -d "$REWRITTEN"
 380        then
 381                test -f "$DOTEST"/current-commit &&
 382                        current_commit=$(cat "$DOTEST"/current-commit) &&
 383                        git rev-parse HEAD > "$REWRITTEN"/$current_commit
 384                if test -f "$REWRITTEN"/$OLDHEAD
 385                then
 386                        NEWHEAD=$(cat "$REWRITTEN"/$OLDHEAD)
 387                else
 388                        NEWHEAD=$OLDHEAD
 389                fi
 390        else
 391                NEWHEAD=$(git rev-parse HEAD)
 392        fi &&
 393        case $HEADNAME in
 394        refs/*)
 395                message="$GIT_REFLOG_ACTION: $HEADNAME onto $SHORTONTO)" &&
 396                git update-ref -m "$message" $HEADNAME $NEWHEAD $OLDHEAD &&
 397                git symbolic-ref HEAD $HEADNAME
 398                ;;
 399        esac && {
 400                test ! -f "$DOTEST"/verbose ||
 401                        git diff-tree --stat $(cat "$DOTEST"/head)..HEAD
 402        } &&
 403        rm -rf "$DOTEST" &&
 404        git gc --auto &&
 405        warn "Successfully rebased and updated $HEADNAME."
 406
 407        exit
 408}
 409
 410do_rest () {
 411        while :
 412        do
 413                do_next
 414        done
 415}
 416
 417# check if no other options are set
 418is_standalone () {
 419        test $# -eq 2 -a "$2" = '--' &&
 420        test -z "$ONTO" &&
 421        test -z "$PRESERVE_MERGES" &&
 422        test -z "$STRATEGY" &&
 423        test -z "$VERBOSE"
 424}
 425
 426get_saved_options () {
 427        test -d "$REWRITTEN" && PRESERVE_MERGES=t
 428        test -f "$DOTEST"/strategy && STRATEGY="$(cat "$DOTEST"/strategy)"
 429        test -f "$DOTEST"/verbose && VERBOSE=t
 430}
 431
 432while test $# != 0
 433do
 434        case "$1" in
 435        --continue)
 436                is_standalone "$@" || usage
 437                get_saved_options
 438                comment_for_reflog continue
 439
 440                test -d "$DOTEST" || die "No interactive rebase running"
 441
 442                # Sanity check
 443                git rev-parse --verify HEAD >/dev/null ||
 444                        die "Cannot read HEAD"
 445                git update-index --ignore-submodules --refresh &&
 446                        git diff-files --quiet --ignore-submodules ||
 447                        die "Working tree is dirty"
 448
 449                # do we have anything to commit?
 450                if git diff-index --cached --quiet --ignore-submodules HEAD --
 451                then
 452                        : Nothing to commit -- skip this
 453                else
 454                        . "$DOTEST"/author-script ||
 455                                die "Cannot find the author identity"
 456                        amend=
 457                        if test -f "$DOTEST"/amend
 458                        then
 459                                amend=$(git rev-parse --verify HEAD)
 460                                test "$amend" = $(cat "$DOTEST"/amend) ||
 461                                die "\
 462You have uncommitted changes in your working tree. Please, commit them
 463first and then run 'git rebase --continue' again."
 464                                git reset --soft HEAD^ ||
 465                                die "Cannot rewind the HEAD"
 466                        fi
 467                        export GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_AUTHOR_DATE &&
 468                        git commit --no-verify -F "$DOTEST"/message -e || {
 469                                test -n "$amend" && git reset --soft $amend
 470                                die "Could not commit staged changes."
 471                        }
 472                fi
 473
 474                require_clean_work_tree
 475                do_rest
 476                ;;
 477        --abort)
 478                is_standalone "$@" || usage
 479                get_saved_options
 480                comment_for_reflog abort
 481
 482                git rerere clear
 483                test -d "$DOTEST" || die "No interactive rebase running"
 484
 485                HEADNAME=$(cat "$DOTEST"/head-name)
 486                HEAD=$(cat "$DOTEST"/head)
 487                case $HEADNAME in
 488                refs/*)
 489                        git symbolic-ref HEAD $HEADNAME
 490                        ;;
 491                esac &&
 492                output git reset --hard $HEAD &&
 493                rm -rf "$DOTEST"
 494                exit
 495                ;;
 496        --skip)
 497                is_standalone "$@" || usage
 498                get_saved_options
 499                comment_for_reflog skip
 500
 501                git rerere clear
 502                test -d "$DOTEST" || die "No interactive rebase running"
 503
 504                output git reset --hard && do_rest
 505                ;;
 506        -s)
 507                case "$#,$1" in
 508                *,*=*)
 509                        STRATEGY="-s "$(expr "z$1" : 'z-[^=]*=\(.*\)') ;;
 510                1,*)
 511                        usage ;;
 512                *)
 513                        STRATEGY="-s $2"
 514                        shift ;;
 515                esac
 516                ;;
 517        -m)
 518                # we use merge anyway
 519                ;;
 520        -v)
 521                VERBOSE=t
 522                ;;
 523        -p)
 524                PRESERVE_MERGES=t
 525                ;;
 526        -i)
 527                # yeah, we know
 528                ;;
 529        --onto)
 530                shift
 531                ONTO=$(git rev-parse --verify "$1") ||
 532                        die "Does not point to a valid commit: $1"
 533                ;;
 534        --)
 535                shift
 536                run_pre_rebase_hook ${1+"$@"}
 537                test $# -eq 1 -o $# -eq 2 || usage
 538                test -d "$DOTEST" &&
 539                        die "Interactive rebase already started"
 540
 541                git var GIT_COMMITTER_IDENT >/dev/null ||
 542                        die "You need to set your committer info first"
 543
 544                comment_for_reflog start
 545
 546                require_clean_work_tree
 547
 548                UPSTREAM=$(git rev-parse --verify "$1") || die "Invalid base"
 549                test -z "$ONTO" && ONTO=$UPSTREAM
 550
 551                if test ! -z "$2"
 552                then
 553                        output git show-ref --verify --quiet "refs/heads/$2" ||
 554                                die "Invalid branchname: $2"
 555                        output git checkout "$2" ||
 556                                die "Could not checkout $2"
 557                fi
 558
 559                HEAD=$(git rev-parse --verify HEAD) || die "No HEAD?"
 560                mkdir "$DOTEST" || die "Could not create temporary $DOTEST"
 561
 562                : > "$DOTEST"/interactive || die "Could not mark as interactive"
 563                git symbolic-ref HEAD > "$DOTEST"/head-name 2> /dev/null ||
 564                        echo "detached HEAD" > "$DOTEST"/head-name
 565
 566                echo $HEAD > "$DOTEST"/head
 567                echo $UPSTREAM > "$DOTEST"/upstream
 568                echo $ONTO > "$DOTEST"/onto
 569                test -z "$STRATEGY" || echo "$STRATEGY" > "$DOTEST"/strategy
 570                test t = "$VERBOSE" && : > "$DOTEST"/verbose
 571                if test t = "$PRESERVE_MERGES"
 572                then
 573                        # $REWRITTEN contains files for each commit that is
 574                        # reachable by at least one merge base of $HEAD and
 575                        # $UPSTREAM. They are not necessarily rewritten, but
 576                        # their children might be.
 577                        # This ensures that commits on merged, but otherwise
 578                        # unrelated side branches are left alone. (Think "X"
 579                        # in the man page's example.)
 580                        mkdir "$REWRITTEN" &&
 581                        for c in $(git merge-base --all $HEAD $UPSTREAM)
 582                        do
 583                                echo $ONTO > "$REWRITTEN"/$c ||
 584                                        die "Could not init rewritten commits"
 585                        done
 586                        MERGES_OPTION=
 587                else
 588                        MERGES_OPTION=--no-merges
 589                fi
 590
 591                SHORTUPSTREAM=$(git rev-parse --short $UPSTREAM)
 592                SHORTHEAD=$(git rev-parse --short $HEAD)
 593                SHORTONTO=$(git rev-parse --short $ONTO)
 594                git rev-list $MERGES_OPTION --pretty=oneline --abbrev-commit \
 595                        --abbrev=7 --reverse --left-right --cherry-pick \
 596                        $UPSTREAM...$HEAD | \
 597                        sed -n "s/^>/pick /p" > "$TODO"
 598                test -s "$TODO" || echo noop >> "$TODO"
 599                cat >> "$TODO" << EOF
 600
 601# Rebase $SHORTUPSTREAM..$SHORTHEAD onto $SHORTONTO
 602#
 603# Commands:
 604#  p, pick = use commit
 605#  e, edit = use commit, but stop for amending
 606#  s, squash = use commit, but meld into previous commit
 607#
 608# If you remove a line here THAT COMMIT WILL BE LOST.
 609# However, if you remove everything, the rebase will be aborted.
 610#
 611EOF
 612
 613                # Watch for commits that been dropped by --cherry-pick
 614                if test t = "$PRESERVE_MERGES"
 615                then
 616                        mkdir "$DROPPED"
 617                        # drop the --cherry-pick parameter this time
 618                        git rev-list $MERGES_OPTION --abbrev-commit \
 619                                --abbrev=7 $UPSTREAM...$HEAD --left-right | \
 620                                sed -n "s/^>//p" | while read rev
 621                        do
 622                                grep --quiet "$rev" "$TODO"
 623                                if [ $? -ne 0 ]
 624                                then
 625                                        # Use -f2 because if rev-list is telling this commit is not
 626                                        # worthwhile, we don't want to track its multiple heads,
 627                                        # just the history of its first-parent for others that will
 628                                        # be rebasing on top of us
 629                                        full=$(git rev-parse $rev)
 630                                        git rev-list --parents -1 $rev | cut -d' ' -f2 > "$DROPPED"/$full
 631                                fi
 632                        done
 633                fi
 634
 635                has_action "$TODO" ||
 636                        die_abort "Nothing to do"
 637
 638                cp "$TODO" "$TODO".backup
 639                git_editor "$TODO" ||
 640                        die "Could not execute editor"
 641
 642                has_action "$TODO" ||
 643                        die_abort "Nothing to do"
 644
 645                git update-ref ORIG_HEAD $HEAD
 646                output git checkout $ONTO && do_rest
 647                ;;
 648        esac
 649        shift
 650done