git-am.shon commit t3418: non-interactive rebase --continue with rerere enabled (0f62fba)
   1#!/bin/sh
   2#
   3# Copyright (c) 2005, 2006 Junio C Hamano
   4
   5SUBDIRECTORY_OK=Yes
   6OPTIONS_KEEPDASHDASH=
   7OPTIONS_STUCKLONG=t
   8OPTIONS_SPEC="\
   9git am [options] [(<mbox>|<Maildir>)...]
  10git am [options] (--continue | --skip | --abort)
  11--
  12i,interactive   run interactively
  13b,binary*       (historical option -- no-op)
  143,3way          allow fall back on 3way merging if needed
  15q,quiet         be quiet
  16s,signoff       add a Signed-off-by line to the commit message
  17u,utf8          recode into utf8 (default)
  18k,keep          pass -k flag to git-mailinfo
  19keep-non-patch  pass -b flag to git-mailinfo
  20m,message-id    pass -m flag to git-mailinfo
  21keep-cr         pass --keep-cr flag to git-mailsplit for mbox format
  22no-keep-cr      do not pass --keep-cr flag to git-mailsplit independent of am.keepcr
  23c,scissors      strip everything before a scissors line
  24whitespace=     pass it through git-apply
  25ignore-space-change pass it through git-apply
  26ignore-whitespace pass it through git-apply
  27directory=      pass it through git-apply
  28exclude=        pass it through git-apply
  29include=        pass it through git-apply
  30C=              pass it through git-apply
  31p=              pass it through git-apply
  32patch-format=   format the patch(es) are in
  33reject          pass it through git-apply
  34resolvemsg=     override error message when patch failure occurs
  35continue        continue applying patches after resolving a conflict
  36r,resolved      synonyms for --continue
  37skip            skip the current patch
  38abort           restore the original branch and abort the patching operation.
  39committer-date-is-author-date    lie about committer date
  40ignore-date     use current timestamp for author date
  41rerere-autoupdate update the index with reused conflict resolution if possible
  42S,gpg-sign?     GPG-sign commits
  43rebasing*       (internal use for git-rebase)"
  44
  45. git-sh-setup
  46. git-sh-i18n
  47prefix=$(git rev-parse --show-prefix)
  48set_reflog_action am
  49require_work_tree
  50cd_to_toplevel
  51
  52git var GIT_COMMITTER_IDENT >/dev/null ||
  53        die "$(gettext "You need to set your committer info first")"
  54
  55if git rev-parse --verify -q HEAD >/dev/null
  56then
  57        HAS_HEAD=yes
  58else
  59        HAS_HEAD=
  60fi
  61
  62cmdline="git am"
  63if test '' != "$interactive"
  64then
  65        cmdline="$cmdline -i"
  66fi
  67if test '' != "$threeway"
  68then
  69        cmdline="$cmdline -3"
  70fi
  71
  72empty_tree=4b825dc642cb6eb9a060e54bf8d69288fbee4904
  73
  74sq () {
  75        git rev-parse --sq-quote "$@"
  76}
  77
  78stop_here () {
  79    echo "$1" >"$dotest/next"
  80    git rev-parse --verify -q HEAD >"$dotest/abort-safety"
  81    exit 1
  82}
  83
  84safe_to_abort () {
  85        if test -f "$dotest/dirtyindex"
  86        then
  87                return 1
  88        fi
  89
  90        if ! test -f "$dotest/abort-safety"
  91        then
  92                return 0
  93        fi
  94
  95        abort_safety=$(cat "$dotest/abort-safety")
  96        if test "z$(git rev-parse --verify -q HEAD)" = "z$abort_safety"
  97        then
  98                return 0
  99        fi
 100        gettextln "You seem to have moved HEAD since the last 'am' failure.
 101Not rewinding to ORIG_HEAD" >&2
 102        return 1
 103}
 104
 105stop_here_user_resolve () {
 106    if [ -n "$resolvemsg" ]; then
 107            printf '%s\n' "$resolvemsg"
 108            stop_here $1
 109    fi
 110    eval_gettextln "When you have resolved this problem, run \"\$cmdline --continue\".
 111If you prefer to skip this patch, run \"\$cmdline --skip\" instead.
 112To restore the original branch and stop patching, run \"\$cmdline --abort\"."
 113
 114    stop_here $1
 115}
 116
 117go_next () {
 118        rm -f "$dotest/$msgnum" "$dotest/msg" "$dotest/msg-clean" \
 119                "$dotest/patch" "$dotest/info"
 120        echo "$next" >"$dotest/next"
 121        this=$next
 122}
 123
 124cannot_fallback () {
 125        echo "$1"
 126        gettextln "Cannot fall back to three-way merge."
 127        exit 1
 128}
 129
 130fall_back_3way () {
 131    O_OBJECT=$(cd "$GIT_OBJECT_DIRECTORY" && pwd)
 132
 133    rm -fr "$dotest"/patch-merge-*
 134    mkdir "$dotest/patch-merge-tmp-dir"
 135
 136    # First see if the patch records the index info that we can use.
 137    cmd="git apply $git_apply_opt --build-fake-ancestor" &&
 138    cmd="$cmd "'"$dotest/patch-merge-tmp-index" "$dotest/patch"' &&
 139    eval "$cmd" &&
 140    GIT_INDEX_FILE="$dotest/patch-merge-tmp-index" \
 141    git write-tree >"$dotest/patch-merge-base+" ||
 142    cannot_fallback "$(gettext "Repository lacks necessary blobs to fall back on 3-way merge.")"
 143
 144    say "$(gettext "Using index info to reconstruct a base tree...")"
 145
 146    cmd='GIT_INDEX_FILE="$dotest/patch-merge-tmp-index"'
 147
 148    if test -z "$GIT_QUIET"
 149    then
 150        eval "$cmd git diff-index --cached --diff-filter=AM --name-status HEAD"
 151    fi
 152
 153    cmd="$cmd git apply --cached $git_apply_opt"' <"$dotest/patch"'
 154    if eval "$cmd"
 155    then
 156        mv "$dotest/patch-merge-base+" "$dotest/patch-merge-base"
 157        mv "$dotest/patch-merge-tmp-index" "$dotest/patch-merge-index"
 158    else
 159        cannot_fallback "$(gettext "Did you hand edit your patch?
 160It does not apply to blobs recorded in its index.")"
 161    fi
 162
 163    test -f "$dotest/patch-merge-index" &&
 164    his_tree=$(GIT_INDEX_FILE="$dotest/patch-merge-index" git write-tree) &&
 165    orig_tree=$(cat "$dotest/patch-merge-base") &&
 166    rm -fr "$dotest"/patch-merge-* || exit 1
 167
 168    say "$(gettext "Falling back to patching base and 3-way merge...")"
 169
 170    # This is not so wrong.  Depending on which base we picked,
 171    # orig_tree may be wildly different from ours, but his_tree
 172    # has the same set of wildly different changes in parts the
 173    # patch did not touch, so recursive ends up canceling them,
 174    # saying that we reverted all those changes.
 175
 176    eval GITHEAD_$his_tree='"$FIRSTLINE"'
 177    export GITHEAD_$his_tree
 178    if test -n "$GIT_QUIET"
 179    then
 180            GIT_MERGE_VERBOSITY=0 && export GIT_MERGE_VERBOSITY
 181    fi
 182    our_tree=$(git rev-parse --verify -q HEAD || echo $empty_tree)
 183    git-merge-recursive $orig_tree -- $our_tree $his_tree || {
 184            git rerere $allow_rerere_autoupdate
 185            die "$(gettext "Failed to merge in the changes.")"
 186    }
 187    unset GITHEAD_$his_tree
 188}
 189
 190clean_abort () {
 191        test $# = 0 || echo >&2 "$@"
 192        rm -fr "$dotest"
 193        exit 1
 194}
 195
 196patch_format=
 197
 198check_patch_format () {
 199        # early return if patch_format was set from the command line
 200        if test -n "$patch_format"
 201        then
 202                return 0
 203        fi
 204
 205        # we default to mbox format if input is from stdin and for
 206        # directories
 207        if test $# = 0 || test "x$1" = "x-" || test -d "$1"
 208        then
 209                patch_format=mbox
 210                return 0
 211        fi
 212
 213        # otherwise, check the first few non-blank lines of the first
 214        # patch to try to detect its format
 215        {
 216                # Start from first line containing non-whitespace
 217                l1=
 218                while test -z "$l1"
 219                do
 220                        read l1 || break
 221                done
 222                read l2
 223                read l3
 224                case "$l1" in
 225                "From "* | "From: "*)
 226                        patch_format=mbox
 227                        ;;
 228                '# This series applies on GIT commit'*)
 229                        patch_format=stgit-series
 230                        ;;
 231                "# HG changeset patch")
 232                        patch_format=hg
 233                        ;;
 234                *)
 235                        # if the second line is empty and the third is
 236                        # a From, Author or Date entry, this is very
 237                        # likely an StGIT patch
 238                        case "$l2,$l3" in
 239                        ,"From: "* | ,"Author: "* | ,"Date: "*)
 240                                patch_format=stgit
 241                                ;;
 242                        *)
 243                                ;;
 244                        esac
 245                        ;;
 246                esac
 247                if test -z "$patch_format" &&
 248                        test -n "$l1" &&
 249                        test -n "$l2" &&
 250                        test -n "$l3"
 251                then
 252                        # This begins with three non-empty lines.  Is this a
 253                        # piece of e-mail a-la RFC2822?  Grab all the headers,
 254                        # discarding the indented remainder of folded lines,
 255                        # and see if it looks like that they all begin with the
 256                        # header field names...
 257                        tr -d '\015' <"$1" |
 258                        sed -n -e '/^$/q' -e '/^[       ]/d' -e p |
 259                        sane_egrep -v '^[!-9;-~]+:' >/dev/null ||
 260                        patch_format=mbox
 261                fi
 262        } < "$1" || clean_abort
 263}
 264
 265split_patches () {
 266        case "$patch_format" in
 267        mbox)
 268                if test t = "$keepcr"
 269                then
 270                    keep_cr=--keep-cr
 271                else
 272                    keep_cr=
 273                fi
 274                git mailsplit -d"$prec" -o"$dotest" -b $keep_cr -- "$@" > "$dotest/last" ||
 275                clean_abort
 276                ;;
 277        stgit-series)
 278                if test $# -ne 1
 279                then
 280                        clean_abort "$(gettext "Only one StGIT patch series can be applied at once")"
 281                fi
 282                series_dir=$(dirname "$1")
 283                series_file="$1"
 284                shift
 285                {
 286                        set x
 287                        while read filename
 288                        do
 289                                set "$@" "$series_dir/$filename"
 290                        done
 291                        # remove the safety x
 292                        shift
 293                        # remove the arg coming from the first-line comment
 294                        shift
 295                } < "$series_file" || clean_abort
 296                # set the patch format appropriately
 297                patch_format=stgit
 298                # now handle the actual StGIT patches
 299                split_patches "$@"
 300                ;;
 301        stgit)
 302                this=0
 303                for stgit in "$@"
 304                do
 305                        this=$(expr "$this" + 1)
 306                        msgnum=$(printf "%0${prec}d" $this)
 307                        # Perl version of StGIT parse_patch. The first nonemptyline
 308                        # not starting with Author, From or Date is the
 309                        # subject, and the body starts with the next nonempty
 310                        # line not starting with Author, From or Date
 311                        @@PERL@@ -ne 'BEGIN { $subject = 0 }
 312                                if ($subject > 1) { print ; }
 313                                elsif (/^\s+$/) { next ; }
 314                                elsif (/^Author:/) { s/Author/From/ ; print ;}
 315                                elsif (/^(From|Date)/) { print ; }
 316                                elsif ($subject) {
 317                                        $subject = 2 ;
 318                                        print "\n" ;
 319                                        print ;
 320                                } else {
 321                                        print "Subject: ", $_ ;
 322                                        $subject = 1;
 323                                }
 324                        ' < "$stgit" > "$dotest/$msgnum" || clean_abort
 325                done
 326                echo "$this" > "$dotest/last"
 327                this=
 328                msgnum=
 329                ;;
 330        hg)
 331                this=0
 332                for hg in "$@"
 333                do
 334                        this=$(( $this + 1 ))
 335                        msgnum=$(printf "%0${prec}d" $this)
 336                        # hg stores changeset metadata in #-commented lines preceding
 337                        # the commit message and diff(s). The only metadata we care about
 338                        # are the User and Date (Node ID and Parent are hashes which are
 339                        # only relevant to the hg repository and thus not useful to us)
 340                        # Since we cannot guarantee that the commit message is in
 341                        # git-friendly format, we put no Subject: line and just consume
 342                        # all of the message as the body
 343                        LANG=C LC_ALL=C @@PERL@@ -M'POSIX qw(strftime)' -ne 'BEGIN { $subject = 0 }
 344                                if ($subject) { print ; }
 345                                elsif (/^\# User /) { s/\# User/From:/ ; print ; }
 346                                elsif (/^\# Date /) {
 347                                        my ($hashsign, $str, $time, $tz) = split ;
 348                                        $tz = sprintf "%+05d", (0-$tz)/36;
 349                                        print "Date: " .
 350                                              strftime("%a, %d %b %Y %H:%M:%S ",
 351                                                       localtime($time))
 352                                              . "$tz\n";
 353                                } elsif (/^\# /) { next ; }
 354                                else {
 355                                        print "\n", $_ ;
 356                                        $subject = 1;
 357                                }
 358                        ' <"$hg" >"$dotest/$msgnum" || clean_abort
 359                done
 360                echo "$this" >"$dotest/last"
 361                this=
 362                msgnum=
 363                ;;
 364        *)
 365                if test -n "$patch_format"
 366                then
 367                        clean_abort "$(eval_gettext "Patch format \$patch_format is not supported.")"
 368                else
 369                        clean_abort "$(gettext "Patch format detection failed.")"
 370                fi
 371                ;;
 372        esac
 373}
 374
 375prec=4
 376dotest="$GIT_DIR/rebase-apply"
 377sign= utf8=t keep= keepcr= skip= interactive= resolved= rebasing= abort=
 378messageid= resolvemsg= resume= scissors= no_inbody_headers=
 379git_apply_opt=
 380committer_date_is_author_date=
 381ignore_date=
 382allow_rerere_autoupdate=
 383gpg_sign_opt=
 384threeway=
 385
 386if test "$(git config --bool --get am.messageid)" = true
 387then
 388    messageid=t
 389fi
 390
 391if test "$(git config --bool --get am.keepcr)" = true
 392then
 393    keepcr=t
 394fi
 395
 396if test "$(git config --bool --get am.threeWay)" = true
 397then
 398    threeway=t
 399fi
 400
 401while test $# != 0
 402do
 403        case "$1" in
 404        -i|--interactive)
 405                interactive=t ;;
 406        -b|--binary)
 407                gettextln >&2 "The -b/--binary option has been a no-op for long time, and
 408it will be removed. Please do not use it anymore."
 409                ;;
 410        -3|--3way)
 411                threeway=t ;;
 412        --no-3way)
 413                threeway=f ;;
 414        -s|--signoff)
 415                sign=t ;;
 416        -u|--utf8)
 417                utf8=t ;; # this is now default
 418        --no-utf8)
 419                utf8= ;;
 420        -m|--message-id)
 421                messageid=t ;;
 422        --no-message-id)
 423                messageid=f ;;
 424        -k|--keep)
 425                keep=t ;;
 426        --keep-non-patch)
 427                keep=b ;;
 428        -c|--scissors)
 429                scissors=t ;;
 430        --no-scissors)
 431                scissors=f ;;
 432        -r|--resolved|--continue)
 433                resolved=t ;;
 434        --skip)
 435                skip=t ;;
 436        --abort)
 437                abort=t ;;
 438        --rebasing)
 439                rebasing=t threeway=t ;;
 440        --resolvemsg=*)
 441                resolvemsg="${1#--resolvemsg=}" ;;
 442        --whitespace=*|--directory=*|--exclude=*|--include=*)
 443                git_apply_opt="$git_apply_opt $(sq "$1")" ;;
 444        -C*|-p*)
 445                git_apply_opt="$git_apply_opt $(sq "$1")" ;;
 446        --patch-format=*)
 447                patch_format="${1#--patch-format=}" ;;
 448        --reject|--ignore-whitespace|--ignore-space-change)
 449                git_apply_opt="$git_apply_opt $1" ;;
 450        --committer-date-is-author-date)
 451                committer_date_is_author_date=t ;;
 452        --ignore-date)
 453                ignore_date=t ;;
 454        --rerere-autoupdate|--no-rerere-autoupdate)
 455                allow_rerere_autoupdate="$1" ;;
 456        -q|--quiet)
 457                GIT_QUIET=t ;;
 458        --keep-cr)
 459                keepcr=t ;;
 460        --no-keep-cr)
 461                keepcr=f ;;
 462        --gpg-sign)
 463                gpg_sign_opt=-S ;;
 464        --gpg-sign=*)
 465                gpg_sign_opt="-S${1#--gpg-sign=}" ;;
 466        --)
 467                shift; break ;;
 468        *)
 469                usage ;;
 470        esac
 471        shift
 472done
 473
 474# If the dotest directory exists, but we have finished applying all the
 475# patches in them, clear it out.
 476if test -d "$dotest" &&
 477   test -f "$dotest/last" &&
 478   test -f "$dotest/next" &&
 479   last=$(cat "$dotest/last") &&
 480   next=$(cat "$dotest/next") &&
 481   test $# != 0 &&
 482   test "$next" -gt "$last"
 483then
 484   rm -fr "$dotest"
 485fi
 486
 487if test -d "$dotest" && test -f "$dotest/last" && test -f "$dotest/next"
 488then
 489        case "$#,$skip$resolved$abort" in
 490        0,*t*)
 491                # Explicit resume command and we do not have file, so
 492                # we are happy.
 493                : ;;
 494        0,)
 495                # No file input but without resume parameters; catch
 496                # user error to feed us a patch from standard input
 497                # when there is already $dotest.  This is somewhat
 498                # unreliable -- stdin could be /dev/null for example
 499                # and the caller did not intend to feed us a patch but
 500                # wanted to continue unattended.
 501                test -t 0
 502                ;;
 503        *)
 504                false
 505                ;;
 506        esac ||
 507        die "$(eval_gettext "previous rebase directory \$dotest still exists but mbox given.")"
 508        resume=yes
 509
 510        case "$skip,$abort" in
 511        t,t)
 512                die "$(gettext "Please make up your mind. --skip or --abort?")"
 513                ;;
 514        t,)
 515                git rerere clear
 516                head_tree=$(git rev-parse --verify -q HEAD || echo $empty_tree) &&
 517                git read-tree --reset -u $head_tree $head_tree &&
 518                index_tree=$(git write-tree) &&
 519                git read-tree -m -u $index_tree $head_tree
 520                git read-tree $head_tree
 521                ;;
 522        ,t)
 523                if test -f "$dotest/rebasing"
 524                then
 525                        exec git rebase --abort
 526                fi
 527                git rerere clear
 528                if safe_to_abort
 529                then
 530                        head_tree=$(git rev-parse --verify -q HEAD || echo $empty_tree) &&
 531                        git read-tree --reset -u $head_tree $head_tree &&
 532                        index_tree=$(git write-tree) &&
 533                        orig_head=$(git rev-parse --verify -q ORIG_HEAD || echo $empty_tree) &&
 534                        git read-tree -m -u $index_tree $orig_head
 535                        if git rev-parse --verify -q ORIG_HEAD >/dev/null 2>&1
 536                        then
 537                                git reset ORIG_HEAD
 538                        else
 539                                git read-tree $empty_tree
 540                                curr_branch=$(git symbolic-ref HEAD 2>/dev/null) &&
 541                                git update-ref -d $curr_branch
 542                        fi
 543                fi
 544                rm -fr "$dotest"
 545                exit ;;
 546        esac
 547        rm -f "$dotest/dirtyindex"
 548else
 549        # Possible stray $dotest directory in the independent-run
 550        # case; in the --rebasing case, it is upto the caller
 551        # (git-rebase--am) to take care of stray directories.
 552        if test -d "$dotest" && test -z "$rebasing"
 553        then
 554                case "$skip,$resolved,$abort" in
 555                ,,t)
 556                        rm -fr "$dotest"
 557                        exit 0
 558                        ;;
 559                *)
 560                        die "$(eval_gettext "Stray \$dotest directory found.
 561Use \"git am --abort\" to remove it.")"
 562                        ;;
 563                esac
 564        fi
 565
 566        # Make sure we are not given --skip, --continue, or --abort
 567        test "$skip$resolved$abort" = "" ||
 568                die "$(gettext "Resolve operation not in progress, we are not resuming.")"
 569
 570        # Start afresh.
 571        mkdir -p "$dotest" || exit
 572
 573        if test -n "$prefix" && test $# != 0
 574        then
 575                first=t
 576                for arg
 577                do
 578                        test -n "$first" && {
 579                                set x
 580                                first=
 581                        }
 582                        if is_absolute_path "$arg"
 583                        then
 584                                set "$@" "$arg"
 585                        else
 586                                set "$@" "$prefix$arg"
 587                        fi
 588                done
 589                shift
 590        fi
 591
 592        check_patch_format "$@"
 593
 594        split_patches "$@"
 595
 596        # -i can and must be given when resuming; everything
 597        # else is kept
 598        echo " $git_apply_opt" >"$dotest/apply-opt"
 599        echo "$threeway" >"$dotest/threeway"
 600        echo "$sign" >"$dotest/sign"
 601        echo "$utf8" >"$dotest/utf8"
 602        echo "$keep" >"$dotest/keep"
 603        echo "$messageid" >"$dotest/messageid"
 604        echo "$scissors" >"$dotest/scissors"
 605        echo "$no_inbody_headers" >"$dotest/no_inbody_headers"
 606        echo "$GIT_QUIET" >"$dotest/quiet"
 607        echo 1 >"$dotest/next"
 608        if test -n "$rebasing"
 609        then
 610                : >"$dotest/rebasing"
 611        else
 612                : >"$dotest/applying"
 613                if test -n "$HAS_HEAD"
 614                then
 615                        git update-ref ORIG_HEAD HEAD
 616                else
 617                        git update-ref -d ORIG_HEAD >/dev/null 2>&1
 618                fi
 619        fi
 620fi
 621
 622git update-index -q --refresh
 623
 624case "$resolved" in
 625'')
 626        case "$HAS_HEAD" in
 627        '')
 628                files=$(git ls-files) ;;
 629        ?*)
 630                files=$(git diff-index --cached --name-only HEAD --) ;;
 631        esac || exit
 632        if test "$files"
 633        then
 634                test -n "$HAS_HEAD" && : >"$dotest/dirtyindex"
 635                die "$(eval_gettext "Dirty index: cannot apply patches (dirty: \$files)")"
 636        fi
 637esac
 638
 639# Now, decide what command line options we will give to the git
 640# commands we invoke, based on the result of parsing command line
 641# options and previous invocation state stored in $dotest/ files.
 642
 643if test "$(cat "$dotest/utf8")" = t
 644then
 645        utf8=-u
 646else
 647        utf8=-n
 648fi
 649keep=$(cat "$dotest/keep")
 650case "$keep" in
 651t)
 652        keep=-k ;;
 653b)
 654        keep=-b ;;
 655*)
 656        keep= ;;
 657esac
 658case "$(cat "$dotest/messageid")" in
 659t)
 660        messageid=-m ;;
 661f)
 662        messageid= ;;
 663esac
 664case "$(cat "$dotest/scissors")" in
 665t)
 666        scissors=--scissors ;;
 667f)
 668        scissors=--no-scissors ;;
 669esac
 670if test "$(cat "$dotest/no_inbody_headers")" = t
 671then
 672        no_inbody_headers=--no-inbody-headers
 673else
 674        no_inbody_headers=
 675fi
 676if test "$(cat "$dotest/quiet")" = t
 677then
 678        GIT_QUIET=t
 679fi
 680if test "$(cat "$dotest/threeway")" = t
 681then
 682        threeway=t
 683else
 684        threeway=f
 685fi
 686git_apply_opt=$(cat "$dotest/apply-opt")
 687if test "$(cat "$dotest/sign")" = t
 688then
 689        SIGNOFF=$(git var GIT_COMMITTER_IDENT | sed -e '
 690                        s/>.*/>/
 691                        s/^/Signed-off-by: /'
 692                )
 693else
 694        SIGNOFF=
 695fi
 696
 697last=$(cat "$dotest/last")
 698this=$(cat "$dotest/next")
 699if test "$skip" = t
 700then
 701        this=$(expr "$this" + 1)
 702        resume=
 703fi
 704
 705while test "$this" -le "$last"
 706do
 707        msgnum=$(printf "%0${prec}d" $this)
 708        next=$(expr "$this" + 1)
 709        test -f "$dotest/$msgnum" || {
 710                resume=
 711                go_next
 712                continue
 713        }
 714
 715        # If we are not resuming, parse and extract the patch information
 716        # into separate files:
 717        #  - info records the authorship and title
 718        #  - msg is the rest of commit log message
 719        #  - patch is the patch body.
 720        #
 721        # When we are resuming, these files are either already prepared
 722        # by the user, or the user can tell us to do so by --continue flag.
 723        case "$resume" in
 724        '')
 725                if test -f "$dotest/rebasing"
 726                then
 727                        commit=$(sed -e 's/^From \([0-9a-f]*\) .*/\1/' \
 728                                -e q "$dotest/$msgnum") &&
 729                        test "$(git cat-file -t "$commit")" = commit ||
 730                                stop_here $this
 731                        git cat-file commit "$commit" |
 732                        sed -e '1,/^$/d' >"$dotest/msg-clean"
 733                        echo "$commit" >"$dotest/original-commit"
 734                        get_author_ident_from_commit "$commit" >"$dotest/author-script"
 735                        git diff-tree --root --binary --full-index "$commit" >"$dotest/patch"
 736                else
 737                        git mailinfo $keep $no_inbody_headers $messageid $scissors $utf8 "$dotest/msg" "$dotest/patch" \
 738                                <"$dotest/$msgnum" >"$dotest/info" ||
 739                                stop_here $this
 740
 741                        # skip pine's internal folder data
 742                        sane_grep '^Author: Mail System Internal Data$' \
 743                                <"$dotest"/info >/dev/null &&
 744                                go_next && continue
 745
 746                        test -s "$dotest/patch" || {
 747                                eval_gettextln "Patch is empty.  Was it split wrong?
 748If you would prefer to skip this patch, instead run \"\$cmdline --skip\".
 749To restore the original branch and stop patching run \"\$cmdline --abort\"."
 750                                stop_here $this
 751                        }
 752                        rm -f "$dotest/original-commit" "$dotest/author-script"
 753                        {
 754                                sed -n '/^Subject/ s/Subject: //p' "$dotest/info"
 755                                echo
 756                                cat "$dotest/msg"
 757                        } |
 758                        git stripspace > "$dotest/msg-clean"
 759                fi
 760                ;;
 761        esac
 762
 763        if test -f "$dotest/author-script"
 764        then
 765                eval $(cat "$dotest/author-script")
 766        else
 767                GIT_AUTHOR_NAME="$(sed -n '/^Author/ s/Author: //p' "$dotest/info")"
 768                GIT_AUTHOR_EMAIL="$(sed -n '/^Email/ s/Email: //p' "$dotest/info")"
 769                GIT_AUTHOR_DATE="$(sed -n '/^Date/ s/Date: //p' "$dotest/info")"
 770        fi
 771
 772        if test -z "$GIT_AUTHOR_EMAIL"
 773        then
 774                gettextln "Patch does not have a valid e-mail address."
 775                stop_here $this
 776        fi
 777
 778        export GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_AUTHOR_DATE
 779
 780        case "$resume" in
 781        '')
 782            if test '' != "$SIGNOFF"
 783            then
 784                LAST_SIGNED_OFF_BY=$(
 785                    sed -ne '/^Signed-off-by: /p' \
 786                    "$dotest/msg-clean" |
 787                    sed -ne '$p'
 788                )
 789                ADD_SIGNOFF=$(
 790                    test "$LAST_SIGNED_OFF_BY" = "$SIGNOFF" || {
 791                    test '' = "$LAST_SIGNED_OFF_BY" && echo
 792                    echo "$SIGNOFF"
 793                })
 794            else
 795                ADD_SIGNOFF=
 796            fi
 797            {
 798                if test -s "$dotest/msg-clean"
 799                then
 800                        cat "$dotest/msg-clean"
 801                fi
 802                if test '' != "$ADD_SIGNOFF"
 803                then
 804                        echo "$ADD_SIGNOFF"
 805                fi
 806            } >"$dotest/final-commit"
 807            ;;
 808        *)
 809                case "$resolved$interactive" in
 810                tt)
 811                        # This is used only for interactive view option.
 812                        git diff-index -p --cached HEAD -- >"$dotest/patch"
 813                        ;;
 814                esac
 815        esac
 816
 817        resume=
 818        if test "$interactive" = t
 819        then
 820            test -t 0 ||
 821            die "$(gettext "cannot be interactive without stdin connected to a terminal.")"
 822            action=again
 823            while test "$action" = again
 824            do
 825                gettextln "Commit Body is:"
 826                echo "--------------------------"
 827                cat "$dotest/final-commit"
 828                echo "--------------------------"
 829                # TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
 830                # in your translation. The program will only accept English
 831                # input at this point.
 832                gettext "Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all "
 833                read reply
 834                case "$reply" in
 835                [yY]*) action=yes ;;
 836                [aA]*) action=yes interactive= ;;
 837                [nN]*) action=skip ;;
 838                [eE]*) git_editor "$dotest/final-commit"
 839                       action=again ;;
 840                [vV]*) action=again
 841                       git_pager "$dotest/patch" ;;
 842                *)     action=again ;;
 843                esac
 844            done
 845        else
 846            action=yes
 847        fi
 848
 849        if test $action = skip
 850        then
 851                go_next
 852                continue
 853        fi
 854
 855        hook="$(git rev-parse --git-path hooks/applypatch-msg)"
 856        if test -x "$hook"
 857        then
 858                "$hook" "$dotest/final-commit" || stop_here $this
 859        fi
 860
 861        if test -f "$dotest/final-commit"
 862        then
 863                FIRSTLINE=$(sed 1q "$dotest/final-commit")
 864        else
 865                FIRSTLINE=""
 866        fi
 867
 868        say "$(eval_gettext "Applying: \$FIRSTLINE")"
 869
 870        case "$resolved" in
 871        '')
 872                # When we are allowed to fall back to 3-way later, don't give
 873                # false errors during the initial attempt.
 874                squelch=
 875                if test "$threeway" = t
 876                then
 877                        squelch='>/dev/null 2>&1 '
 878                fi
 879                eval "git apply $squelch$git_apply_opt"' --index "$dotest/patch"'
 880                apply_status=$?
 881                ;;
 882        t)
 883                # Resolved means the user did all the hard work, and
 884                # we do not have to do any patch application.  Just
 885                # trust what the user has in the index file and the
 886                # working tree.
 887                resolved=
 888                git diff-index --quiet --cached HEAD -- && {
 889                        gettextln "No changes - did you forget to use 'git add'?
 890If there is nothing left to stage, chances are that something else
 891already introduced the same changes; you might want to skip this patch."
 892                        stop_here_user_resolve $this
 893                }
 894                unmerged=$(git ls-files -u)
 895                if test -n "$unmerged"
 896                then
 897                        gettextln "You still have unmerged paths in your index
 898did you forget to use 'git add'?"
 899                        stop_here_user_resolve $this
 900                fi
 901                apply_status=0
 902                git rerere
 903                ;;
 904        esac
 905
 906        if test $apply_status != 0 && test "$threeway" = t
 907        then
 908                if (fall_back_3way)
 909                then
 910                    # Applying the patch to an earlier tree and merging the
 911                    # result may have produced the same tree as ours.
 912                    git diff-index --quiet --cached HEAD -- && {
 913                        say "$(gettext "No changes -- Patch already applied.")"
 914                        go_next
 915                        continue
 916                    }
 917                    # clear apply_status -- we have successfully merged.
 918                    apply_status=0
 919                fi
 920        fi
 921        if test $apply_status != 0
 922        then
 923                eval_gettextln 'Patch failed at $msgnum $FIRSTLINE'
 924                if test "$(git config --bool advice.amworkdir)" != false
 925                then
 926                        eval_gettextln 'The copy of the patch that failed is found in:
 927   $dotest/patch'
 928                fi
 929                stop_here_user_resolve $this
 930        fi
 931
 932        hook="$(git rev-parse --git-path hooks/pre-applypatch)"
 933        if test -x "$hook"
 934        then
 935                "$hook" || stop_here $this
 936        fi
 937
 938        tree=$(git write-tree) &&
 939        commit=$(
 940                if test -n "$ignore_date"
 941                then
 942                        GIT_AUTHOR_DATE=
 943                fi
 944                parent=$(git rev-parse --verify -q HEAD) ||
 945                say >&2 "$(gettext "applying to an empty history")"
 946
 947                if test -n "$committer_date_is_author_date"
 948                then
 949                        GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
 950                        export GIT_COMMITTER_DATE
 951                fi &&
 952                git commit-tree ${parent:+-p} $parent ${gpg_sign_opt:+"$gpg_sign_opt"} $tree  \
 953                        <"$dotest/final-commit"
 954        ) &&
 955        git update-ref -m "$GIT_REFLOG_ACTION: $FIRSTLINE" HEAD $commit $parent ||
 956        stop_here $this
 957
 958        if test -f "$dotest/original-commit"; then
 959                echo "$(cat "$dotest/original-commit") $commit" >> "$dotest/rewritten"
 960        fi
 961
 962        hook="$(git rev-parse --git-path hooks/post-applypatch)"
 963        test -x "$hook" && "$hook"
 964
 965        go_next
 966done
 967
 968if test -s "$dotest"/rewritten; then
 969    git notes copy --for-rewrite=rebase < "$dotest"/rewritten
 970    hook="$(git rev-parse --git-path hooks/post-rewrite)"
 971    if test -x "$hook"; then
 972        "$hook" rebase < "$dotest"/rewritten
 973    fi
 974fi
 975
 976# If am was called with --rebasing (from git-rebase--am), it's up to
 977# the caller to take care of housekeeping.
 978if ! test -f "$dotest/rebasing"
 979then
 980        rm -fr "$dotest"
 981        git gc --auto
 982fi