c9681178f7e65ca2c6ed62dc24347f2dbdbab429
   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        NEWHEAD=$(git rev-parse HEAD) &&
 380        case $HEADNAME in
 381        refs/*)
 382                message="$GIT_REFLOG_ACTION: $HEADNAME onto $SHORTONTO)" &&
 383                git update-ref -m "$message" $HEADNAME $NEWHEAD $OLDHEAD &&
 384                git symbolic-ref HEAD $HEADNAME
 385                ;;
 386        esac && {
 387                test ! -f "$DOTEST"/verbose ||
 388                        git diff-tree --stat $(cat "$DOTEST"/head)..HEAD
 389        } &&
 390        rm -rf "$DOTEST" &&
 391        git gc --auto &&
 392        warn "Successfully rebased and updated $HEADNAME."
 393
 394        exit
 395}
 396
 397do_rest () {
 398        while :
 399        do
 400                do_next
 401        done
 402}
 403
 404# check if no other options are set
 405is_standalone () {
 406        test $# -eq 2 -a "$2" = '--' &&
 407        test -z "$ONTO" &&
 408        test -z "$PRESERVE_MERGES" &&
 409        test -z "$STRATEGY" &&
 410        test -z "$VERBOSE"
 411}
 412
 413get_saved_options () {
 414        test -d "$REWRITTEN" && PRESERVE_MERGES=t
 415        test -f "$DOTEST"/strategy && STRATEGY="$(cat "$DOTEST"/strategy)"
 416        test -f "$DOTEST"/verbose && VERBOSE=t
 417}
 418
 419while test $# != 0
 420do
 421        case "$1" in
 422        --continue)
 423                is_standalone "$@" || usage
 424                get_saved_options
 425                comment_for_reflog continue
 426
 427                test -d "$DOTEST" || die "No interactive rebase running"
 428
 429                # Sanity check
 430                git rev-parse --verify HEAD >/dev/null ||
 431                        die "Cannot read HEAD"
 432                git update-index --ignore-submodules --refresh &&
 433                        git diff-files --quiet --ignore-submodules ||
 434                        die "Working tree is dirty"
 435
 436                # do we have anything to commit?
 437                if git diff-index --cached --quiet --ignore-submodules HEAD --
 438                then
 439                        : Nothing to commit -- skip this
 440                else
 441                        . "$DOTEST"/author-script ||
 442                                die "Cannot find the author identity"
 443                        amend=
 444                        if test -f "$DOTEST"/amend
 445                        then
 446                                amend=$(git rev-parse --verify HEAD)
 447                                test "$amend" = $(cat "$DOTEST"/amend) ||
 448                                die "\
 449You have uncommitted changes in your working tree. Please, commit them
 450first and then run 'git rebase --continue' again."
 451                                git reset --soft HEAD^ ||
 452                                die "Cannot rewind the HEAD"
 453                        fi
 454                        export GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_AUTHOR_DATE &&
 455                        git commit --no-verify -F "$DOTEST"/message -e || {
 456                                test -n "$amend" && git reset --soft $amend
 457                                die "Could not commit staged changes."
 458                        }
 459                fi
 460
 461                require_clean_work_tree
 462                do_rest
 463                ;;
 464        --abort)
 465                is_standalone "$@" || usage
 466                get_saved_options
 467                comment_for_reflog abort
 468
 469                git rerere clear
 470                test -d "$DOTEST" || die "No interactive rebase running"
 471
 472                HEADNAME=$(cat "$DOTEST"/head-name)
 473                HEAD=$(cat "$DOTEST"/head)
 474                case $HEADNAME in
 475                refs/*)
 476                        git symbolic-ref HEAD $HEADNAME
 477                        ;;
 478                esac &&
 479                output git reset --hard $HEAD &&
 480                rm -rf "$DOTEST"
 481                exit
 482                ;;
 483        --skip)
 484                is_standalone "$@" || usage
 485                get_saved_options
 486                comment_for_reflog skip
 487
 488                git rerere clear
 489                test -d "$DOTEST" || die "No interactive rebase running"
 490
 491                output git reset --hard && do_rest
 492                ;;
 493        -s)
 494                case "$#,$1" in
 495                *,*=*)
 496                        STRATEGY="-s "$(expr "z$1" : 'z-[^=]*=\(.*\)') ;;
 497                1,*)
 498                        usage ;;
 499                *)
 500                        STRATEGY="-s $2"
 501                        shift ;;
 502                esac
 503                ;;
 504        -m)
 505                # we use merge anyway
 506                ;;
 507        -v)
 508                VERBOSE=t
 509                ;;
 510        -p)
 511                PRESERVE_MERGES=t
 512                ;;
 513        -i)
 514                # yeah, we know
 515                ;;
 516        --onto)
 517                shift
 518                ONTO=$(git rev-parse --verify "$1") ||
 519                        die "Does not point to a valid commit: $1"
 520                ;;
 521        --)
 522                shift
 523                run_pre_rebase_hook ${1+"$@"}
 524                test $# -eq 1 -o $# -eq 2 || usage
 525                test -d "$DOTEST" &&
 526                        die "Interactive rebase already started"
 527
 528                git var GIT_COMMITTER_IDENT >/dev/null ||
 529                        die "You need to set your committer info first"
 530
 531                comment_for_reflog start
 532
 533                require_clean_work_tree
 534
 535                UPSTREAM=$(git rev-parse --verify "$1") || die "Invalid base"
 536                test -z "$ONTO" && ONTO=$UPSTREAM
 537
 538                if test ! -z "$2"
 539                then
 540                        output git show-ref --verify --quiet "refs/heads/$2" ||
 541                                die "Invalid branchname: $2"
 542                        output git checkout "$2" ||
 543                                die "Could not checkout $2"
 544                fi
 545
 546                HEAD=$(git rev-parse --verify HEAD) || die "No HEAD?"
 547                mkdir "$DOTEST" || die "Could not create temporary $DOTEST"
 548
 549                : > "$DOTEST"/interactive || die "Could not mark as interactive"
 550                git symbolic-ref HEAD > "$DOTEST"/head-name 2> /dev/null ||
 551                        echo "detached HEAD" > "$DOTEST"/head-name
 552
 553                echo $HEAD > "$DOTEST"/head
 554                echo $UPSTREAM > "$DOTEST"/upstream
 555                echo $ONTO > "$DOTEST"/onto
 556                test -z "$STRATEGY" || echo "$STRATEGY" > "$DOTEST"/strategy
 557                test t = "$VERBOSE" && : > "$DOTEST"/verbose
 558                if test t = "$PRESERVE_MERGES"
 559                then
 560                        # $REWRITTEN contains files for each commit that is
 561                        # reachable by at least one merge base of $HEAD and
 562                        # $UPSTREAM. They are not necessarily rewritten, but
 563                        # their children might be.
 564                        # This ensures that commits on merged, but otherwise
 565                        # unrelated side branches are left alone. (Think "X"
 566                        # in the man page's example.)
 567                        mkdir "$REWRITTEN" &&
 568                        for c in $(git merge-base --all $HEAD $UPSTREAM)
 569                        do
 570                                echo $ONTO > "$REWRITTEN"/$c ||
 571                                        die "Could not init rewritten commits"
 572                        done
 573                        MERGES_OPTION=
 574                else
 575                        MERGES_OPTION=--no-merges
 576                fi
 577
 578                SHORTUPSTREAM=$(git rev-parse --short $UPSTREAM)
 579                SHORTHEAD=$(git rev-parse --short $HEAD)
 580                SHORTONTO=$(git rev-parse --short $ONTO)
 581                git rev-list $MERGES_OPTION --pretty=oneline --abbrev-commit \
 582                        --abbrev=7 --reverse --left-right --cherry-pick \
 583                        $UPSTREAM...$HEAD | \
 584                        sed -n "s/^>/pick /p" > "$TODO"
 585                test -s "$TODO" || echo noop >> "$TODO"
 586                cat >> "$TODO" << EOF
 587
 588# Rebase $SHORTUPSTREAM..$SHORTHEAD onto $SHORTONTO
 589#
 590# Commands:
 591#  p, pick = use commit
 592#  e, edit = use commit, but stop for amending
 593#  s, squash = use commit, but meld into previous commit
 594#
 595# If you remove a line here THAT COMMIT WILL BE LOST.
 596# However, if you remove everything, the rebase will be aborted.
 597#
 598EOF
 599
 600                # Watch for commits that been dropped by --cherry-pick
 601                if test t = "$PRESERVE_MERGES"
 602                then
 603                        mkdir "$DROPPED"
 604                        # drop the --cherry-pick parameter this time
 605                        git rev-list $MERGES_OPTION --abbrev-commit \
 606                                --abbrev=7 $UPSTREAM...$HEAD --left-right | \
 607                                sed -n "s/^>//p" | while read rev
 608                        do
 609                                grep --quiet "$rev" "$TODO"
 610                                if [ $? -ne 0 ]
 611                                then
 612                                        # Use -f2 because if rev-list is telling this commit is not
 613                                        # worthwhile, we don't want to track its multiple heads,
 614                                        # just the history of its first-parent for others that will
 615                                        # be rebasing on top of us
 616                                        full=$(git rev-parse $rev)
 617                                        git rev-list --parents -1 $rev | cut -d' ' -f2 > "$DROPPED"/$full
 618                                fi
 619                        done
 620                fi
 621
 622                has_action "$TODO" ||
 623                        die_abort "Nothing to do"
 624
 625                cp "$TODO" "$TODO".backup
 626                git_editor "$TODO" ||
 627                        die "Could not execute editor"
 628
 629                has_action "$TODO" ||
 630                        die_abort "Nothing to do"
 631
 632                git update-ref ORIG_HEAD $HEAD
 633                output git checkout $ONTO && do_rest
 634                ;;
 635        esac
 636        shift
 637done