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