Code

5396be227931ebc2a302cd1aebd86e028733a69c
[git.git] / git-am.sh
1 #!/bin/sh
2 #
3 # Copyright (c) 2005, 2006 Junio C Hamano
5 SUBDIRECTORY_OK=Yes
6 OPTIONS_KEEPDASHDASH=
7 OPTIONS_SPEC="\
8 git am [options] [<mbox>|<Maildir>...]
9 git am [options] (--resolved | --skip | --abort)
10 --
11 i,interactive   run interactively
12 b,binary*       (historical option -- no-op)
13 3,3way          allow fall back on 3way merging if needed
14 q,quiet         be quiet
15 s,signoff       add a Signed-off-by line to the commit message
16 u,utf8          recode into utf8 (default)
17 k,keep          pass -k flag to git-mailinfo
18 whitespace=     pass it through git-apply
19 directory=      pass it through git-apply
20 C=              pass it through git-apply
21 p=              pass it through git-apply
22 patch-format=   format the patch(es) are in
23 reject          pass it through git-apply
24 resolvemsg=     override error message when patch failure occurs
25 r,resolved      to be used after a patch failure
26 skip            skip the current patch
27 abort           restore the original branch and abort the patching operation.
28 committer-date-is-author-date    lie about committer date
29 ignore-date     use current timestamp for author date
30 rebasing*       (internal use for git-rebase)"
32 . git-sh-setup
33 prefix=$(git rev-parse --show-prefix)
34 set_reflog_action am
35 require_work_tree
36 cd_to_toplevel
38 git var GIT_COMMITTER_IDENT >/dev/null ||
39         die "You need to set your committer info first"
41 if git rev-parse --verify -q HEAD >/dev/null
42 then
43         HAS_HEAD=yes
44 else
45         HAS_HEAD=
46 fi
48 sq () {
49         git rev-parse --sq-quote "$@"
50 }
52 stop_here () {
53     echo "$1" >"$dotest/next"
54     exit 1
55 }
57 stop_here_user_resolve () {
58     if [ -n "$resolvemsg" ]; then
59             printf '%s\n' "$resolvemsg"
60             stop_here $1
61     fi
62     cmdline="git am"
63     if test '' != "$interactive"
64     then
65         cmdline="$cmdline -i"
66     fi
67     if test '' != "$threeway"
68     then
69         cmdline="$cmdline -3"
70     fi
71     echo "When you have resolved this problem run \"$cmdline --resolved\"."
72     echo "If you would prefer to skip this patch, instead run \"$cmdline --skip\"."
73     echo "To restore the original branch and stop patching run \"$cmdline --abort\"."
75     stop_here $1
76 }
78 go_next () {
79         rm -f "$dotest/$msgnum" "$dotest/msg" "$dotest/msg-clean" \
80                 "$dotest/patch" "$dotest/info"
81         echo "$next" >"$dotest/next"
82         this=$next
83 }
85 cannot_fallback () {
86         echo "$1"
87         echo "Cannot fall back to three-way merge."
88         exit 1
89 }
91 fall_back_3way () {
92     O_OBJECT=`cd "$GIT_OBJECT_DIRECTORY" && pwd`
94     rm -fr "$dotest"/patch-merge-*
95     mkdir "$dotest/patch-merge-tmp-dir"
97     # First see if the patch records the index info that we can use.
98     git apply --build-fake-ancestor "$dotest/patch-merge-tmp-index" \
99         "$dotest/patch" &&
100     GIT_INDEX_FILE="$dotest/patch-merge-tmp-index" \
101     git write-tree >"$dotest/patch-merge-base+" ||
102     cannot_fallback "Repository lacks necessary blobs to fall back on 3-way merge."
104     say Using index info to reconstruct a base tree...
105     if GIT_INDEX_FILE="$dotest/patch-merge-tmp-index" \
106         git apply --cached <"$dotest/patch"
107     then
108         mv "$dotest/patch-merge-base+" "$dotest/patch-merge-base"
109         mv "$dotest/patch-merge-tmp-index" "$dotest/patch-merge-index"
110     else
111         cannot_fallback "Did you hand edit your patch?
112 It does not apply to blobs recorded in its index."
113     fi
115     test -f "$dotest/patch-merge-index" &&
116     his_tree=$(GIT_INDEX_FILE="$dotest/patch-merge-index" git write-tree) &&
117     orig_tree=$(cat "$dotest/patch-merge-base") &&
118     rm -fr "$dotest"/patch-merge-* || exit 1
120     say Falling back to patching base and 3-way merge...
122     # This is not so wrong.  Depending on which base we picked,
123     # orig_tree may be wildly different from ours, but his_tree
124     # has the same set of wildly different changes in parts the
125     # patch did not touch, so recursive ends up canceling them,
126     # saying that we reverted all those changes.
128     eval GITHEAD_$his_tree='"$FIRSTLINE"'
129     export GITHEAD_$his_tree
130     if test -n "$GIT_QUIET"
131     then
132             export GIT_MERGE_VERBOSITY=0
133     fi
134     git-merge-recursive $orig_tree -- HEAD $his_tree || {
135             git rerere
136             echo Failed to merge in the changes.
137             exit 1
138     }
139     unset GITHEAD_$his_tree
142 clean_abort () {
143         test $# = 0 || echo >&2 "$@"
144         rm -fr "$dotest"
145         exit 1
148 patch_format=
150 check_patch_format () {
151         # early return if patch_format was set from the command line
152         if test -n "$patch_format"
153         then
154                 return 0
155         fi
157         # we default to mbox format if input is from stdin and for
158         # directories
159         if test $# = 0 || test "x$1" = "x-" || test -d "$1"
160         then
161                 patch_format=mbox
162                 return 0
163         fi
165         # otherwise, check the first few lines of the first patch to try
166         # to detect its format
167         {
168                 read l1
169                 read l2
170                 read l3
171                 case "$l1" in
172                 "From "* | "From: "*)
173                         patch_format=mbox
174                         ;;
175                 '# This series applies on GIT commit'*)
176                         patch_format=stgit-series
177                         ;;
178                 "# HG changeset patch")
179                         patch_format=hg
180                         ;;
181                 *)
182                         # if the second line is empty and the third is
183                         # a From, Author or Date entry, this is very
184                         # likely an StGIT patch
185                         case "$l2,$l3" in
186                         ,"From: "* | ,"Author: "* | ,"Date: "*)
187                                 patch_format=stgit
188                                 ;;
189                         *)
190                                 ;;
191                         esac
192                         ;;
193                 esac
194                 if test -z "$patch_format" &&
195                         test -n "$l1" &&
196                         test -n "$l2" &&
197                         test -n "$l3"
198                 then
199                         # This begins with three non-empty lines.  Is this a
200                         # piece of e-mail a-la RFC2822?  Grab all the headers,
201                         # discarding the indented remainder of folded lines,
202                         # and see if it looks like that they all begin with the
203                         # header field names...
204                         sed -n -e '/^$/q' -e '/^[       ]/d' -e p "$1" |
205                         egrep -v '^[A-Za-z]+(-[A-Za-z]+)*:' >/dev/null ||
206                         patch_format=mbox
207                 fi
208         } < "$1" || clean_abort
211 split_patches () {
212         case "$patch_format" in
213         mbox)
214                 case "$rebasing" in
215                 '')
216                         keep_cr= ;;
217                 ?*)
218                         keep_cr=--keep-cr ;;
219                 esac
220                 git mailsplit -d"$prec" -o"$dotest" -b $keep_cr -- "$@" > "$dotest/last" ||
221                 clean_abort
222                 ;;
223         stgit-series)
224                 if test $# -ne 1
225                 then
226                         clean_abort "Only one StGIT patch series can be applied at once"
227                 fi
228                 series_dir=`dirname "$1"`
229                 series_file="$1"
230                 shift
231                 {
232                         set x
233                         while read filename
234                         do
235                                 set "$@" "$series_dir/$filename"
236                         done
237                         # remove the safety x
238                         shift
239                         # remove the arg coming from the first-line comment
240                         shift
241                 } < "$series_file" || clean_abort
242                 # set the patch format appropriately
243                 patch_format=stgit
244                 # now handle the actual StGIT patches
245                 split_patches "$@"
246                 ;;
247         stgit)
248                 this=0
249                 for stgit in "$@"
250                 do
251                         this=`expr "$this" + 1`
252                         msgnum=`printf "%0${prec}d" $this`
253                         # Perl version of StGIT parse_patch. The first nonemptyline
254                         # not starting with Author, From or Date is the
255                         # subject, and the body starts with the next nonempty
256                         # line not starting with Author, From or Date
257                         perl -ne 'BEGIN { $subject = 0 }
258                                 if ($subject > 1) { print ; }
259                                 elsif (/^\s+$/) { next ; }
260                                 elsif (/^Author:/) { print s/Author/From/ ; }
261                                 elsif (/^(From|Date)/) { print ; }
262                                 elsif ($subject) {
263                                         $subject = 2 ;
264                                         print "\n" ;
265                                         print ;
266                                 } else {
267                                         print "Subject: ", $_ ;
268                                         $subject = 1;
269                                 }
270                         ' < "$stgit" > "$dotest/$msgnum" || clean_abort
271                 done
272                 echo "$this" > "$dotest/last"
273                 this=
274                 msgnum=
275                 ;;
276         *)
277                 if test -n "$parse_patch" ; then
278                         clean_abort "Patch format $patch_format is not supported."
279                 else
280                         clean_abort "Patch format detection failed."
281                 fi
282                 ;;
283         esac
286 prec=4
287 dotest="$GIT_DIR/rebase-apply"
288 sign= utf8=t keep= skip= interactive= resolved= rebasing= abort=
289 resolvemsg= resume=
290 git_apply_opt=
291 committer_date_is_author_date=
292 ignore_date=
294 while test $# != 0
295 do
296         case "$1" in
297         -i|--interactive)
298                 interactive=t ;;
299         -b|--binary)
300                 : ;;
301         -3|--3way)
302                 threeway=t ;;
303         -s|--signoff)
304                 sign=t ;;
305         -u|--utf8)
306                 utf8=t ;; # this is now default
307         --no-utf8)
308                 utf8= ;;
309         -k|--keep)
310                 keep=t ;;
311         -r|--resolved)
312                 resolved=t ;;
313         --skip)
314                 skip=t ;;
315         --abort)
316                 abort=t ;;
317         --rebasing)
318                 rebasing=t threeway=t keep=t ;;
319         -d|--dotest)
320                 die "-d option is no longer supported.  Do not use."
321                 ;;
322         --resolvemsg)
323                 shift; resolvemsg=$1 ;;
324         --whitespace|--directory)
325                 git_apply_opt="$git_apply_opt $(sq "$1=$2")"; shift ;;
326         -C|-p)
327                 git_apply_opt="$git_apply_opt $(sq "$1$2")"; shift ;;
328         --patch-format)
329                 shift ; patch_format="$1" ;;
330         --reject)
331                 git_apply_opt="$git_apply_opt $1" ;;
332         --committer-date-is-author-date)
333                 committer_date_is_author_date=t ;;
334         --ignore-date)
335                 ignore_date=t ;;
336         -q|--quiet)
337                 GIT_QUIET=t ;;
338         --)
339                 shift; break ;;
340         *)
341                 usage ;;
342         esac
343         shift
344 done
346 # If the dotest directory exists, but we have finished applying all the
347 # patches in them, clear it out.
348 if test -d "$dotest" &&
349    last=$(cat "$dotest/last") &&
350    next=$(cat "$dotest/next") &&
351    test $# != 0 &&
352    test "$next" -gt "$last"
353 then
354    rm -fr "$dotest"
355 fi
357 if test -d "$dotest"
358 then
359         case "$#,$skip$resolved$abort" in
360         0,*t*)
361                 # Explicit resume command and we do not have file, so
362                 # we are happy.
363                 : ;;
364         0,)
365                 # No file input but without resume parameters; catch
366                 # user error to feed us a patch from standard input
367                 # when there is already $dotest.  This is somewhat
368                 # unreliable -- stdin could be /dev/null for example
369                 # and the caller did not intend to feed us a patch but
370                 # wanted to continue unattended.
371                 test -t 0
372                 ;;
373         *)
374                 false
375                 ;;
376         esac ||
377         die "previous rebase directory $dotest still exists but mbox given."
378         resume=yes
380         case "$skip,$abort" in
381         t,t)
382                 die "Please make up your mind. --skip or --abort?"
383                 ;;
384         t,)
385                 git rerere clear
386                 git read-tree --reset -u HEAD HEAD
387                 orig_head=$(cat "$GIT_DIR/ORIG_HEAD")
388                 git reset HEAD
389                 git update-ref ORIG_HEAD $orig_head
390                 ;;
391         ,t)
392                 if test -f "$dotest/rebasing"
393                 then
394                         exec git rebase --abort
395                 fi
396                 git rerere clear
397                 test -f "$dotest/dirtyindex" || {
398                         git read-tree --reset -u HEAD ORIG_HEAD
399                         git reset ORIG_HEAD
400                 }
401                 rm -fr "$dotest"
402                 exit ;;
403         esac
404         rm -f "$dotest/dirtyindex"
405 else
406         # Make sure we are not given --skip, --resolved, nor --abort
407         test "$skip$resolved$abort" = "" ||
408                 die "Resolve operation not in progress, we are not resuming."
410         # Start afresh.
411         mkdir -p "$dotest" || exit
413         if test -n "$prefix" && test $# != 0
414         then
415                 first=t
416                 for arg
417                 do
418                         test -n "$first" && {
419                                 set x
420                                 first=
421                         }
422                         case "$arg" in
423                         /*)
424                                 set "$@" "$arg" ;;
425                         *)
426                                 set "$@" "$prefix$arg" ;;
427                         esac
428                 done
429                 shift
430         fi
432         check_patch_format "$@"
434         split_patches "$@"
436         # -s, -u, -k, --whitespace, -3, -C, -q and -p flags are kept
437         # for the resuming session after a patch failure.
438         # -i can and must be given when resuming.
439         echo " $git_apply_opt" >"$dotest/apply-opt"
440         echo "$threeway" >"$dotest/threeway"
441         echo "$sign" >"$dotest/sign"
442         echo "$utf8" >"$dotest/utf8"
443         echo "$keep" >"$dotest/keep"
444         echo "$GIT_QUIET" >"$dotest/quiet"
445         echo 1 >"$dotest/next"
446         if test -n "$rebasing"
447         then
448                 : >"$dotest/rebasing"
449         else
450                 : >"$dotest/applying"
451                 if test -n "$HAS_HEAD"
452                 then
453                         git update-ref ORIG_HEAD HEAD
454                 else
455                         git update-ref -d ORIG_HEAD >/dev/null 2>&1
456                 fi
457         fi
458 fi
460 case "$resolved" in
461 '')
462         case "$HAS_HEAD" in
463         '')
464                 files=$(git ls-files) ;;
465         ?*)
466                 files=$(git diff-index --cached --name-only HEAD --) ;;
467         esac || exit
468         if test "$files"
469         then
470                 test -n "$HAS_HEAD" && : >"$dotest/dirtyindex"
471                 die "Dirty index: cannot apply patches (dirty: $files)"
472         fi
473 esac
475 if test "$(cat "$dotest/utf8")" = t
476 then
477         utf8=-u
478 else
479         utf8=-n
480 fi
481 if test "$(cat "$dotest/keep")" = t
482 then
483         keep=-k
484 fi
485 if test "$(cat "$dotest/quiet")" = t
486 then
487         GIT_QUIET=t
488 fi
489 if test "$(cat "$dotest/threeway")" = t
490 then
491         threeway=t
492 fi
493 git_apply_opt=$(cat "$dotest/apply-opt")
494 if test "$(cat "$dotest/sign")" = t
495 then
496         SIGNOFF=`git var GIT_COMMITTER_IDENT | sed -e '
497                         s/>.*/>/
498                         s/^/Signed-off-by: /'
499                 `
500 else
501         SIGNOFF=
502 fi
504 last=`cat "$dotest/last"`
505 this=`cat "$dotest/next"`
506 if test "$skip" = t
507 then
508         this=`expr "$this" + 1`
509         resume=
510 fi
512 if test "$this" -gt "$last"
513 then
514         say Nothing to do.
515         rm -fr "$dotest"
516         exit
517 fi
519 while test "$this" -le "$last"
520 do
521         msgnum=`printf "%0${prec}d" $this`
522         next=`expr "$this" + 1`
523         test -f "$dotest/$msgnum" || {
524                 resume=
525                 go_next
526                 continue
527         }
529         # If we are not resuming, parse and extract the patch information
530         # into separate files:
531         #  - info records the authorship and title
532         #  - msg is the rest of commit log message
533         #  - patch is the patch body.
534         #
535         # When we are resuming, these files are either already prepared
536         # by the user, or the user can tell us to do so by --resolved flag.
537         case "$resume" in
538         '')
539                 git mailinfo $keep $utf8 "$dotest/msg" "$dotest/patch" \
540                         <"$dotest/$msgnum" >"$dotest/info" ||
541                         stop_here $this
543                 # skip pine's internal folder data
544                 grep '^Author: Mail System Internal Data$' \
545                         <"$dotest"/info >/dev/null &&
546                         go_next && continue
548                 test -s "$dotest/patch" || {
549                         echo "Patch is empty.  Was it split wrong?"
550                         stop_here $this
551                 }
552                 if test -f "$dotest/rebasing" &&
553                         commit=$(sed -e 's/^From \([0-9a-f]*\) .*/\1/' \
554                                 -e q "$dotest/$msgnum") &&
555                         test "$(git cat-file -t "$commit")" = commit
556                 then
557                         git cat-file commit "$commit" |
558                         sed -e '1,/^$/d' >"$dotest/msg-clean"
559                 else
560                         SUBJECT="$(sed -n '/^Subject/ s/Subject: //p' "$dotest/info")"
561                         case "$keep_subject" in -k)  SUBJECT="[PATCH] $SUBJECT" ;; esac
563                         (printf '%s\n\n' "$SUBJECT"; cat "$dotest/msg") |
564                                 git stripspace > "$dotest/msg-clean"
565                 fi
566                 ;;
567         esac
569         GIT_AUTHOR_NAME="$(sed -n '/^Author/ s/Author: //p' "$dotest/info")"
570         GIT_AUTHOR_EMAIL="$(sed -n '/^Email/ s/Email: //p' "$dotest/info")"
571         GIT_AUTHOR_DATE="$(sed -n '/^Date/ s/Date: //p' "$dotest/info")"
573         if test -z "$GIT_AUTHOR_EMAIL"
574         then
575                 echo "Patch does not have a valid e-mail address."
576                 stop_here $this
577         fi
579         export GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_AUTHOR_DATE
581         case "$resume" in
582         '')
583             if test '' != "$SIGNOFF"
584             then
585                 LAST_SIGNED_OFF_BY=`
586                     sed -ne '/^Signed-off-by: /p' \
587                     "$dotest/msg-clean" |
588                     sed -ne '$p'
589                 `
590                 ADD_SIGNOFF=`
591                     test "$LAST_SIGNED_OFF_BY" = "$SIGNOFF" || {
592                     test '' = "$LAST_SIGNED_OFF_BY" && echo
593                     echo "$SIGNOFF"
594                 }`
595             else
596                 ADD_SIGNOFF=
597             fi
598             {
599                 if test -s "$dotest/msg-clean"
600                 then
601                         cat "$dotest/msg-clean"
602                 fi
603                 if test '' != "$ADD_SIGNOFF"
604                 then
605                         echo "$ADD_SIGNOFF"
606                 fi
607             } >"$dotest/final-commit"
608             ;;
609         *)
610                 case "$resolved$interactive" in
611                 tt)
612                         # This is used only for interactive view option.
613                         git diff-index -p --cached HEAD -- >"$dotest/patch"
614                         ;;
615                 esac
616         esac
618         resume=
619         if test "$interactive" = t
620         then
621             test -t 0 ||
622             die "cannot be interactive without stdin connected to a terminal."
623             action=again
624             while test "$action" = again
625             do
626                 echo "Commit Body is:"
627                 echo "--------------------------"
628                 cat "$dotest/final-commit"
629                 echo "--------------------------"
630                 printf "Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all "
631                 read reply
632                 case "$reply" in
633                 [yY]*) action=yes ;;
634                 [aA]*) action=yes interactive= ;;
635                 [nN]*) action=skip ;;
636                 [eE]*) git_editor "$dotest/final-commit"
637                        action=again ;;
638                 [vV]*) action=again
639                        LESS=-S ${PAGER:-less} "$dotest/patch" ;;
640                 *)     action=again ;;
641                 esac
642             done
643         else
644             action=yes
645         fi
646         FIRSTLINE=$(sed 1q "$dotest/final-commit")
648         if test $action = skip
649         then
650                 go_next
651                 continue
652         fi
654         if test -x "$GIT_DIR"/hooks/applypatch-msg
655         then
656                 "$GIT_DIR"/hooks/applypatch-msg "$dotest/final-commit" ||
657                 stop_here $this
658         fi
660         say "Applying: $FIRSTLINE"
662         case "$resolved" in
663         '')
664                 # When we are allowed to fall back to 3-way later, don't give
665                 # false errors during the initial attempt.
666                 squelch=
667                 if test "$threeway" = t
668                 then
669                         squelch='>/dev/null 2>&1 '
670                 fi
671                 eval "git apply $squelch$git_apply_opt"' --index "$dotest/patch"'
672                 apply_status=$?
673                 ;;
674         t)
675                 # Resolved means the user did all the hard work, and
676                 # we do not have to do any patch application.  Just
677                 # trust what the user has in the index file and the
678                 # working tree.
679                 resolved=
680                 git diff-index --quiet --cached HEAD -- && {
681                         echo "No changes - did you forget to use 'git add'?"
682                         stop_here_user_resolve $this
683                 }
684                 unmerged=$(git ls-files -u)
685                 if test -n "$unmerged"
686                 then
687                         echo "You still have unmerged paths in your index"
688                         echo "did you forget to use 'git add'?"
689                         stop_here_user_resolve $this
690                 fi
691                 apply_status=0
692                 git rerere
693                 ;;
694         esac
696         if test $apply_status = 1 && test "$threeway" = t
697         then
698                 if (fall_back_3way)
699                 then
700                     # Applying the patch to an earlier tree and merging the
701                     # result may have produced the same tree as ours.
702                     git diff-index --quiet --cached HEAD -- && {
703                         say No changes -- Patch already applied.
704                         go_next
705                         continue
706                     }
707                     # clear apply_status -- we have successfully merged.
708                     apply_status=0
709                 fi
710         fi
711         if test $apply_status != 0
712         then
713                 printf 'Patch failed at %s %s\n' "$msgnum" "$FIRSTLINE"
714                 stop_here_user_resolve $this
715         fi
717         if test -x "$GIT_DIR"/hooks/pre-applypatch
718         then
719                 "$GIT_DIR"/hooks/pre-applypatch || stop_here $this
720         fi
722         tree=$(git write-tree) &&
723         commit=$(
724                 if test -n "$ignore_date"
725                 then
726                         GIT_AUTHOR_DATE=
727                 fi
728                 parent=$(git rev-parse --verify -q HEAD) ||
729                 say >&2 "applying to an empty history"
731                 if test -n "$committer_date_is_author_date"
732                 then
733                         GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"
734                         export GIT_COMMITTER_DATE
735                 fi &&
736                 git commit-tree $tree ${parent:+-p} $parent <"$dotest/final-commit"
737         ) &&
738         git update-ref -m "$GIT_REFLOG_ACTION: $FIRSTLINE" HEAD $commit $parent ||
739         stop_here $this
741         if test -x "$GIT_DIR"/hooks/post-applypatch
742         then
743                 "$GIT_DIR"/hooks/post-applypatch
744         fi
746         go_next
747 done
749 git gc --auto
751 rm -fr "$dotest"