fetch: use "quick" has_sha1_file for tag following
[git] / git-rebase--interactive.sh
1 # This shell script fragment is sourced by git-rebase to implement
2 # its interactive mode.  "git rebase --interactive" makes it easy
3 # to fix up commits in the middle of a series and rearrange commits.
4 #
5 # Copyright (c) 2006 Johannes E. Schindelin
6 #
7 # The original idea comes from Eric W. Biederman, in
8 # http://article.gmane.org/gmane.comp.version-control.git/22407
9 #
10 # The file containing rebase commands, comments, and empty lines.
11 # This file is created by "git rebase -i" then edited by the user.  As
12 # the lines are processed, they are removed from the front of this
13 # file and written to the tail of $done.
14 todo="$state_dir"/git-rebase-todo
15
16 # The rebase command lines that have already been processed.  A line
17 # is moved here when it is first handled, before any associated user
18 # actions.
19 done="$state_dir"/done
20
21 # The commit message that is planned to be used for any changes that
22 # need to be committed following a user interaction.
23 msg="$state_dir"/message
24
25 # The file into which is accumulated the suggested commit message for
26 # squash/fixup commands.  When the first of a series of squash/fixups
27 # is seen, the file is created and the commit message from the
28 # previous commit and from the first squash/fixup commit are written
29 # to it.  The commit message for each subsequent squash/fixup commit
30 # is appended to the file as it is processed.
31 #
32 # The first line of the file is of the form
33 #     # This is a combination of $count commits.
34 # where $count is the number of commits whose messages have been
35 # written to the file so far (including the initial "pick" commit).
36 # Each time that a commit message is processed, this line is read and
37 # updated.  It is deleted just before the combined commit is made.
38 squash_msg="$state_dir"/message-squash
39
40 # If the current series of squash/fixups has not yet included a squash
41 # command, then this file exists and holds the commit message of the
42 # original "pick" commit.  (If the series ends without a "squash"
43 # command, then this can be used as the commit message of the combined
44 # commit without opening the editor.)
45 fixup_msg="$state_dir"/message-fixup
46
47 # $rewritten is the name of a directory containing files for each
48 # commit that is reachable by at least one merge base of $head and
49 # $upstream. They are not necessarily rewritten, but their children
50 # might be.  This ensures that commits on merged, but otherwise
51 # unrelated side branches are left alone. (Think "X" in the man page's
52 # example.)
53 rewritten="$state_dir"/rewritten
54
55 dropped="$state_dir"/dropped
56
57 end="$state_dir"/end
58 msgnum="$state_dir"/msgnum
59
60 # A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
61 # GIT_AUTHOR_DATE that will be used for the commit that is currently
62 # being rebased.
63 author_script="$state_dir"/author-script
64
65 # When an "edit" rebase command is being processed, the SHA1 of the
66 # commit to be edited is recorded in this file.  When "git rebase
67 # --continue" is executed, if there are any staged changes then they
68 # will be amended to the HEAD commit, but only provided the HEAD
69 # commit is still the commit to be edited.  When any other rebase
70 # command is processed, this file is deleted.
71 amend="$state_dir"/amend
72
73 # For the post-rewrite hook, we make a list of rewritten commits and
74 # their new sha1s.  The rewritten-pending list keeps the sha1s of
75 # commits that have been processed, but not committed yet,
76 # e.g. because they are waiting for a 'squash' command.
77 rewritten_list="$state_dir"/rewritten-list
78 rewritten_pending="$state_dir"/rewritten-pending
79
80 # Work around Git for Windows' Bash whose "read" does not strip CRLF
81 # and leaves CR at the end instead.
82 cr=$(printf "\015")
83
84 strategy_args=${strategy:+--strategy=$strategy}
85 test -n "$strategy_opts" &&
86 eval '
87         for strategy_opt in '"$strategy_opts"'
88         do
89                 strategy_args="$strategy_args -X$(git rev-parse --sq-quote "${strategy_opt#--}")"
90         done
91 '
92
93 GIT_CHERRY_PICK_HELP="$resolvemsg"
94 export GIT_CHERRY_PICK_HELP
95
96 comment_char=$(git config --get core.commentchar 2>/dev/null | cut -c1)
97 : ${comment_char:=#}
98
99 warn () {
100         printf '%s\n' "$*" >&2
101 }
102
103 # Output the commit message for the specified commit.
104 commit_message () {
105         git cat-file commit "$1" | sed "1,/^$/d"
106 }
107
108 orig_reflog_action="$GIT_REFLOG_ACTION"
109
110 comment_for_reflog () {
111         case "$orig_reflog_action" in
112         ''|rebase*)
113                 GIT_REFLOG_ACTION="rebase -i ($1)"
114                 export GIT_REFLOG_ACTION
115                 ;;
116         esac
117 }
118
119 last_count=
120 mark_action_done () {
121         sed -e 1q < "$todo" >> "$done"
122         sed -e 1d < "$todo" >> "$todo".new
123         mv -f "$todo".new "$todo"
124         new_count=$(git stripspace --strip-comments <"$done" | wc -l)
125         echo $new_count >"$msgnum"
126         total=$(($new_count + $(git stripspace --strip-comments <"$todo" | wc -l)))
127         echo $total >"$end"
128         if test "$last_count" != "$new_count"
129         then
130                 last_count=$new_count
131                 printf "Rebasing (%d/%d)\r" $new_count $total
132                 test -z "$verbose" || echo
133         fi
134 }
135
136 # Put the last action marked done at the beginning of the todo list
137 # again. If there has not been an action marked done yet, leave the list of
138 # items on the todo list unchanged.
139 reschedule_last_action () {
140         tail -n 1 "$done" | cat - "$todo" >"$todo".new
141         sed -e \$d <"$done" >"$done".new
142         mv -f "$todo".new "$todo"
143         mv -f "$done".new "$done"
144 }
145
146 append_todo_help () {
147         git stripspace --comment-lines >>"$todo" <<\EOF
148
149 Commands:
150  p, pick = use commit
151  r, reword = use commit, but edit the commit message
152  e, edit = use commit, but stop for amending
153  s, squash = use commit, but meld into previous commit
154  f, fixup = like "squash", but discard this commit's log message
155  x, exec = run command (the rest of the line) using shell
156  d, drop = remove commit
157
158 These lines can be re-ordered; they are executed from top to bottom.
159
160 EOF
161         if test $(get_missing_commit_check_level) = error
162         then
163                 git stripspace --comment-lines >>"$todo" <<\EOF
164 Do not remove any line. Use 'drop' explicitly to remove a commit.
165 EOF
166         else
167                 git stripspace --comment-lines >>"$todo" <<\EOF
168 If you remove a line here THAT COMMIT WILL BE LOST.
169 EOF
170         fi
171 }
172
173 make_patch () {
174         sha1_and_parents="$(git rev-list --parents -1 "$1")"
175         case "$sha1_and_parents" in
176         ?*' '?*' '?*)
177                 git diff --cc $sha1_and_parents
178                 ;;
179         ?*' '?*)
180                 git diff-tree -p "$1^!"
181                 ;;
182         *)
183                 echo "Root commit"
184                 ;;
185         esac > "$state_dir"/patch
186         test -f "$msg" ||
187                 commit_message "$1" > "$msg"
188         test -f "$author_script" ||
189                 get_author_ident_from_commit "$1" > "$author_script"
190 }
191
192 die_with_patch () {
193         echo "$1" > "$state_dir"/stopped-sha
194         make_patch "$1"
195         die "$2"
196 }
197
198 exit_with_patch () {
199         echo "$1" > "$state_dir"/stopped-sha
200         make_patch $1
201         git rev-parse --verify HEAD > "$amend"
202         gpg_sign_opt_quoted=${gpg_sign_opt:+$(git rev-parse --sq-quote "$gpg_sign_opt")}
203         warn "You can amend the commit now, with"
204         warn
205         warn "  git commit --amend $gpg_sign_opt_quoted"
206         warn
207         warn "Once you are satisfied with your changes, run"
208         warn
209         warn "  git rebase --continue"
210         warn
211         exit $2
212 }
213
214 die_abort () {
215         apply_autostash
216         rm -rf "$state_dir"
217         die "$1"
218 }
219
220 has_action () {
221         test -n "$(git stripspace --strip-comments <"$1")"
222 }
223
224 is_empty_commit() {
225         tree=$(git rev-parse -q --verify "$1"^{tree} 2>/dev/null ||
226                 die "$1: not a commit that can be picked")
227         ptree=$(git rev-parse -q --verify "$1"^^{tree} 2>/dev/null ||
228                 ptree=4b825dc642cb6eb9a060e54bf8d69288fbee4904)
229         test "$tree" = "$ptree"
230 }
231
232 is_merge_commit()
233 {
234         git rev-parse --verify --quiet "$1"^2 >/dev/null 2>&1
235 }
236
237 # Run command with GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
238 # GIT_AUTHOR_DATE exported from the current environment.
239 do_with_author () {
240         (
241                 export GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_AUTHOR_DATE
242                 "$@"
243         )
244 }
245
246 git_sequence_editor () {
247         if test -z "$GIT_SEQUENCE_EDITOR"
248         then
249                 GIT_SEQUENCE_EDITOR="$(git config sequence.editor)"
250                 if [ -z "$GIT_SEQUENCE_EDITOR" ]
251                 then
252                         GIT_SEQUENCE_EDITOR="$(git var GIT_EDITOR)" || return $?
253                 fi
254         fi
255
256         eval "$GIT_SEQUENCE_EDITOR" '"$@"'
257 }
258
259 pick_one () {
260         ff=--ff
261
262         case "$1" in -n) sha1=$2; ff= ;; *) sha1=$1 ;; esac
263         case "$force_rebase" in '') ;; ?*) ff= ;; esac
264         output git rev-parse --verify $sha1 || die "Invalid commit name: $sha1"
265
266         if is_empty_commit "$sha1"
267         then
268                 empty_args="--allow-empty"
269         fi
270
271         test -d "$rewritten" &&
272                 pick_one_preserving_merges "$@" && return
273         output eval git cherry-pick \
274                         ${gpg_sign_opt:+$(git rev-parse --sq-quote "$gpg_sign_opt")} \
275                         "$strategy_args" $empty_args $ff "$@"
276
277         # If cherry-pick dies it leaves the to-be-picked commit unrecorded. Reschedule
278         # previous task so this commit is not lost.
279         ret=$?
280         case "$ret" in [01]) ;; *) reschedule_last_action ;; esac
281         return $ret
282 }
283
284 pick_one_preserving_merges () {
285         fast_forward=t
286         case "$1" in
287         -n)
288                 fast_forward=f
289                 sha1=$2
290                 ;;
291         *)
292                 sha1=$1
293                 ;;
294         esac
295         sha1=$(git rev-parse $sha1)
296
297         if test -f "$state_dir"/current-commit
298         then
299                 if test "$fast_forward" = t
300                 then
301                         while read current_commit
302                         do
303                                 git rev-parse HEAD > "$rewritten"/$current_commit
304                         done <"$state_dir"/current-commit
305                         rm "$state_dir"/current-commit ||
306                         die "Cannot write current commit's replacement sha1"
307                 fi
308         fi
309
310         echo $sha1 >> "$state_dir"/current-commit
311
312         # rewrite parents; if none were rewritten, we can fast-forward.
313         new_parents=
314         pend=" $(git rev-list --parents -1 $sha1 | cut -d' ' -s -f2-)"
315         if test "$pend" = " "
316         then
317                 pend=" root"
318         fi
319         while [ "$pend" != "" ]
320         do
321                 p=$(expr "$pend" : ' \([^ ]*\)')
322                 pend="${pend# $p}"
323
324                 if test -f "$rewritten"/$p
325                 then
326                         new_p=$(cat "$rewritten"/$p)
327
328                         # If the todo reordered commits, and our parent is marked for
329                         # rewriting, but hasn't been gotten to yet, assume the user meant to
330                         # drop it on top of the current HEAD
331                         if test -z "$new_p"
332                         then
333                                 new_p=$(git rev-parse HEAD)
334                         fi
335
336                         test $p != $new_p && fast_forward=f
337                         case "$new_parents" in
338                         *$new_p*)
339                                 ;; # do nothing; that parent is already there
340                         *)
341                                 new_parents="$new_parents $new_p"
342                                 ;;
343                         esac
344                 else
345                         if test -f "$dropped"/$p
346                         then
347                                 fast_forward=f
348                                 replacement="$(cat "$dropped"/$p)"
349                                 test -z "$replacement" && replacement=root
350                                 pend=" $replacement$pend"
351                         else
352                                 new_parents="$new_parents $p"
353                         fi
354                 fi
355         done
356         case $fast_forward in
357         t)
358                 output warn "Fast-forward to $sha1"
359                 output git reset --hard $sha1 ||
360                         die "Cannot fast-forward to $sha1"
361                 ;;
362         f)
363                 first_parent=$(expr "$new_parents" : ' \([^ ]*\)')
364
365                 if [ "$1" != "-n" ]
366                 then
367                         # detach HEAD to current parent
368                         output git checkout $first_parent 2> /dev/null ||
369                                 die "Cannot move HEAD to $first_parent"
370                 fi
371
372                 case "$new_parents" in
373                 ' '*' '*)
374                         test "a$1" = a-n && die "Refusing to squash a merge: $sha1"
375
376                         # redo merge
377                         author_script_content=$(get_author_ident_from_commit $sha1)
378                         eval "$author_script_content"
379                         msg_content="$(commit_message $sha1)"
380                         # No point in merging the first parent, that's HEAD
381                         new_parents=${new_parents# $first_parent}
382                         merge_args="--no-log --no-ff"
383                         if ! do_with_author output eval \
384                         'git merge ${gpg_sign_opt:+"$gpg_sign_opt"} \
385                                 $merge_args $strategy_args -m "$msg_content" $new_parents'
386                         then
387                                 printf "%s\n" "$msg_content" > "$GIT_DIR"/MERGE_MSG
388                                 die_with_patch $sha1 "Error redoing merge $sha1"
389                         fi
390                         echo "$sha1 $(git rev-parse HEAD^0)" >> "$rewritten_list"
391                         ;;
392                 *)
393                         output eval git cherry-pick \
394                                 ${gpg_sign_opt:+$(git rev-parse --sq-quote "$gpg_sign_opt")} \
395                                 "$strategy_args" "$@" ||
396                                 die_with_patch $sha1 "Could not pick $sha1"
397                         ;;
398                 esac
399                 ;;
400         esac
401 }
402
403 nth_string () {
404         case "$1" in
405         *1[0-9]|*[04-9]) echo "$1"th;;
406         *1) echo "$1"st;;
407         *2) echo "$1"nd;;
408         *3) echo "$1"rd;;
409         esac
410 }
411
412 update_squash_messages () {
413         if test -f "$squash_msg"; then
414                 mv "$squash_msg" "$squash_msg".bak || exit
415                 count=$(($(sed -n \
416                         -e "1s/^. This is a combination of \(.*\) commits\./\1/p" \
417                         -e "q" < "$squash_msg".bak)+1))
418                 {
419                         printf '%s\n' "$comment_char This is a combination of $count commits."
420                         sed -e 1d -e '2,/^./{
421                                 /^$/d
422                         }' <"$squash_msg".bak
423                 } >"$squash_msg"
424         else
425                 commit_message HEAD > "$fixup_msg" || die "Cannot write $fixup_msg"
426                 count=2
427                 {
428                         printf '%s\n' "$comment_char This is a combination of 2 commits."
429                         printf '%s\n' "$comment_char The first commit's message is:"
430                         echo
431                         cat "$fixup_msg"
432                 } >"$squash_msg"
433         fi
434         case $1 in
435         squash)
436                 rm -f "$fixup_msg"
437                 echo
438                 printf '%s\n' "$comment_char This is the $(nth_string $count) commit message:"
439                 echo
440                 commit_message $2
441                 ;;
442         fixup)
443                 echo
444                 printf '%s\n' "$comment_char The $(nth_string $count) commit message will be skipped:"
445                 echo
446                 # Change the space after the comment character to TAB:
447                 commit_message $2 | git stripspace --comment-lines | sed -e 's/ /       /'
448                 ;;
449         esac >>"$squash_msg"
450 }
451
452 peek_next_command () {
453         git stripspace --strip-comments <"$todo" | sed -n -e 's/ .*//p' -e q
454 }
455
456 # A squash/fixup has failed.  Prepare the long version of the squash
457 # commit message, then die_with_patch.  This code path requires the
458 # user to edit the combined commit message for all commits that have
459 # been squashed/fixedup so far.  So also erase the old squash
460 # messages, effectively causing the combined commit to be used as the
461 # new basis for any further squash/fixups.  Args: sha1 rest
462 die_failed_squash() {
463         mv "$squash_msg" "$msg" || exit
464         rm -f "$fixup_msg"
465         cp "$msg" "$GIT_DIR"/MERGE_MSG || exit
466         warn
467         warn "Could not apply $1... $2"
468         die_with_patch $1 ""
469 }
470
471 flush_rewritten_pending() {
472         test -s "$rewritten_pending" || return
473         newsha1="$(git rev-parse HEAD^0)"
474         sed "s/$/ $newsha1/" < "$rewritten_pending" >> "$rewritten_list"
475         rm -f "$rewritten_pending"
476 }
477
478 record_in_rewritten() {
479         oldsha1="$(git rev-parse $1)"
480         echo "$oldsha1" >> "$rewritten_pending"
481
482         case "$(peek_next_command)" in
483         squash|s|fixup|f)
484                 ;;
485         *)
486                 flush_rewritten_pending
487                 ;;
488         esac
489 }
490
491 do_pick () {
492         if test "$(git rev-parse HEAD)" = "$squash_onto"
493         then
494                 # Set the correct commit message and author info on the
495                 # sentinel root before cherry-picking the original changes
496                 # without committing (-n).  Finally, update the sentinel again
497                 # to include these changes.  If the cherry-pick results in a
498                 # conflict, this means our behaviour is similar to a standard
499                 # failed cherry-pick during rebase, with a dirty index to
500                 # resolve before manually running git commit --amend then git
501                 # rebase --continue.
502                 git commit --allow-empty --allow-empty-message --amend \
503                            --no-post-rewrite -n -q -C $1 &&
504                         pick_one -n $1 &&
505                         git commit --allow-empty --allow-empty-message \
506                                    --amend --no-post-rewrite -n -q -C $1 \
507                                    ${gpg_sign_opt:+"$gpg_sign_opt"} ||
508                         die_with_patch $1 "Could not apply $1... $2"
509         else
510                 pick_one $1 ||
511                         die_with_patch $1 "Could not apply $1... $2"
512         fi
513 }
514
515 do_next () {
516         rm -f "$msg" "$author_script" "$amend" "$state_dir"/stopped-sha || exit
517         read -r command sha1 rest < "$todo"
518         case "$command" in
519         "$comment_char"*|''|noop|drop|d)
520                 mark_action_done
521                 ;;
522         "$cr")
523                 # Work around CR left by "read" (e.g. with Git for Windows' Bash).
524                 mark_action_done
525                 ;;
526         pick|p)
527                 comment_for_reflog pick
528
529                 mark_action_done
530                 do_pick $sha1 "$rest"
531                 record_in_rewritten $sha1
532                 ;;
533         reword|r)
534                 comment_for_reflog reword
535
536                 mark_action_done
537                 do_pick $sha1 "$rest"
538                 git commit --amend --no-post-rewrite ${gpg_sign_opt:+"$gpg_sign_opt"} || {
539                         warn "Could not amend commit after successfully picking $sha1... $rest"
540                         warn "This is most likely due to an empty commit message, or the pre-commit hook"
541                         warn "failed. If the pre-commit hook failed, you may need to resolve the issue before"
542                         warn "you are able to reword the commit."
543                         exit_with_patch $sha1 1
544                 }
545                 record_in_rewritten $sha1
546                 ;;
547         edit|e)
548                 comment_for_reflog edit
549
550                 mark_action_done
551                 do_pick $sha1 "$rest"
552                 sha1_abbrev=$(git rev-parse --short $sha1)
553                 warn "Stopped at $sha1_abbrev... $rest"
554                 exit_with_patch $sha1 0
555                 ;;
556         squash|s|fixup|f)
557                 case "$command" in
558                 squash|s)
559                         squash_style=squash
560                         ;;
561                 fixup|f)
562                         squash_style=fixup
563                         ;;
564                 esac
565                 comment_for_reflog $squash_style
566
567                 test -f "$done" && has_action "$done" ||
568                         die "Cannot '$squash_style' without a previous commit"
569
570                 mark_action_done
571                 update_squash_messages $squash_style $sha1
572                 author_script_content=$(get_author_ident_from_commit HEAD)
573                 echo "$author_script_content" > "$author_script"
574                 eval "$author_script_content"
575                 if ! pick_one -n $sha1
576                 then
577                         git rev-parse --verify HEAD >"$amend"
578                         die_failed_squash $sha1 "$rest"
579                 fi
580                 case "$(peek_next_command)" in
581                 squash|s|fixup|f)
582                         # This is an intermediate commit; its message will only be
583                         # used in case of trouble.  So use the long version:
584                         do_with_author output git commit --amend --no-verify -F "$squash_msg" \
585                                 ${gpg_sign_opt:+"$gpg_sign_opt"} ||
586                                 die_failed_squash $sha1 "$rest"
587                         ;;
588                 *)
589                         # This is the final command of this squash/fixup group
590                         if test -f "$fixup_msg"
591                         then
592                                 do_with_author git commit --amend --no-verify -F "$fixup_msg" \
593                                         ${gpg_sign_opt:+"$gpg_sign_opt"} ||
594                                         die_failed_squash $sha1 "$rest"
595                         else
596                                 cp "$squash_msg" "$GIT_DIR"/SQUASH_MSG || exit
597                                 rm -f "$GIT_DIR"/MERGE_MSG
598                                 do_with_author git commit --amend --no-verify -F "$GIT_DIR"/SQUASH_MSG -e \
599                                         ${gpg_sign_opt:+"$gpg_sign_opt"} ||
600                                         die_failed_squash $sha1 "$rest"
601                         fi
602                         rm -f "$squash_msg" "$fixup_msg"
603                         ;;
604                 esac
605                 record_in_rewritten $sha1
606                 ;;
607         x|"exec")
608                 read -r command rest < "$todo"
609                 mark_action_done
610                 printf 'Executing: %s\n' "$rest"
611                 "${SHELL:-@SHELL_PATH@}" -c "$rest" # Actual execution
612                 status=$?
613                 # Run in subshell because require_clean_work_tree can die.
614                 dirty=f
615                 (require_clean_work_tree "rebase" 2>/dev/null) || dirty=t
616                 if test "$status" -ne 0
617                 then
618                         warn "Execution failed: $rest"
619                         test "$dirty" = f ||
620                         warn "and made changes to the index and/or the working tree"
621
622                         warn "You can fix the problem, and then run"
623                         warn
624                         warn "  git rebase --continue"
625                         warn
626                         if test $status -eq 127         # command not found
627                         then
628                                 status=1
629                         fi
630                         exit "$status"
631                 elif test "$dirty" = t
632                 then
633                         warn "Execution succeeded: $rest"
634                         warn "but left changes to the index and/or the working tree"
635                         warn "Commit or stash your changes, and then run"
636                         warn
637                         warn "  git rebase --continue"
638                         warn
639                         exit 1
640                 fi
641                 ;;
642         *)
643                 warn "Unknown command: $command $sha1 $rest"
644                 fixtodo="Please fix this using 'git rebase --edit-todo'."
645                 if git rev-parse --verify -q "$sha1" >/dev/null
646                 then
647                         die_with_patch $sha1 "$fixtodo"
648                 else
649                         die "$fixtodo"
650                 fi
651                 ;;
652         esac
653         test -s "$todo" && return
654
655         comment_for_reflog finish &&
656         newhead=$(git rev-parse HEAD) &&
657         case $head_name in
658         refs/*)
659                 message="$GIT_REFLOG_ACTION: $head_name onto $onto" &&
660                 git update-ref -m "$message" $head_name $newhead $orig_head &&
661                 git symbolic-ref \
662                   -m "$GIT_REFLOG_ACTION: returning to $head_name" \
663                   HEAD $head_name
664                 ;;
665         esac && {
666                 test ! -f "$state_dir"/verbose ||
667                         git diff-tree --stat $orig_head..HEAD
668         } &&
669         {
670                 test -s "$rewritten_list" &&
671                 git notes copy --for-rewrite=rebase < "$rewritten_list" ||
672                 true # we don't care if this copying failed
673         } &&
674         hook="$(git rev-parse --git-path hooks/post-rewrite)"
675         if test -x "$hook" && test -s "$rewritten_list"; then
676                 "$hook" rebase < "$rewritten_list"
677                 true # we don't care if this hook failed
678         fi &&
679         warn "Successfully rebased and updated $head_name."
680
681         return 1 # not failure; just to break the do_rest loop
682 }
683
684 # can only return 0, when the infinite loop breaks
685 do_rest () {
686         while :
687         do
688                 do_next || break
689         done
690 }
691
692 # skip picking commits whose parents are unchanged
693 skip_unnecessary_picks () {
694         fd=3
695         while read -r command rest
696         do
697                 # fd=3 means we skip the command
698                 case "$fd,$command" in
699                 3,pick|3,p)
700                         # pick a commit whose parent is current $onto -> skip
701                         sha1=${rest%% *}
702                         case "$(git rev-parse --verify --quiet "$sha1"^)" in
703                         "$onto"*)
704                                 onto=$sha1
705                                 ;;
706                         *)
707                                 fd=1
708                                 ;;
709                         esac
710                         ;;
711                 3,"$comment_char"*|3,)
712                         # copy comments
713                         ;;
714                 *)
715                         fd=1
716                         ;;
717                 esac
718                 printf '%s\n' "$command${rest:+ }$rest" >&$fd
719         done <"$todo" >"$todo.new" 3>>"$done" &&
720         mv -f "$todo".new "$todo" &&
721         case "$(peek_next_command)" in
722         squash|s|fixup|f)
723                 record_in_rewritten "$onto"
724                 ;;
725         esac ||
726         die "Could not skip unnecessary pick commands"
727 }
728
729 transform_todo_ids () {
730         while read -r command rest
731         do
732                 case "$command" in
733                 "$comment_char"* | exec)
734                         # Be careful for oddball commands like 'exec'
735                         # that do not have a SHA-1 at the beginning of $rest.
736                         ;;
737                 *)
738                         sha1=$(git rev-parse --verify --quiet "$@" ${rest%%[     ]*}) &&
739                         rest="$sha1 ${rest#*[    ]}"
740                         ;;
741                 esac
742                 printf '%s\n' "$command${rest:+ }$rest"
743         done <"$todo" >"$todo.new" &&
744         mv -f "$todo.new" "$todo"
745 }
746
747 expand_todo_ids() {
748         transform_todo_ids
749 }
750
751 collapse_todo_ids() {
752         transform_todo_ids --short
753 }
754
755 # Rearrange the todo list that has both "pick sha1 msg" and
756 # "pick sha1 fixup!/squash! msg" appears in it so that the latter
757 # comes immediately after the former, and change "pick" to
758 # "fixup"/"squash".
759 #
760 # Note that if the config has specified a custom instruction format
761 # each log message will be re-retrieved in order to normalize the
762 # autosquash arrangement
763 rearrange_squash () {
764         # extract fixup!/squash! lines and resolve any referenced sha1's
765         while read -r pick sha1 message
766         do
767                 test -z "${format}" || message=$(git log -n 1 --format="%s" ${sha1})
768                 case "$message" in
769                 "squash! "*|"fixup! "*)
770                         action="${message%%!*}"
771                         rest=$message
772                         prefix=
773                         # skip all squash! or fixup! (but save for later)
774                         while :
775                         do
776                                 case "$rest" in
777                                 "squash! "*|"fixup! "*)
778                                         prefix="$prefix${rest%%!*},"
779                                         rest="${rest#*! }"
780                                         ;;
781                                 *)
782                                         break
783                                         ;;
784                                 esac
785                         done
786                         printf '%s %s %s %s\n' "$sha1" "$action" "$prefix" "$rest"
787                         # if it's a single word, try to resolve to a full sha1 and
788                         # emit a second copy. This allows us to match on both message
789                         # and on sha1 prefix
790                         if test "${rest#* }" = "$rest"; then
791                                 fullsha="$(git rev-parse -q --verify "$rest" 2>/dev/null)"
792                                 if test -n "$fullsha"; then
793                                         # prefix the action to uniquely identify this line as
794                                         # intended for full sha1 match
795                                         echo "$sha1 +$action $prefix $fullsha"
796                                 fi
797                         fi
798                 esac
799         done >"$1.sq" <"$1"
800         test -s "$1.sq" || return
801
802         used=
803         while read -r pick sha1 message
804         do
805                 case " $used" in
806                 *" $sha1 "*) continue ;;
807                 esac
808                 printf '%s\n' "$pick $sha1 $message"
809                 test -z "${format}" || message=$(git log -n 1 --format="%s" ${sha1})
810                 used="$used$sha1 "
811                 while read -r squash action msg_prefix msg_content
812                 do
813                         case " $used" in
814                         *" $squash "*) continue ;;
815                         esac
816                         emit=0
817                         case "$action" in
818                         +*)
819                                 action="${action#+}"
820                                 # full sha1 prefix test
821                                 case "$msg_content" in "$sha1"*) emit=1;; esac ;;
822                         *)
823                                 # message prefix test
824                                 case "$message" in "$msg_content"*) emit=1;; esac ;;
825                         esac
826                         if test $emit = 1; then
827                                 if test -n "${format}"
828                                 then
829                                         msg_content=$(git log -n 1 --format="${format}" ${squash})
830                                 else
831                                         msg_content="$(echo "$msg_prefix" | sed "s/,/! /g")$msg_content"
832                                 fi
833                                 printf '%s\n' "$action $squash $msg_content"
834                                 used="$used$squash "
835                         fi
836                 done <"$1.sq"
837         done >"$1.rearranged" <"$1"
838         cat "$1.rearranged" >"$1"
839         rm -f "$1.sq" "$1.rearranged"
840 }
841
842 # Add commands after a pick or after a squash/fixup serie
843 # in the todo list.
844 add_exec_commands () {
845         {
846                 first=t
847                 while read -r insn rest
848                 do
849                         case $insn in
850                         pick)
851                                 test -n "$first" ||
852                                 printf "%s" "$cmd"
853                                 ;;
854                         esac
855                         printf "%s %s\n" "$insn" "$rest"
856                         first=
857                 done
858                 printf "%s" "$cmd"
859         } <"$1" >"$1.new" &&
860         mv "$1.new" "$1"
861 }
862
863 # Check if the SHA-1 passed as an argument is a
864 # correct one, if not then print $2 in "$todo".badsha
865 # $1: the SHA-1 to test
866 # $2: the line number of the input
867 # $3: the input filename
868 check_commit_sha () {
869         badsha=0
870         if test -z "$1"
871         then
872                 badsha=1
873         else
874                 sha1_verif="$(git rev-parse --verify --quiet $1^{commit})"
875                 if test -z "$sha1_verif"
876                 then
877                         badsha=1
878                 fi
879         fi
880
881         if test $badsha -ne 0
882         then
883                 line="$(sed -n -e "${2}p" "$3")"
884                 warn "Warning: the SHA-1 is missing or isn't" \
885                         "a commit in the following line:"
886                 warn " - $line"
887                 warn
888         fi
889
890         return $badsha
891 }
892
893 # prints the bad commits and bad commands
894 # from the todolist in stdin
895 check_bad_cmd_and_sha () {
896         retval=0
897         lineno=0
898         while read -r command rest
899         do
900                 lineno=$(( $lineno + 1 ))
901                 case $command in
902                 "$comment_char"*|''|noop|x|exec)
903                         # Doesn't expect a SHA-1
904                         ;;
905                 "$cr")
906                         # Work around CR left by "read" (e.g. with Git for
907                         # Windows' Bash).
908                         ;;
909                 pick|p|drop|d|reword|r|edit|e|squash|s|fixup|f)
910                         if ! check_commit_sha "${rest%%[        ]*}" "$lineno" "$1"
911                         then
912                                 retval=1
913                         fi
914                         ;;
915                 *)
916                         line="$(sed -n -e "${lineno}p" "$1")"
917                         warn "Warning: the command isn't recognized" \
918                                 "in the following line:"
919                         warn " - $line"
920                         warn
921                         retval=1
922                         ;;
923                 esac
924         done <"$1"
925         return $retval
926 }
927
928 # Print the list of the SHA-1 of the commits
929 # from stdin to stdout
930 todo_list_to_sha_list () {
931         git stripspace --strip-comments |
932         while read -r command sha1 rest
933         do
934                 case $command in
935                 "$comment_char"*|''|noop|x|"exec")
936                         ;;
937                 *)
938                         long_sha=$(git rev-list --no-walk "$sha1" 2>/dev/null)
939                         printf "%s\n" "$long_sha"
940                         ;;
941                 esac
942         done
943 }
944
945 # Use warn for each line in stdin
946 warn_lines () {
947         while read -r line
948         do
949                 warn " - $line"
950         done
951 }
952
953 # Switch to the branch in $into and notify it in the reflog
954 checkout_onto () {
955         GIT_REFLOG_ACTION="$GIT_REFLOG_ACTION: checkout $onto_name"
956         output git checkout $onto || die_abort "could not detach HEAD"
957         git update-ref ORIG_HEAD $orig_head
958 }
959
960 get_missing_commit_check_level () {
961         check_level=$(git config --get rebase.missingCommitsCheck)
962         check_level=${check_level:-ignore}
963         # Don't be case sensitive
964         printf '%s' "$check_level" | tr 'A-Z' 'a-z'
965 }
966
967 # Check if the user dropped some commits by mistake
968 # Behaviour determined by rebase.missingCommitsCheck.
969 # Check if there is an unrecognized command or a
970 # bad SHA-1 in a command.
971 check_todo_list () {
972         raise_error=f
973
974         check_level=$(get_missing_commit_check_level)
975
976         case "$check_level" in
977         warn|error)
978                 # Get the SHA-1 of the commits
979                 todo_list_to_sha_list <"$todo".backup >"$todo".oldsha1
980                 todo_list_to_sha_list <"$todo" >"$todo".newsha1
981
982                 # Sort the SHA-1 and compare them
983                 sort -u "$todo".oldsha1 >"$todo".oldsha1+
984                 mv "$todo".oldsha1+ "$todo".oldsha1
985                 sort -u "$todo".newsha1 >"$todo".newsha1+
986                 mv "$todo".newsha1+ "$todo".newsha1
987                 comm -2 -3 "$todo".oldsha1 "$todo".newsha1 >"$todo".miss
988
989                 # Warn about missing commits
990                 if test -s "$todo".miss
991                 then
992                         test "$check_level" = error && raise_error=t
993
994                         warn "Warning: some commits may have been dropped" \
995                                 "accidentally."
996                         warn "Dropped commits (newer to older):"
997
998                         # Make the list user-friendly and display
999                         opt="--no-walk=sorted --format=oneline --abbrev-commit --stdin"
1000                         git rev-list $opt <"$todo".miss | warn_lines
1001
1002                         warn "To avoid this message, use \"drop\" to" \
1003                                 "explicitly remove a commit."
1004                         warn
1005                         warn "Use 'git config rebase.missingCommitsCheck' to change" \
1006                                 "the level of warnings."
1007                         warn "The possible behaviours are: ignore, warn, error."
1008                         warn
1009                 fi
1010                 ;;
1011         ignore)
1012                 ;;
1013         *)
1014                 warn "Unrecognized setting $check_level for option" \
1015                         "rebase.missingCommitsCheck. Ignoring."
1016                 ;;
1017         esac
1018
1019         if ! check_bad_cmd_and_sha "$todo"
1020         then
1021                 raise_error=t
1022         fi
1023
1024         if test $raise_error = t
1025         then
1026                 # Checkout before the first commit of the
1027                 # rebase: this way git rebase --continue
1028                 # will work correctly as it expects HEAD to be
1029                 # placed before the commit of the next action
1030                 checkout_onto
1031
1032                 warn "You can fix this with 'git rebase --edit-todo'."
1033                 die "Or you can abort the rebase with 'git rebase --abort'."
1034         fi
1035 }
1036
1037 # The whole contents of this file is run by dot-sourcing it from
1038 # inside a shell function.  It used to be that "return"s we see
1039 # below were not inside any function, and expected to return
1040 # to the function that dot-sourced us.
1041 #
1042 # However, older (9.x) versions of FreeBSD /bin/sh misbehave on such a
1043 # construct and continue to run the statements that follow such a "return".
1044 # As a work-around, we introduce an extra layer of a function
1045 # here, and immediately call it after defining it.
1046 git_rebase__interactive () {
1047
1048 case "$action" in
1049 continue)
1050         # do we have anything to commit?
1051         if git diff-index --cached --quiet HEAD --
1052         then
1053                 # Nothing to commit -- skip this commit
1054
1055                 test ! -f "$GIT_DIR"/CHERRY_PICK_HEAD ||
1056                 rm "$GIT_DIR"/CHERRY_PICK_HEAD ||
1057                 die "Could not remove CHERRY_PICK_HEAD"
1058         else
1059                 if ! test -f "$author_script"
1060                 then
1061                         gpg_sign_opt_quoted=${gpg_sign_opt:+$(git rev-parse --sq-quote "$gpg_sign_opt")}
1062                         die "You have staged changes in your working tree. If these changes are meant to be
1063 squashed into the previous commit, run:
1064
1065   git commit --amend $gpg_sign_opt_quoted
1066
1067 If they are meant to go into a new commit, run:
1068
1069   git commit $gpg_sign_opt_quoted
1070
1071 In both case, once you're done, continue with:
1072
1073   git rebase --continue
1074 "
1075                 fi
1076                 . "$author_script" ||
1077                         die "Error trying to find the author identity to amend commit"
1078                 if test -f "$amend"
1079                 then
1080                         current_head=$(git rev-parse --verify HEAD)
1081                         test "$current_head" = $(cat "$amend") ||
1082                         die "\
1083 You have uncommitted changes in your working tree. Please, commit them
1084 first and then run 'git rebase --continue' again."
1085                         do_with_author git commit --amend --no-verify -F "$msg" -e \
1086                                 ${gpg_sign_opt:+"$gpg_sign_opt"} ||
1087                                 die "Could not commit staged changes."
1088                 else
1089                         do_with_author git commit --no-verify -F "$msg" -e \
1090                                 ${gpg_sign_opt:+"$gpg_sign_opt"} ||
1091                                 die "Could not commit staged changes."
1092                 fi
1093         fi
1094
1095         if test -r "$state_dir"/stopped-sha
1096         then
1097                 record_in_rewritten "$(cat "$state_dir"/stopped-sha)"
1098         fi
1099
1100         require_clean_work_tree "rebase"
1101         do_rest
1102         return 0
1103         ;;
1104 skip)
1105         git rerere clear
1106
1107         do_rest
1108         return 0
1109         ;;
1110 edit-todo)
1111         git stripspace --strip-comments <"$todo" >"$todo".new
1112         mv -f "$todo".new "$todo"
1113         collapse_todo_ids
1114         append_todo_help
1115         git stripspace --comment-lines >>"$todo" <<\EOF
1116
1117 You are editing the todo file of an ongoing interactive rebase.
1118 To continue rebase after editing, run:
1119     git rebase --continue
1120
1121 EOF
1122
1123         git_sequence_editor "$todo" ||
1124                 die "Could not execute editor"
1125         expand_todo_ids
1126
1127         exit
1128         ;;
1129 esac
1130
1131 git var GIT_COMMITTER_IDENT >/dev/null ||
1132         die "You need to set your committer info first"
1133
1134 comment_for_reflog start
1135
1136 if test ! -z "$switch_to"
1137 then
1138         GIT_REFLOG_ACTION="$GIT_REFLOG_ACTION: checkout $switch_to"
1139         output git checkout "$switch_to" -- ||
1140         die "Could not checkout $switch_to"
1141
1142         comment_for_reflog start
1143 fi
1144
1145 orig_head=$(git rev-parse --verify HEAD) || die "No HEAD?"
1146 mkdir -p "$state_dir" || die "Could not create temporary $state_dir"
1147
1148 : > "$state_dir"/interactive || die "Could not mark as interactive"
1149 write_basic_state
1150 if test t = "$preserve_merges"
1151 then
1152         if test -z "$rebase_root"
1153         then
1154                 mkdir "$rewritten" &&
1155                 for c in $(git merge-base --all $orig_head $upstream)
1156                 do
1157                         echo $onto > "$rewritten"/$c ||
1158                                 die "Could not init rewritten commits"
1159                 done
1160         else
1161                 mkdir "$rewritten" &&
1162                 echo $onto > "$rewritten"/root ||
1163                         die "Could not init rewritten commits"
1164         fi
1165         # No cherry-pick because our first pass is to determine
1166         # parents to rewrite and skipping dropped commits would
1167         # prematurely end our probe
1168         merges_option=
1169 else
1170         merges_option="--no-merges --cherry-pick"
1171 fi
1172
1173 shorthead=$(git rev-parse --short $orig_head)
1174 shortonto=$(git rev-parse --short $onto)
1175 if test -z "$rebase_root"
1176         # this is now equivalent to ! -z "$upstream"
1177 then
1178         shortupstream=$(git rev-parse --short $upstream)
1179         revisions=$upstream...$orig_head
1180         shortrevisions=$shortupstream..$shorthead
1181 else
1182         revisions=$onto...$orig_head
1183         shortrevisions=$shorthead
1184 fi
1185 format=$(git config --get rebase.instructionFormat)
1186 # the 'rev-list .. | sed' requires %m to parse; the instruction requires %H to parse
1187 git rev-list $merges_option --format="%m%H ${format:-%s}" \
1188         --reverse --left-right --topo-order \
1189         $revisions ${restrict_revision+^$restrict_revision} | \
1190         sed -n "s/^>//p" |
1191 while read -r sha1 rest
1192 do
1193
1194         if test -z "$keep_empty" && is_empty_commit $sha1 && ! is_merge_commit $sha1
1195         then
1196                 comment_out="$comment_char "
1197         else
1198                 comment_out=
1199         fi
1200
1201         if test t != "$preserve_merges"
1202         then
1203                 printf '%s\n' "${comment_out}pick $sha1 $rest" >>"$todo"
1204         else
1205                 if test -z "$rebase_root"
1206                 then
1207                         preserve=t
1208                         for p in $(git rev-list --parents -1 $sha1 | cut -d' ' -s -f2-)
1209                         do
1210                                 if test -f "$rewritten"/$p
1211                                 then
1212                                         preserve=f
1213                                 fi
1214                         done
1215                 else
1216                         preserve=f
1217                 fi
1218                 if test f = "$preserve"
1219                 then
1220                         touch "$rewritten"/$sha1
1221                         printf '%s\n' "${comment_out}pick $sha1 $rest" >>"$todo"
1222                 fi
1223         fi
1224 done
1225
1226 # Watch for commits that been dropped by --cherry-pick
1227 if test t = "$preserve_merges"
1228 then
1229         mkdir "$dropped"
1230         # Save all non-cherry-picked changes
1231         git rev-list $revisions --left-right --cherry-pick | \
1232                 sed -n "s/^>//p" > "$state_dir"/not-cherry-picks
1233         # Now all commits and note which ones are missing in
1234         # not-cherry-picks and hence being dropped
1235         git rev-list $revisions |
1236         while read rev
1237         do
1238                 if test -f "$rewritten"/$rev &&
1239                    ! sane_grep "$rev" "$state_dir"/not-cherry-picks >/dev/null
1240                 then
1241                         # Use -f2 because if rev-list is telling us this commit is
1242                         # not worthwhile, we don't want to track its multiple heads,
1243                         # just the history of its first-parent for others that will
1244                         # be rebasing on top of it
1245                         git rev-list --parents -1 $rev | cut -d' ' -s -f2 > "$dropped"/$rev
1246                         sha1=$(git rev-list -1 $rev)
1247                         sane_grep -v "^[a-z][a-z]* $sha1" <"$todo" > "${todo}2" ; mv "${todo}2" "$todo"
1248                         rm "$rewritten"/$rev
1249                 fi
1250         done
1251 fi
1252
1253 test -s "$todo" || echo noop >> "$todo"
1254 test -n "$autosquash" && rearrange_squash "$todo"
1255 test -n "$cmd" && add_exec_commands "$todo"
1256
1257 todocount=$(git stripspace --strip-comments <"$todo" | wc -l)
1258 todocount=${todocount##* }
1259
1260 cat >>"$todo" <<EOF
1261
1262 $comment_char Rebase $shortrevisions onto $shortonto ($todocount command(s))
1263 EOF
1264 append_todo_help
1265 git stripspace --comment-lines >>"$todo" <<\EOF
1266
1267 However, if you remove everything, the rebase will be aborted.
1268
1269 EOF
1270
1271 if test -z "$keep_empty"
1272 then
1273         printf '%s\n' "$comment_char Note that empty commits are commented out" >>"$todo"
1274 fi
1275
1276
1277 has_action "$todo" ||
1278         return 2
1279
1280 cp "$todo" "$todo".backup
1281 collapse_todo_ids
1282 git_sequence_editor "$todo" ||
1283         die_abort "Could not execute editor"
1284
1285 has_action "$todo" ||
1286         return 2
1287
1288 check_todo_list
1289
1290 expand_todo_ids
1291
1292 test -d "$rewritten" || test -n "$force_rebase" || skip_unnecessary_picks
1293
1294 checkout_onto
1295 do_rest
1296
1297 }
1298 # ... and then we call the whole thing.
1299 git_rebase__interactive