Teach "am" and "rebase" to mark the original position with ORIG_HEAD
[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
10 git-am [options] --skip
11 --
12 d,dotest=       (removed -- do not use)
13 i,interactive   run interactively
14 b,binary        pass --allow-binary-replacement to git-apply
15 3,3way          allow fall back on 3way merging if needed
16 s,signoff       add a Signed-off-by line to the commit message
17 u,utf8          recode into utf8 (default)
18 k,keep          pass -k flag to git-mailinfo
19 whitespace=     pass it through git-apply
20 C=              pass it through git-apply
21 p=              pass it through git-apply
22 resolvemsg=     override error message when patch failure occurs
23 r,resolved      to be used after a patch failure
24 skip            skip the current patch
25 rebasing        (internal use for git-rebase)"
26
27 . git-sh-setup
28 prefix=$(git rev-parse --show-prefix)
29 set_reflog_action am
30 require_work_tree
31 cd_to_toplevel
32
33 git var GIT_COMMITTER_IDENT >/dev/null || exit
34
35 stop_here () {
36     echo "$1" >"$dotest/next"
37     exit 1
38 }
39
40 stop_here_user_resolve () {
41     if [ -n "$resolvemsg" ]; then
42             printf '%s\n' "$resolvemsg"
43             stop_here $1
44     fi
45     cmdline=$(basename $0)
46     if test '' != "$interactive"
47     then
48         cmdline="$cmdline -i"
49     fi
50     if test '' != "$threeway"
51     then
52         cmdline="$cmdline -3"
53     fi
54     echo "When you have resolved this problem run \"$cmdline --resolved\"."
55     echo "If you would prefer to skip this patch, instead run \"$cmdline --skip\"."
56
57     stop_here $1
58 }
59
60 go_next () {
61         rm -f "$dotest/$msgnum" "$dotest/msg" "$dotest/msg-clean" \
62                 "$dotest/patch" "$dotest/info"
63         echo "$next" >"$dotest/next"
64         this=$next
65 }
66
67 cannot_fallback () {
68         echo "$1"
69         echo "Cannot fall back to three-way merge."
70         exit 1
71 }
72
73 fall_back_3way () {
74     O_OBJECT=`cd "$GIT_OBJECT_DIRECTORY" && pwd`
75
76     rm -fr "$dotest"/patch-merge-*
77     mkdir "$dotest/patch-merge-tmp-dir"
78
79     # First see if the patch records the index info that we can use.
80     git apply --build-fake-ancestor "$dotest/patch-merge-tmp-index" \
81         "$dotest/patch" &&
82     GIT_INDEX_FILE="$dotest/patch-merge-tmp-index" \
83     git write-tree >"$dotest/patch-merge-base+" ||
84     cannot_fallback "Repository lacks necessary blobs to fall back on 3-way merge."
85
86     echo Using index info to reconstruct a base tree...
87     if GIT_INDEX_FILE="$dotest/patch-merge-tmp-index" \
88         git apply $binary --cached <"$dotest/patch"
89     then
90         mv "$dotest/patch-merge-base+" "$dotest/patch-merge-base"
91         mv "$dotest/patch-merge-tmp-index" "$dotest/patch-merge-index"
92     else
93         cannot_fallback "Did you hand edit your patch?
94 It does not apply to blobs recorded in its index."
95     fi
96
97     test -f "$dotest/patch-merge-index" &&
98     his_tree=$(GIT_INDEX_FILE="$dotest/patch-merge-index" git write-tree) &&
99     orig_tree=$(cat "$dotest/patch-merge-base") &&
100     rm -fr "$dotest"/patch-merge-* || exit 1
101
102     echo Falling back to patching base and 3-way merge...
103
104     # This is not so wrong.  Depending on which base we picked,
105     # orig_tree may be wildly different from ours, but his_tree
106     # has the same set of wildly different changes in parts the
107     # patch did not touch, so recursive ends up canceling them,
108     # saying that we reverted all those changes.
109
110     eval GITHEAD_$his_tree='"$FIRSTLINE"'
111     export GITHEAD_$his_tree
112     git-merge-recursive $orig_tree -- HEAD $his_tree || {
113             git rerere
114             echo Failed to merge in the changes.
115             exit 1
116     }
117     unset GITHEAD_$his_tree
118 }
119
120 prec=4
121 dotest=".dotest"
122 sign= utf8=t keep= skip= interactive= resolved= binary= rebasing=
123 resolvemsg= resume=
124 git_apply_opt=
125
126 while test $# != 0
127 do
128         case "$1" in
129         -i|--interactive)
130                 interactive=t ;;
131         -b|--binary)
132                 binary=t ;;
133         -3|--3way)
134                 threeway=t ;;
135         -s|--signoff)
136                 sign=t ;;
137         -u|--utf8)
138                 utf8=t ;; # this is now default
139         --no-utf8)
140                 utf8= ;;
141         -k|--keep)
142                 keep=t ;;
143         -r|--resolved)
144                 resolved=t ;;
145         --skip)
146                 skip=t ;;
147         --rebasing)
148                 rebasing=t threeway=t keep=t binary=t ;;
149         -d|--dotest)
150                 die "-d option is no longer supported.  Do not use."
151                 ;;
152         --resolvemsg)
153                 shift; resolvemsg=$1 ;;
154         --whitespace)
155                 git_apply_opt="$git_apply_opt $1=$2"; shift ;;
156         -C|-p)
157                 git_apply_opt="$git_apply_opt $1$2"; shift ;;
158         --)
159                 shift; break ;;
160         *)
161                 usage ;;
162         esac
163         shift
164 done
165
166 # If the dotest directory exists, but we have finished applying all the
167 # patches in them, clear it out.
168 if test -d "$dotest" &&
169    last=$(cat "$dotest/last") &&
170    next=$(cat "$dotest/next") &&
171    test $# != 0 &&
172    test "$next" -gt "$last"
173 then
174    rm -fr "$dotest"
175 fi
176
177 if test -d "$dotest"
178 then
179         case "$#,$skip$resolved" in
180         0,*t*)
181                 # Explicit resume command and we do not have file, so
182                 # we are happy.
183                 : ;;
184         0,)
185                 # No file input but without resume parameters; catch
186                 # user error to feed us a patch from standard input
187                 # when there is already $dotest.  This is somewhat
188                 # unreliable -- stdin could be /dev/null for example
189                 # and the caller did not intend to feed us a patch but
190                 # wanted to continue unattended.
191                 tty -s
192                 ;;
193         *)
194                 false
195                 ;;
196         esac ||
197         die "previous dotest directory $dotest still exists but mbox given."
198         resume=yes
199 else
200         # Make sure we are not given --skip nor --resolved
201         test ",$skip,$resolved," = ,,, ||
202                 die "Resolve operation not in progress, we are not resuming."
203
204         # Start afresh.
205         mkdir -p "$dotest" || exit
206
207         if test -n "$prefix" && test $# != 0
208         then
209                 first=t
210                 for arg
211                 do
212                         test -n "$first" && {
213                                 set x
214                                 first=
215                         }
216                         case "$arg" in
217                         /*)
218                                 set "$@" "$arg" ;;
219                         *)
220                                 set "$@" "$prefix$arg" ;;
221                         esac
222                 done
223                 shift
224         fi
225         git mailsplit -d"$prec" -o"$dotest" -b -- "$@" > "$dotest/last" ||  {
226                 rm -fr "$dotest"
227                 exit 1
228         }
229
230         # -b, -s, -u, -k and --whitespace flags are kept for the
231         # resuming session after a patch failure.
232         # -3 and -i can and must be given when resuming.
233         echo "$binary" >"$dotest/binary"
234         echo " $ws" >"$dotest/whitespace"
235         echo "$sign" >"$dotest/sign"
236         echo "$utf8" >"$dotest/utf8"
237         echo "$keep" >"$dotest/keep"
238         echo 1 >"$dotest/next"
239         if test -n "$rebasing"
240         then
241                 : >"$dotest/rebasing"
242         else
243                 : >"$dotest/applying"
244                 git update-ref ORIG_HEAD HEAD
245         fi
246 fi
247
248 case "$resolved" in
249 '')
250         files=$(git diff-index --cached --name-only HEAD --) || exit
251         if [ "$files" ]; then
252            echo "Dirty index: cannot apply patches (dirty: $files)" >&2
253            exit 1
254         fi
255 esac
256
257 if test "$(cat "$dotest/binary")" = t
258 then
259         binary=--allow-binary-replacement
260 fi
261 if test "$(cat "$dotest/utf8")" = t
262 then
263         utf8=-u
264 else
265         utf8=-n
266 fi
267 if test "$(cat "$dotest/keep")" = t
268 then
269         keep=-k
270 fi
271 ws=`cat "$dotest/whitespace"`
272 if test "$(cat "$dotest/sign")" = t
273 then
274         SIGNOFF=`git-var GIT_COMMITTER_IDENT | sed -e '
275                         s/>.*/>/
276                         s/^/Signed-off-by: /'
277                 `
278 else
279         SIGNOFF=
280 fi
281
282 last=`cat "$dotest/last"`
283 this=`cat "$dotest/next"`
284 if test "$skip" = t
285 then
286         git rerere clear
287         this=`expr "$this" + 1`
288         resume=
289 fi
290
291 if test "$this" -gt "$last"
292 then
293         echo Nothing to do.
294         rm -fr "$dotest"
295         exit
296 fi
297
298 while test "$this" -le "$last"
299 do
300         msgnum=`printf "%0${prec}d" $this`
301         next=`expr "$this" + 1`
302         test -f "$dotest/$msgnum" || {
303                 resume=
304                 go_next
305                 continue
306         }
307
308         # If we are not resuming, parse and extract the patch information
309         # into separate files:
310         #  - info records the authorship and title
311         #  - msg is the rest of commit log message
312         #  - patch is the patch body.
313         #
314         # When we are resuming, these files are either already prepared
315         # by the user, or the user can tell us to do so by --resolved flag.
316         case "$resume" in
317         '')
318                 git mailinfo $keep $utf8 "$dotest/msg" "$dotest/patch" \
319                         <"$dotest/$msgnum" >"$dotest/info" ||
320                         stop_here $this
321
322                 # skip pine's internal folder data
323                 grep '^Author: Mail System Internal Data$' \
324                         <"$dotest"/info >/dev/null &&
325                         go_next && continue
326
327                 test -s $dotest/patch || {
328                         echo "Patch is empty.  Was it split wrong?"
329                         stop_here $this
330                 }
331                 if test -f "$dotest/rebasing" &&
332                         commit=$(sed -e 's/^From \([0-9a-f]*\) .*/\1/' \
333                                 -e q "$dotest/$msgnum") &&
334                         test "$(git cat-file -t "$commit")" = commit
335                 then
336                         git cat-file commit "$commit" |
337                         sed -e '1,/^$/d' >"$dotest/msg-clean"
338                 else
339                         SUBJECT="$(sed -n '/^Subject/ s/Subject: //p' "$dotest/info")"
340                         case "$keep_subject" in -k)  SUBJECT="[PATCH] $SUBJECT" ;; esac
341
342                         (printf '%s\n\n' "$SUBJECT"; cat "$dotest/msg") |
343                                 git stripspace > "$dotest/msg-clean"
344                 fi
345                 ;;
346         esac
347
348         GIT_AUTHOR_NAME="$(sed -n '/^Author/ s/Author: //p' "$dotest/info")"
349         GIT_AUTHOR_EMAIL="$(sed -n '/^Email/ s/Email: //p' "$dotest/info")"
350         GIT_AUTHOR_DATE="$(sed -n '/^Date/ s/Date: //p' "$dotest/info")"
351
352         if test -z "$GIT_AUTHOR_EMAIL"
353         then
354                 echo "Patch does not have a valid e-mail address."
355                 stop_here $this
356         fi
357
358         export GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_AUTHOR_DATE
359
360         case "$resume" in
361         '')
362             if test '' != "$SIGNOFF"
363             then
364                 LAST_SIGNED_OFF_BY=`
365                     sed -ne '/^Signed-off-by: /p' \
366                     "$dotest/msg-clean" |
367                     sed -ne '$p'
368                 `
369                 ADD_SIGNOFF=`
370                     test "$LAST_SIGNED_OFF_BY" = "$SIGNOFF" || {
371                     test '' = "$LAST_SIGNED_OFF_BY" && echo
372                     echo "$SIGNOFF"
373                 }`
374             else
375                 ADD_SIGNOFF=
376             fi
377             {
378                 if test -s "$dotest/msg-clean"
379                 then
380                         cat "$dotest/msg-clean"
381                 fi
382                 if test '' != "$ADD_SIGNOFF"
383                 then
384                         echo "$ADD_SIGNOFF"
385                 fi
386             } >"$dotest/final-commit"
387             ;;
388         *)
389                 case "$resolved$interactive" in
390                 tt)
391                         # This is used only for interactive view option.
392                         git diff-index -p --cached HEAD -- >"$dotest/patch"
393                         ;;
394                 esac
395         esac
396
397         resume=
398         if test "$interactive" = t
399         then
400             test -t 0 ||
401             die "cannot be interactive without stdin connected to a terminal."
402             action=again
403             while test "$action" = again
404             do
405                 echo "Commit Body is:"
406                 echo "--------------------------"
407                 cat "$dotest/final-commit"
408                 echo "--------------------------"
409                 printf "Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all "
410                 read reply
411                 case "$reply" in
412                 [yY]*) action=yes ;;
413                 [aA]*) action=yes interactive= ;;
414                 [nN]*) action=skip ;;
415                 [eE]*) git_editor "$dotest/final-commit"
416                        action=again ;;
417                 [vV]*) action=again
418                        LESS=-S ${PAGER:-less} "$dotest/patch" ;;
419                 *)     action=again ;;
420                 esac
421             done
422         else
423             action=yes
424         fi
425         FIRSTLINE=$(sed 1q "$dotest/final-commit")
426
427         if test $action = skip
428         then
429                 go_next
430                 continue
431         fi
432
433         if test -x "$GIT_DIR"/hooks/applypatch-msg
434         then
435                 "$GIT_DIR"/hooks/applypatch-msg "$dotest/final-commit" ||
436                 stop_here $this
437         fi
438
439         printf 'Applying %s\n' "$FIRSTLINE"
440
441         case "$resolved" in
442         '')
443                 git apply $git_apply_opt $binary --index "$dotest/patch"
444                 apply_status=$?
445                 ;;
446         t)
447                 # Resolved means the user did all the hard work, and
448                 # we do not have to do any patch application.  Just
449                 # trust what the user has in the index file and the
450                 # working tree.
451                 resolved=
452                 git diff-index --quiet --cached HEAD -- && {
453                         echo "No changes - did you forget to use 'git add'?"
454                         stop_here_user_resolve $this
455                 }
456                 unmerged=$(git ls-files -u)
457                 if test -n "$unmerged"
458                 then
459                         echo "You still have unmerged paths in your index"
460                         echo "did you forget to use 'git add'?"
461                         stop_here_user_resolve $this
462                 fi
463                 apply_status=0
464                 git rerere
465                 ;;
466         esac
467
468         if test $apply_status = 1 && test "$threeway" = t
469         then
470                 if (fall_back_3way)
471                 then
472                     # Applying the patch to an earlier tree and merging the
473                     # result may have produced the same tree as ours.
474                     git diff-index --quiet --cached HEAD -- && {
475                         echo No changes -- Patch already applied.
476                         go_next
477                         continue
478                     }
479                     # clear apply_status -- we have successfully merged.
480                     apply_status=0
481                 fi
482         fi
483         if test $apply_status != 0
484         then
485                 echo Patch failed at $msgnum.
486                 stop_here_user_resolve $this
487         fi
488
489         if test -x "$GIT_DIR"/hooks/pre-applypatch
490         then
491                 "$GIT_DIR"/hooks/pre-applypatch || stop_here $this
492         fi
493
494         tree=$(git write-tree) &&
495         parent=$(git rev-parse --verify HEAD) &&
496         commit=$(git commit-tree $tree -p $parent <"$dotest/final-commit") &&
497         git update-ref -m "$GIT_REFLOG_ACTION: $FIRSTLINE" HEAD $commit $parent ||
498         stop_here $this
499
500         if test -x "$GIT_DIR"/hooks/post-applypatch
501         then
502                 "$GIT_DIR"/hooks/post-applypatch
503         fi
504
505         go_next
506 done
507
508 git gc --auto
509
510 rm -fr "$dotest"