git-merge: refactor option parsing
[git] / git-merge.sh
1 #!/bin/sh
2 #
3 # Copyright (c) 2005 Junio C Hamano
4 #
5
6 USAGE='[-n] [--summary] [--no-commit] [--squash] [-s <strategy>] [-m=<merge-message>] <commit>+'
7
8 SUBDIRECTORY_OK=Yes
9 . git-sh-setup
10 require_work_tree
11 cd_to_toplevel
12
13 test -z "$(git ls-files -u)" ||
14         die "You are in the middle of a conflicted merge."
15
16 LF='
17 '
18
19 all_strategies='recur recursive octopus resolve stupid ours subtree'
20 default_twohead_strategies='recursive'
21 default_octopus_strategies='octopus'
22 no_fast_forward_strategies='subtree ours'
23 no_trivial_strategies='recursive recur subtree ours'
24 use_strategies=
25
26 allow_fast_forward=t
27 allow_trivial_merge=t
28
29 dropsave() {
30         rm -f -- "$GIT_DIR/MERGE_HEAD" "$GIT_DIR/MERGE_MSG" \
31                  "$GIT_DIR/MERGE_SAVE" || exit 1
32 }
33
34 savestate() {
35         # Stash away any local modifications.
36         git diff-index -z --name-only $head |
37         cpio -0 -o >"$GIT_DIR/MERGE_SAVE"
38 }
39
40 restorestate() {
41         if test -f "$GIT_DIR/MERGE_SAVE"
42         then
43                 git reset --hard $head >/dev/null
44                 cpio -iuv <"$GIT_DIR/MERGE_SAVE"
45                 git update-index --refresh >/dev/null
46         fi
47 }
48
49 finish_up_to_date () {
50         case "$squash" in
51         t)
52                 echo "$1 (nothing to squash)" ;;
53         '')
54                 echo "$1" ;;
55         esac
56         dropsave
57 }
58
59 squash_message () {
60         echo Squashed commit of the following:
61         echo
62         git log --no-merges ^"$head" $remoteheads
63 }
64
65 finish () {
66         if test '' = "$2"
67         then
68                 rlogm="$GIT_REFLOG_ACTION"
69         else
70                 echo "$2"
71                 rlogm="$GIT_REFLOG_ACTION: $2"
72         fi
73         case "$squash" in
74         t)
75                 echo "Squash commit -- not updating HEAD"
76                 squash_message >"$GIT_DIR/SQUASH_MSG"
77                 ;;
78         '')
79                 case "$merge_msg" in
80                 '')
81                         echo "No merge message -- not updating HEAD"
82                         ;;
83                 *)
84                         git update-ref -m "$rlogm" HEAD "$1" "$head" || exit 1
85                         ;;
86                 esac
87                 ;;
88         esac
89         case "$1" in
90         '')
91                 ;;
92         ?*)
93                 if test "$show_diffstat" = t
94                 then
95                         # We want color (if set), but no pager
96                         GIT_PAGER='' git diff --stat --summary -M "$head" "$1"
97                 fi
98                 ;;
99         esac
100 }
101
102 merge_name () {
103         remote="$1"
104         rh=$(git rev-parse --verify "$remote^0" 2>/dev/null) || return
105         bh=$(git show-ref -s --verify "refs/heads/$remote" 2>/dev/null)
106         if test "$rh" = "$bh"
107         then
108                 echo "$rh               branch '$remote' of ."
109         elif truname=$(expr "$remote" : '\(.*\)~[1-9][0-9]*$') &&
110                 git show-ref -q --verify "refs/heads/$truname" 2>/dev/null
111         then
112                 echo "$rh               branch '$truname' (early part) of ."
113         elif test "$remote" = "FETCH_HEAD" -a -r "$GIT_DIR/FETCH_HEAD"
114         then
115                 sed -e 's/      not-for-merge   /               /' -e 1q \
116                         "$GIT_DIR/FETCH_HEAD"
117         else
118                 echo "$rh               commit '$remote'"
119         fi
120 }
121
122 parse_option () {
123         case "$1" in
124         -n|--n|--no|--no-|--no-s|--no-su|--no-sum|--no-summ|\
125                 --no-summa|--no-summar|--no-summary)
126                 show_diffstat=false ;;
127         --summary)
128                 show_diffstat=t ;;
129         --sq|--squ|--squa|--squas|--squash)
130                 squash=t no_commit=t ;;
131         --no-c|--no-co|--no-com|--no-comm|--no-commi|--no-commit)
132                 no_commit=t ;;
133         -s=*|--s=*|--st=*|--str=*|--stra=*|--strat=*|--strate=*|\
134                 --strateg=*|--strategy=*|\
135         -s|--s|--st|--str|--stra|--strat|--strate|--strateg|--strategy)
136                 case "$#,$1" in
137                 *,*=*)
138                         strategy=`expr "z$1" : 'z-[^=]*=\(.*\)'` ;;
139                 1,*)
140                         usage ;;
141                 *)
142                         strategy="$2"
143                         shift ;;
144                 esac
145                 case " $all_strategies " in
146                 *" $strategy "*)
147                         use_strategies="$use_strategies$strategy " ;;
148                 *)
149                         die "available strategies are: $all_strategies" ;;
150                 esac
151                 ;;
152         -m=*|--m=*|--me=*|--mes=*|--mess=*|--messa=*|--messag=*|--message=*)
153                 merge_msg=`expr "z$1" : 'z-[^=]*=\(.*\)'`
154                 have_message=t
155                 ;;
156         -m|--m|--me|--mes|--mess|--messa|--messag|--message)
157                 shift
158                 case "$#" in
159                 1)      usage ;;
160                 esac
161                 merge_msg="$1"
162                 have_message=t
163                 ;;
164         -*)     usage ;;
165         *)      return 1 ;;
166         esac
167         shift
168         args_left=$#
169 }
170
171 test $# != 0 || usage
172
173 have_message=
174 while parse_option "$@"
175 do
176         while test $args_left -lt $#
177         do
178                 shift
179         done
180 done
181
182 if test -z "$show_diffstat"; then
183     test "$(git config --bool merge.diffstat)" = false && show_diffstat=false
184     test -z "$show_diffstat" && show_diffstat=t
185 fi
186
187 # This could be traditional "merge <msg> HEAD <commit>..."  and the
188 # way we can tell it is to see if the second token is HEAD, but some
189 # people might have misused the interface and used a committish that
190 # is the same as HEAD there instead.  Traditional format never would
191 # have "-m" so it is an additional safety measure to check for it.
192
193 if test -z "$have_message" &&
194         second_token=$(git rev-parse --verify "$2^0" 2>/dev/null) &&
195         head_commit=$(git rev-parse --verify "HEAD" 2>/dev/null) &&
196         test "$second_token" = "$head_commit"
197 then
198         merge_msg="$1"
199         shift
200         head_arg="$1"
201         shift
202 elif ! git rev-parse --verify HEAD >/dev/null 2>&1
203 then
204         # If the merged head is a valid one there is no reason to
205         # forbid "git merge" into a branch yet to be born.  We do
206         # the same for "git pull".
207         if test 1 -ne $#
208         then
209                 echo >&2 "Can merge only exactly one commit into empty head"
210                 exit 1
211         fi
212
213         rh=$(git rev-parse --verify "$1^0") ||
214                 die "$1 - not something we can merge"
215
216         git update-ref -m "initial pull" HEAD "$rh" "" &&
217         git read-tree --reset -u HEAD
218         exit
219
220 else
221         # We are invoked directly as the first-class UI.
222         head_arg=HEAD
223
224         # All the rest are the commits being merged; prepare
225         # the standard merge summary message to be appended to
226         # the given message.  If remote is invalid we will die
227         # later in the common codepath so we discard the error
228         # in this loop.
229         merge_name=$(for remote
230                 do
231                         merge_name "$remote"
232                 done | git fmt-merge-msg
233         )
234         merge_msg="${merge_msg:+$merge_msg$LF$LF}$merge_name"
235 fi
236 head=$(git rev-parse --verify "$head_arg"^0) || usage
237
238 # All the rest are remote heads
239 test "$#" = 0 && usage ;# we need at least one remote head.
240 set_reflog_action "merge $*"
241
242 remoteheads=
243 for remote
244 do
245         remotehead=$(git rev-parse --verify "$remote"^0 2>/dev/null) ||
246             die "$remote - not something we can merge"
247         remoteheads="${remoteheads}$remotehead "
248         eval GITHEAD_$remotehead='"$remote"'
249         export GITHEAD_$remotehead
250 done
251 set x $remoteheads ; shift
252
253 case "$use_strategies" in
254 '')
255         case "$#" in
256         1)
257                 var="`git config --get pull.twohead`"
258                 if test -n "$var"
259                 then
260                         use_strategies="$var"
261                 else
262                         use_strategies="$default_twohead_strategies"
263                 fi ;;
264         *)
265                 var="`git config --get pull.octopus`"
266                 if test -n "$var"
267                 then
268                         use_strategies="$var"
269                 else
270                         use_strategies="$default_octopus_strategies"
271                 fi ;;
272         esac
273         ;;
274 esac
275
276 for s in $use_strategies
277 do
278         for ss in $no_fast_forward_strategies
279         do
280                 case " $s " in
281                 *" $ss "*)
282                         allow_fast_forward=f
283                         break
284                         ;;
285                 esac
286         done
287         for ss in $no_trivial_strategies
288         do
289                 case " $s " in
290                 *" $ss "*)
291                         allow_trivial_merge=f
292                         break
293                         ;;
294                 esac
295         done
296 done
297
298 case "$#" in
299 1)
300         common=$(git merge-base --all $head "$@")
301         ;;
302 *)
303         common=$(git show-branch --merge-base $head "$@")
304         ;;
305 esac
306 echo "$head" >"$GIT_DIR/ORIG_HEAD"
307
308 case "$allow_fast_forward,$#,$common,$no_commit" in
309 ?,*,'',*)
310         # No common ancestors found. We need a real merge.
311         ;;
312 ?,1,"$1",*)
313         # If head can reach all the merge then we are up to date.
314         # but first the most common case of merging one remote.
315         finish_up_to_date "Already up-to-date."
316         exit 0
317         ;;
318 t,1,"$head",*)
319         # Again the most common case of merging one remote.
320         echo "Updating $(git rev-parse --short $head)..$(git rev-parse --short $1)"
321         git update-index --refresh 2>/dev/null
322         msg="Fast forward"
323         if test -n "$have_message"
324         then
325                 msg="$msg (no commit created; -m option ignored)"
326         fi
327         new_head=$(git rev-parse --verify "$1^0") &&
328         git read-tree -v -m -u --exclude-per-directory=.gitignore $head "$new_head" &&
329         finish "$new_head" "$msg" || exit
330         dropsave
331         exit 0
332         ;;
333 ?,1,?*"$LF"?*,*)
334         # We are not doing octopus and not fast forward.  Need a
335         # real merge.
336         ;;
337 ?,1,*,)
338         # We are not doing octopus, not fast forward, and have only
339         # one common.
340         git update-index --refresh 2>/dev/null
341         case "$allow_trivial_merge" in
342         t)
343                 # See if it is really trivial.
344                 git var GIT_COMMITTER_IDENT >/dev/null || exit
345                 echo "Trying really trivial in-index merge..."
346                 if git read-tree --trivial -m -u -v $common $head "$1" &&
347                    result_tree=$(git write-tree)
348                 then
349                         echo "Wonderful."
350                         result_commit=$(
351                                 printf '%s\n' "$merge_msg" |
352                                 git commit-tree $result_tree -p HEAD -p "$1"
353                         ) || exit
354                         finish "$result_commit" "In-index merge"
355                         dropsave
356                         exit 0
357                 fi
358                 echo "Nope."
359         esac
360         ;;
361 *)
362         # An octopus.  If we can reach all the remote we are up to date.
363         up_to_date=t
364         for remote
365         do
366                 common_one=$(git merge-base --all $head $remote)
367                 if test "$common_one" != "$remote"
368                 then
369                         up_to_date=f
370                         break
371                 fi
372         done
373         if test "$up_to_date" = t
374         then
375                 finish_up_to_date "Already up-to-date. Yeeah!"
376                 exit 0
377         fi
378         ;;
379 esac
380
381 # We are going to make a new commit.
382 git var GIT_COMMITTER_IDENT >/dev/null || exit
383
384 # At this point, we need a real merge.  No matter what strategy
385 # we use, it would operate on the index, possibly affecting the
386 # working tree, and when resolved cleanly, have the desired tree
387 # in the index -- this means that the index must be in sync with
388 # the $head commit.  The strategies are responsible to ensure this.
389
390 case "$use_strategies" in
391 ?*' '?*)
392     # Stash away the local changes so that we can try more than one.
393     savestate
394     single_strategy=no
395     ;;
396 *)
397     rm -f "$GIT_DIR/MERGE_SAVE"
398     single_strategy=yes
399     ;;
400 esac
401
402 result_tree= best_cnt=-1 best_strategy= wt_strategy=
403 merge_was_ok=
404 for strategy in $use_strategies
405 do
406     test "$wt_strategy" = '' || {
407         echo "Rewinding the tree to pristine..."
408         restorestate
409     }
410     case "$single_strategy" in
411     no)
412         echo "Trying merge strategy $strategy..."
413         ;;
414     esac
415
416     # Remember which strategy left the state in the working tree
417     wt_strategy=$strategy
418
419     git-merge-$strategy $common -- "$head_arg" "$@"
420     exit=$?
421     if test "$no_commit" = t && test "$exit" = 0
422     then
423         merge_was_ok=t
424         exit=1 ;# pretend it left conflicts.
425     fi
426
427     test "$exit" = 0 || {
428
429         # The backend exits with 1 when conflicts are left to be resolved,
430         # with 2 when it does not handle the given merge at all.
431
432         if test "$exit" -eq 1
433         then
434             cnt=`{
435                 git diff-files --name-only
436                 git ls-files --unmerged
437             } | wc -l`
438             if test $best_cnt -le 0 -o $cnt -le $best_cnt
439             then
440                 best_strategy=$strategy
441                 best_cnt=$cnt
442             fi
443         fi
444         continue
445     }
446
447     # Automerge succeeded.
448     result_tree=$(git write-tree) && break
449 done
450
451 # If we have a resulting tree, that means the strategy module
452 # auto resolved the merge cleanly.
453 if test '' != "$result_tree"
454 then
455     parents=$(git show-branch --independent "$head" "$@" | sed -e 's/^/-p /')
456     result_commit=$(printf '%s\n' "$merge_msg" | git commit-tree $result_tree $parents) || exit
457     finish "$result_commit" "Merge made by $wt_strategy."
458     dropsave
459     exit 0
460 fi
461
462 # Pick the result from the best strategy and have the user fix it up.
463 case "$best_strategy" in
464 '')
465         restorestate
466         case "$use_strategies" in
467         ?*' '?*)
468                 echo >&2 "No merge strategy handled the merge."
469                 ;;
470         *)
471                 echo >&2 "Merge with strategy $use_strategies failed."
472                 ;;
473         esac
474         exit 2
475         ;;
476 "$wt_strategy")
477         # We already have its result in the working tree.
478         ;;
479 *)
480         echo "Rewinding the tree to pristine..."
481         restorestate
482         echo "Using the $best_strategy to prepare resolving by hand."
483         git-merge-$best_strategy $common -- "$head_arg" "$@"
484         ;;
485 esac
486
487 if test "$squash" = t
488 then
489         finish
490 else
491         for remote
492         do
493                 echo $remote
494         done >"$GIT_DIR/MERGE_HEAD"
495         printf '%s\n' "$merge_msg" >"$GIT_DIR/MERGE_MSG"
496 fi
497
498 if test "$merge_was_ok" = t
499 then
500         echo >&2 \
501         "Automatic merge went well; stopped before committing as requested"
502         exit 0
503 else
504         {
505             echo '
506 Conflicts:
507 '
508                 git ls-files --unmerged |
509                 sed -e 's/^[^   ]*      /       /' |
510                 uniq
511         } >>"$GIT_DIR/MERGE_MSG"
512         git rerere
513         die "Automatic merge failed; fix conflicts and then commit the result."
514 fi