run-command: add stdin callback for parallelization
[git] / sequencer.c
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object-store.h"
6 #include "object.h"
7 #include "commit.h"
8 #include "sequencer.h"
9 #include "tag.h"
10 #include "run-command.h"
11 #include "hook.h"
12 #include "exec-cmd.h"
13 #include "utf8.h"
14 #include "cache-tree.h"
15 #include "diff.h"
16 #include "revision.h"
17 #include "rerere.h"
18 #include "merge-ort.h"
19 #include "merge-ort-wrappers.h"
20 #include "refs.h"
21 #include "strvec.h"
22 #include "quote.h"
23 #include "trailer.h"
24 #include "log-tree.h"
25 #include "wt-status.h"
26 #include "hashmap.h"
27 #include "notes-utils.h"
28 #include "sigchain.h"
29 #include "unpack-trees.h"
30 #include "worktree.h"
31 #include "oidmap.h"
32 #include "oidset.h"
33 #include "commit-slab.h"
34 #include "alias.h"
35 #include "commit-reach.h"
36 #include "rebase-interactive.h"
37 #include "reset.h"
38
39 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
40
41 static const char sign_off_header[] = "Signed-off-by: ";
42 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
43
44 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
45
46 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
47
48 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
49 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
50 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
51 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
52
53 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
54 /*
55  * The file containing rebase commands, comments, and empty lines.
56  * This file is created by "git rebase -i" then edited by the user. As
57  * the lines are processed, they are removed from the front of this
58  * file and written to the tail of 'done'.
59  */
60 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
61 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
62
63 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
64
65 /*
66  * The rebase command lines that have already been processed. A line
67  * is moved here when it is first handled, before any associated user
68  * actions.
69  */
70 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
71 /*
72  * The file to keep track of how many commands were already processed (e.g.
73  * for the prompt).
74  */
75 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
76 /*
77  * The file to keep track of how many commands are to be processed in total
78  * (e.g. for the prompt).
79  */
80 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
81 /*
82  * The commit message that is planned to be used for any changes that
83  * need to be committed following a user interaction.
84  */
85 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
86 /*
87  * The file into which is accumulated the suggested commit message for
88  * squash/fixup commands. When the first of a series of squash/fixups
89  * is seen, the file is created and the commit message from the
90  * previous commit and from the first squash/fixup commit are written
91  * to it. The commit message for each subsequent squash/fixup commit
92  * is appended to the file as it is processed.
93  */
94 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
95 /*
96  * If the current series of squash/fixups has not yet included a squash
97  * command, then this file exists and holds the commit message of the
98  * original "pick" commit.  (If the series ends without a "squash"
99  * command, then this can be used as the commit message of the combined
100  * commit without opening the editor.)
101  */
102 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
103 /*
104  * This file contains the list fixup/squash commands that have been
105  * accumulated into message-fixup or message-squash so far.
106  */
107 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
108 /*
109  * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
110  * GIT_AUTHOR_DATE that will be used for the commit that is currently
111  * being rebased.
112  */
113 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
114 /*
115  * When an "edit" rebase command is being processed, the SHA1 of the
116  * commit to be edited is recorded in this file.  When "git rebase
117  * --continue" is executed, if there are any staged changes then they
118  * will be amended to the HEAD commit, but only provided the HEAD
119  * commit is still the commit to be edited.  When any other rebase
120  * command is processed, this file is deleted.
121  */
122 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
123 /*
124  * When we stop at a given patch via the "edit" command, this file contains
125  * the commit object name of the corresponding patch.
126  */
127 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
128 /*
129  * For the post-rewrite hook, we make a list of rewritten commits and
130  * their new sha1s.  The rewritten-pending list keeps the sha1s of
131  * commits that have been processed, but not committed yet,
132  * e.g. because they are waiting for a 'squash' command.
133  */
134 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
135 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
136         "rebase-merge/rewritten-pending")
137
138 /*
139  * The path of the file containing the OID of the "squash onto" commit, i.e.
140  * the dummy commit used for `reset [new root]`.
141  */
142 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
143
144 /*
145  * The path of the file listing refs that need to be deleted after the rebase
146  * finishes. This is used by the `label` command to record the need for cleanup.
147  */
148 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
149
150 /*
151  * The following files are written by git-rebase just after parsing the
152  * command-line.
153  */
154 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
155 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
156 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
157 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
158 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
159 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
160 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
161 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
162 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
163 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
164 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
165 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
166 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
167 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
168 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
169 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
170 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
171
172 static int git_sequencer_config(const char *k, const char *v, void *cb)
173 {
174         struct replay_opts *opts = cb;
175         int status;
176
177         if (!strcmp(k, "commit.cleanup")) {
178                 const char *s;
179
180                 status = git_config_string(&s, k, v);
181                 if (status)
182                         return status;
183
184                 if (!strcmp(s, "verbatim")) {
185                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
186                         opts->explicit_cleanup = 1;
187                 } else if (!strcmp(s, "whitespace")) {
188                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
189                         opts->explicit_cleanup = 1;
190                 } else if (!strcmp(s, "strip")) {
191                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
192                         opts->explicit_cleanup = 1;
193                 } else if (!strcmp(s, "scissors")) {
194                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
195                         opts->explicit_cleanup = 1;
196                 } else {
197                         warning(_("invalid commit message cleanup mode '%s'"),
198                                   s);
199                 }
200
201                 free((char *)s);
202                 return status;
203         }
204
205         if (!strcmp(k, "commit.gpgsign")) {
206                 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
207                 return 0;
208         }
209
210         if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
211                 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
212                 if (ret == 0) {
213                         /*
214                          * pull.twohead is allowed to be multi-valued; we only
215                          * care about the first value.
216                          */
217                         char *tmp = strchr(opts->default_strategy, ' ');
218                         if (tmp)
219                                 *tmp = '\0';
220                 }
221                 return ret;
222         }
223
224         status = git_gpg_config(k, v, NULL);
225         if (status)
226                 return status;
227
228         return git_diff_basic_config(k, v, NULL);
229 }
230
231 void sequencer_init_config(struct replay_opts *opts)
232 {
233         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
234         git_config(git_sequencer_config, opts);
235 }
236
237 static inline int is_rebase_i(const struct replay_opts *opts)
238 {
239         return opts->action == REPLAY_INTERACTIVE_REBASE;
240 }
241
242 static const char *get_dir(const struct replay_opts *opts)
243 {
244         if (is_rebase_i(opts))
245                 return rebase_path();
246         return git_path_seq_dir();
247 }
248
249 static const char *get_todo_path(const struct replay_opts *opts)
250 {
251         if (is_rebase_i(opts))
252                 return rebase_path_todo();
253         return git_path_todo_file();
254 }
255
256 /*
257  * Returns 0 for non-conforming footer
258  * Returns 1 for conforming footer
259  * Returns 2 when sob exists within conforming footer
260  * Returns 3 when sob exists within conforming footer as last entry
261  */
262 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
263         size_t ignore_footer)
264 {
265         struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
266         struct trailer_info info;
267         size_t i;
268         int found_sob = 0, found_sob_last = 0;
269         char saved_char;
270
271         opts.no_divider = 1;
272
273         if (ignore_footer) {
274                 saved_char = sb->buf[sb->len - ignore_footer];
275                 sb->buf[sb->len - ignore_footer] = '\0';
276         }
277
278         trailer_info_get(&info, sb->buf, &opts);
279
280         if (ignore_footer)
281                 sb->buf[sb->len - ignore_footer] = saved_char;
282
283         if (info.trailer_start == info.trailer_end)
284                 return 0;
285
286         for (i = 0; i < info.trailer_nr; i++)
287                 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
288                         found_sob = 1;
289                         if (i == info.trailer_nr - 1)
290                                 found_sob_last = 1;
291                 }
292
293         trailer_info_release(&info);
294
295         if (found_sob_last)
296                 return 3;
297         if (found_sob)
298                 return 2;
299         return 1;
300 }
301
302 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
303 {
304         static struct strbuf buf = STRBUF_INIT;
305
306         strbuf_reset(&buf);
307         if (opts->gpg_sign)
308                 sq_quotef(&buf, "-S%s", opts->gpg_sign);
309         return buf.buf;
310 }
311
312 int sequencer_remove_state(struct replay_opts *opts)
313 {
314         struct strbuf buf = STRBUF_INIT;
315         int i, ret = 0;
316
317         if (is_rebase_i(opts) &&
318             strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
319                 char *p = buf.buf;
320                 while (*p) {
321                         char *eol = strchr(p, '\n');
322                         if (eol)
323                                 *eol = '\0';
324                         if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
325                                 warning(_("could not delete '%s'"), p);
326                                 ret = -1;
327                         }
328                         if (!eol)
329                                 break;
330                         p = eol + 1;
331                 }
332         }
333
334         free(opts->gpg_sign);
335         free(opts->default_strategy);
336         free(opts->strategy);
337         for (i = 0; i < opts->xopts_nr; i++)
338                 free(opts->xopts[i]);
339         free(opts->xopts);
340         strbuf_release(&opts->current_fixups);
341
342         strbuf_reset(&buf);
343         strbuf_addstr(&buf, get_dir(opts));
344         if (remove_dir_recursively(&buf, 0))
345                 ret = error(_("could not remove '%s'"), buf.buf);
346         strbuf_release(&buf);
347
348         return ret;
349 }
350
351 static const char *action_name(const struct replay_opts *opts)
352 {
353         switch (opts->action) {
354         case REPLAY_REVERT:
355                 return N_("revert");
356         case REPLAY_PICK:
357                 return N_("cherry-pick");
358         case REPLAY_INTERACTIVE_REBASE:
359                 return N_("rebase");
360         }
361         die(_("unknown action: %d"), opts->action);
362 }
363
364 struct commit_message {
365         char *parent_label;
366         char *label;
367         char *subject;
368         const char *message;
369 };
370
371 static const char *short_commit_name(struct commit *commit)
372 {
373         return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
374 }
375
376 static int get_message(struct commit *commit, struct commit_message *out)
377 {
378         const char *abbrev, *subject;
379         int subject_len;
380
381         out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
382         abbrev = short_commit_name(commit);
383
384         subject_len = find_commit_subject(out->message, &subject);
385
386         out->subject = xmemdupz(subject, subject_len);
387         out->label = xstrfmt("%s (%s)", abbrev, out->subject);
388         out->parent_label = xstrfmt("parent of %s", out->label);
389
390         return 0;
391 }
392
393 static void free_message(struct commit *commit, struct commit_message *msg)
394 {
395         free(msg->parent_label);
396         free(msg->label);
397         free(msg->subject);
398         unuse_commit_buffer(commit, msg->message);
399 }
400
401 static void print_advice(struct repository *r, int show_hint,
402                          struct replay_opts *opts)
403 {
404         char *msg = getenv("GIT_CHERRY_PICK_HELP");
405
406         if (msg) {
407                 fprintf(stderr, "%s\n", msg);
408                 /*
409                  * A conflict has occurred but the porcelain
410                  * (typically rebase --interactive) wants to take care
411                  * of the commit itself so remove CHERRY_PICK_HEAD
412                  */
413                 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
414                                 NULL, 0);
415                 return;
416         }
417
418         if (show_hint) {
419                 if (opts->no_commit)
420                         advise(_("after resolving the conflicts, mark the corrected paths\n"
421                                  "with 'git add <paths>' or 'git rm <paths>'"));
422                 else
423                         advise(_("after resolving the conflicts, mark the corrected paths\n"
424                                  "with 'git add <paths>' or 'git rm <paths>'\n"
425                                  "and commit the result with 'git commit'"));
426         }
427 }
428
429 static int write_message(const void *buf, size_t len, const char *filename,
430                          int append_eol)
431 {
432         struct lock_file msg_file = LOCK_INIT;
433
434         int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
435         if (msg_fd < 0)
436                 return error_errno(_("could not lock '%s'"), filename);
437         if (write_in_full(msg_fd, buf, len) < 0) {
438                 error_errno(_("could not write to '%s'"), filename);
439                 rollback_lock_file(&msg_file);
440                 return -1;
441         }
442         if (append_eol && write(msg_fd, "\n", 1) < 0) {
443                 error_errno(_("could not write eol to '%s'"), filename);
444                 rollback_lock_file(&msg_file);
445                 return -1;
446         }
447         if (commit_lock_file(&msg_file) < 0)
448                 return error(_("failed to finalize '%s'"), filename);
449
450         return 0;
451 }
452
453 int read_oneliner(struct strbuf *buf,
454         const char *path, unsigned flags)
455 {
456         int orig_len = buf->len;
457
458         if (strbuf_read_file(buf, path, 0) < 0) {
459                 if ((flags & READ_ONELINER_WARN_MISSING) ||
460                     (errno != ENOENT && errno != ENOTDIR))
461                         warning_errno(_("could not read '%s'"), path);
462                 return 0;
463         }
464
465         if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
466                 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
467                         --buf->len;
468                 buf->buf[buf->len] = '\0';
469         }
470
471         if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
472                 return 0;
473
474         return 1;
475 }
476
477 static struct tree *empty_tree(struct repository *r)
478 {
479         return lookup_tree(r, the_hash_algo->empty_tree);
480 }
481
482 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
483 {
484         if (repo_read_index_unmerged(repo))
485                 return error_resolve_conflict(_(action_name(opts)));
486
487         error(_("your local changes would be overwritten by %s."),
488                 _(action_name(opts)));
489
490         if (advice_commit_before_merge)
491                 advise(_("commit your changes or stash them to proceed."));
492         return -1;
493 }
494
495 static void update_abort_safety_file(void)
496 {
497         struct object_id head;
498
499         /* Do nothing on a single-pick */
500         if (!file_exists(git_path_seq_dir()))
501                 return;
502
503         if (!get_oid("HEAD", &head))
504                 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
505         else
506                 write_file(git_path_abort_safety_file(), "%s", "");
507 }
508
509 static int fast_forward_to(struct repository *r,
510                            const struct object_id *to,
511                            const struct object_id *from,
512                            int unborn,
513                            struct replay_opts *opts)
514 {
515         struct ref_transaction *transaction;
516         struct strbuf sb = STRBUF_INIT;
517         struct strbuf err = STRBUF_INIT;
518
519         repo_read_index(r);
520         if (checkout_fast_forward(r, from, to, 1))
521                 return -1; /* the callee should have complained already */
522
523         strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
524
525         transaction = ref_transaction_begin(&err);
526         if (!transaction ||
527             ref_transaction_update(transaction, "HEAD",
528                                    to, unborn && !is_rebase_i(opts) ?
529                                    null_oid() : from,
530                                    0, sb.buf, &err) ||
531             ref_transaction_commit(transaction, &err)) {
532                 ref_transaction_free(transaction);
533                 error("%s", err.buf);
534                 strbuf_release(&sb);
535                 strbuf_release(&err);
536                 return -1;
537         }
538
539         strbuf_release(&sb);
540         strbuf_release(&err);
541         ref_transaction_free(transaction);
542         update_abort_safety_file();
543         return 0;
544 }
545
546 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
547         int use_editor)
548 {
549         if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
550                 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
551                                     COMMIT_MSG_CLEANUP_SPACE;
552         else if (!strcmp(cleanup_arg, "verbatim"))
553                 return COMMIT_MSG_CLEANUP_NONE;
554         else if (!strcmp(cleanup_arg, "whitespace"))
555                 return COMMIT_MSG_CLEANUP_SPACE;
556         else if (!strcmp(cleanup_arg, "strip"))
557                 return COMMIT_MSG_CLEANUP_ALL;
558         else if (!strcmp(cleanup_arg, "scissors"))
559                 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
560                                     COMMIT_MSG_CLEANUP_SPACE;
561         else
562                 die(_("Invalid cleanup mode %s"), cleanup_arg);
563 }
564
565 /*
566  * NB using int rather than enum cleanup_mode to stop clang's
567  * -Wtautological-constant-out-of-range-compare complaining that the comparison
568  * is always true.
569  */
570 static const char *describe_cleanup_mode(int cleanup_mode)
571 {
572         static const char *modes[] = { "whitespace",
573                                        "verbatim",
574                                        "scissors",
575                                        "strip" };
576
577         if (cleanup_mode < ARRAY_SIZE(modes))
578                 return modes[cleanup_mode];
579
580         BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
581 }
582
583 void append_conflicts_hint(struct index_state *istate,
584         struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
585 {
586         int i;
587
588         if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
589                 strbuf_addch(msgbuf, '\n');
590                 wt_status_append_cut_line(msgbuf);
591                 strbuf_addch(msgbuf, comment_line_char);
592         }
593
594         strbuf_addch(msgbuf, '\n');
595         strbuf_commented_addf(msgbuf, "Conflicts:\n");
596         for (i = 0; i < istate->cache_nr;) {
597                 const struct cache_entry *ce = istate->cache[i++];
598                 if (ce_stage(ce)) {
599                         strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
600                         while (i < istate->cache_nr &&
601                                !strcmp(ce->name, istate->cache[i]->name))
602                                 i++;
603                 }
604         }
605 }
606
607 static int do_recursive_merge(struct repository *r,
608                               struct commit *base, struct commit *next,
609                               const char *base_label, const char *next_label,
610                               struct object_id *head, struct strbuf *msgbuf,
611                               struct replay_opts *opts)
612 {
613         struct merge_options o;
614         struct merge_result result;
615         struct tree *next_tree, *base_tree, *head_tree;
616         int clean, show_output;
617         int i;
618         struct lock_file index_lock = LOCK_INIT;
619
620         if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
621                 return -1;
622
623         repo_read_index(r);
624
625         init_merge_options(&o, r);
626         o.ancestor = base ? base_label : "(empty tree)";
627         o.branch1 = "HEAD";
628         o.branch2 = next ? next_label : "(empty tree)";
629         if (is_rebase_i(opts))
630                 o.buffer_output = 2;
631         o.show_rename_progress = 1;
632
633         head_tree = parse_tree_indirect(head);
634         next_tree = next ? get_commit_tree(next) : empty_tree(r);
635         base_tree = base ? get_commit_tree(base) : empty_tree(r);
636
637         for (i = 0; i < opts->xopts_nr; i++)
638                 parse_merge_opt(&o, opts->xopts[i]);
639
640         if (opts->strategy && !strcmp(opts->strategy, "ort")) {
641                 memset(&result, 0, sizeof(result));
642                 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
643                                             &result);
644                 show_output = !is_rebase_i(opts) || !result.clean;
645                 /*
646                  * TODO: merge_switch_to_result will update index/working tree;
647                  * we only really want to do that if !result.clean || this is
648                  * the final patch to be picked.  But determining this is the
649                  * final patch would take some work, and "head_tree" would need
650                  * to be replace with the tree the index matched before we
651                  * started doing any picks.
652                  */
653                 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
654                 clean = result.clean;
655         } else {
656                 clean = merge_trees(&o, head_tree, next_tree, base_tree);
657                 if (is_rebase_i(opts) && clean <= 0)
658                         fputs(o.obuf.buf, stdout);
659                 strbuf_release(&o.obuf);
660         }
661         if (clean < 0) {
662                 rollback_lock_file(&index_lock);
663                 return clean;
664         }
665
666         if (write_locked_index(r->index, &index_lock,
667                                COMMIT_LOCK | SKIP_IF_UNCHANGED))
668                 /*
669                  * TRANSLATORS: %s will be "revert", "cherry-pick" or
670                  * "rebase".
671                  */
672                 return error(_("%s: Unable to write new index file"),
673                         _(action_name(opts)));
674
675         if (!clean)
676                 append_conflicts_hint(r->index, msgbuf,
677                                       opts->default_msg_cleanup);
678
679         return !clean;
680 }
681
682 static struct object_id *get_cache_tree_oid(struct index_state *istate)
683 {
684         if (!cache_tree_fully_valid(istate->cache_tree))
685                 if (cache_tree_update(istate, 0)) {
686                         error(_("unable to update cache tree"));
687                         return NULL;
688                 }
689
690         return &istate->cache_tree->oid;
691 }
692
693 static int is_index_unchanged(struct repository *r)
694 {
695         struct object_id head_oid, *cache_tree_oid;
696         struct commit *head_commit;
697         struct index_state *istate = r->index;
698
699         if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
700                 return error(_("could not resolve HEAD commit"));
701
702         head_commit = lookup_commit(r, &head_oid);
703
704         /*
705          * If head_commit is NULL, check_commit, called from
706          * lookup_commit, would have indicated that head_commit is not
707          * a commit object already.  parse_commit() will return failure
708          * without further complaints in such a case.  Otherwise, if
709          * the commit is invalid, parse_commit() will complain.  So
710          * there is nothing for us to say here.  Just return failure.
711          */
712         if (parse_commit(head_commit))
713                 return -1;
714
715         if (!(cache_tree_oid = get_cache_tree_oid(istate)))
716                 return -1;
717
718         return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
719 }
720
721 static int write_author_script(const char *message)
722 {
723         struct strbuf buf = STRBUF_INIT;
724         const char *eol;
725         int res;
726
727         for (;;)
728                 if (!*message || starts_with(message, "\n")) {
729 missing_author:
730                         /* Missing 'author' line? */
731                         unlink(rebase_path_author_script());
732                         return 0;
733                 } else if (skip_prefix(message, "author ", &message))
734                         break;
735                 else if ((eol = strchr(message, '\n')))
736                         message = eol + 1;
737                 else
738                         goto missing_author;
739
740         strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
741         while (*message && *message != '\n' && *message != '\r')
742                 if (skip_prefix(message, " <", &message))
743                         break;
744                 else if (*message != '\'')
745                         strbuf_addch(&buf, *(message++));
746                 else
747                         strbuf_addf(&buf, "'\\%c'", *(message++));
748         strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
749         while (*message && *message != '\n' && *message != '\r')
750                 if (skip_prefix(message, "> ", &message))
751                         break;
752                 else if (*message != '\'')
753                         strbuf_addch(&buf, *(message++));
754                 else
755                         strbuf_addf(&buf, "'\\%c'", *(message++));
756         strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
757         while (*message && *message != '\n' && *message != '\r')
758                 if (*message != '\'')
759                         strbuf_addch(&buf, *(message++));
760                 else
761                         strbuf_addf(&buf, "'\\%c'", *(message++));
762         strbuf_addch(&buf, '\'');
763         res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
764         strbuf_release(&buf);
765         return res;
766 }
767
768 /**
769  * Take a series of KEY='VALUE' lines where VALUE part is
770  * sq-quoted, and append <KEY, VALUE> at the end of the string list
771  */
772 static int parse_key_value_squoted(char *buf, struct string_list *list)
773 {
774         while (*buf) {
775                 struct string_list_item *item;
776                 char *np;
777                 char *cp = strchr(buf, '=');
778                 if (!cp) {
779                         np = strchrnul(buf, '\n');
780                         return error(_("no key present in '%.*s'"),
781                                      (int) (np - buf), buf);
782                 }
783                 np = strchrnul(cp, '\n');
784                 *cp++ = '\0';
785                 item = string_list_append(list, buf);
786
787                 buf = np + (*np == '\n');
788                 *np = '\0';
789                 cp = sq_dequote(cp);
790                 if (!cp)
791                         return error(_("unable to dequote value of '%s'"),
792                                      item->string);
793                 item->util = xstrdup(cp);
794         }
795         return 0;
796 }
797
798 /**
799  * Reads and parses the state directory's "author-script" file, and sets name,
800  * email and date accordingly.
801  * Returns 0 on success, -1 if the file could not be parsed.
802  *
803  * The author script is of the format:
804  *
805  *      GIT_AUTHOR_NAME='$author_name'
806  *      GIT_AUTHOR_EMAIL='$author_email'
807  *      GIT_AUTHOR_DATE='$author_date'
808  *
809  * where $author_name, $author_email and $author_date are quoted. We are strict
810  * with our parsing, as the file was meant to be eval'd in the now-removed
811  * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
812  * from what this function expects, it is better to bail out than to do
813  * something that the user does not expect.
814  */
815 int read_author_script(const char *path, char **name, char **email, char **date,
816                        int allow_missing)
817 {
818         struct strbuf buf = STRBUF_INIT;
819         struct string_list kv = STRING_LIST_INIT_DUP;
820         int retval = -1; /* assume failure */
821         int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
822
823         if (strbuf_read_file(&buf, path, 256) <= 0) {
824                 strbuf_release(&buf);
825                 if (errno == ENOENT && allow_missing)
826                         return 0;
827                 else
828                         return error_errno(_("could not open '%s' for reading"),
829                                            path);
830         }
831
832         if (parse_key_value_squoted(buf.buf, &kv))
833                 goto finish;
834
835         for (i = 0; i < kv.nr; i++) {
836                 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
837                         if (name_i != -2)
838                                 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
839                         else
840                                 name_i = i;
841                 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
842                         if (email_i != -2)
843                                 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
844                         else
845                                 email_i = i;
846                 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
847                         if (date_i != -2)
848                                 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
849                         else
850                                 date_i = i;
851                 } else {
852                         err = error(_("unknown variable '%s'"),
853                                     kv.items[i].string);
854                 }
855         }
856         if (name_i == -2)
857                 error(_("missing 'GIT_AUTHOR_NAME'"));
858         if (email_i == -2)
859                 error(_("missing 'GIT_AUTHOR_EMAIL'"));
860         if (date_i == -2)
861                 error(_("missing 'GIT_AUTHOR_DATE'"));
862         if (date_i < 0 || email_i < 0 || date_i < 0 || err)
863                 goto finish;
864         *name = kv.items[name_i].util;
865         *email = kv.items[email_i].util;
866         *date = kv.items[date_i].util;
867         retval = 0;
868 finish:
869         string_list_clear(&kv, !!retval);
870         strbuf_release(&buf);
871         return retval;
872 }
873
874 /*
875  * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
876  * file with shell quoting into struct strvec. Returns -1 on
877  * error, 0 otherwise.
878  */
879 static int read_env_script(struct strvec *env)
880 {
881         char *name, *email, *date;
882
883         if (read_author_script(rebase_path_author_script(),
884                                &name, &email, &date, 0))
885                 return -1;
886
887         strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
888         strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
889         strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
890         free(name);
891         free(email);
892         free(date);
893
894         return 0;
895 }
896
897 static char *get_author(const char *message)
898 {
899         size_t len;
900         const char *a;
901
902         a = find_commit_header(message, "author", &len);
903         if (a)
904                 return xmemdupz(a, len);
905
906         return NULL;
907 }
908
909 static const char *author_date_from_env_array(const struct strvec *env)
910 {
911         int i;
912         const char *date;
913
914         for (i = 0; i < env->nr; i++)
915                 if (skip_prefix(env->v[i],
916                                 "GIT_AUTHOR_DATE=", &date))
917                         return date;
918         /*
919          * If GIT_AUTHOR_DATE is missing we should have already errored out when
920          * reading the script
921          */
922         BUG("GIT_AUTHOR_DATE missing from author script");
923 }
924
925 static const char staged_changes_advice[] =
926 N_("you have staged changes in your working tree\n"
927 "If these changes are meant to be squashed into the previous commit, run:\n"
928 "\n"
929 "  git commit --amend %s\n"
930 "\n"
931 "If they are meant to go into a new commit, run:\n"
932 "\n"
933 "  git commit %s\n"
934 "\n"
935 "In both cases, once you're done, continue with:\n"
936 "\n"
937 "  git rebase --continue\n");
938
939 #define ALLOW_EMPTY (1<<0)
940 #define EDIT_MSG    (1<<1)
941 #define AMEND_MSG   (1<<2)
942 #define CLEANUP_MSG (1<<3)
943 #define VERIFY_MSG  (1<<4)
944 #define CREATE_ROOT_COMMIT (1<<5)
945 #define VERBATIM_MSG (1<<6)
946
947 static int run_command_silent_on_success(struct child_process *cmd)
948 {
949         struct strbuf buf = STRBUF_INIT;
950         int rc;
951
952         cmd->stdout_to_stderr = 1;
953         rc = pipe_command(cmd,
954                           NULL, 0,
955                           NULL, 0,
956                           &buf, 0);
957
958         if (rc)
959                 fputs(buf.buf, stderr);
960         strbuf_release(&buf);
961         return rc;
962 }
963
964 /*
965  * If we are cherry-pick, and if the merge did not result in
966  * hand-editing, we will hit this commit and inherit the original
967  * author date and name.
968  *
969  * If we are revert, or if our cherry-pick results in a hand merge,
970  * we had better say that the current user is responsible for that.
971  *
972  * An exception is when run_git_commit() is called during an
973  * interactive rebase: in that case, we will want to retain the
974  * author metadata.
975  */
976 static int run_git_commit(const char *defmsg,
977                           struct replay_opts *opts,
978                           unsigned int flags)
979 {
980         struct child_process cmd = CHILD_PROCESS_INIT;
981
982         if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
983                 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
984
985         cmd.git_cmd = 1;
986
987         if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
988                 const char *gpg_opt = gpg_sign_opt_quoted(opts);
989
990                 return error(_(staged_changes_advice),
991                              gpg_opt, gpg_opt);
992         }
993
994         if (opts->committer_date_is_author_date)
995                 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
996                              opts->ignore_date ?
997                              "" :
998                              author_date_from_env_array(&cmd.env_array));
999         if (opts->ignore_date)
1000                 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
1001
1002         strvec_push(&cmd.args, "commit");
1003
1004         if (!(flags & VERIFY_MSG))
1005                 strvec_push(&cmd.args, "-n");
1006         if ((flags & AMEND_MSG))
1007                 strvec_push(&cmd.args, "--amend");
1008         if (opts->gpg_sign)
1009                 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1010         else
1011                 strvec_push(&cmd.args, "--no-gpg-sign");
1012         if (defmsg)
1013                 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1014         else if (!(flags & EDIT_MSG))
1015                 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1016         if ((flags & CLEANUP_MSG))
1017                 strvec_push(&cmd.args, "--cleanup=strip");
1018         if ((flags & VERBATIM_MSG))
1019                 strvec_push(&cmd.args, "--cleanup=verbatim");
1020         if ((flags & EDIT_MSG))
1021                 strvec_push(&cmd.args, "-e");
1022         else if (!(flags & CLEANUP_MSG) &&
1023                  !opts->signoff && !opts->record_origin &&
1024                  !opts->explicit_cleanup)
1025                 strvec_push(&cmd.args, "--cleanup=verbatim");
1026
1027         if ((flags & ALLOW_EMPTY))
1028                 strvec_push(&cmd.args, "--allow-empty");
1029
1030         if (!(flags & EDIT_MSG))
1031                 strvec_push(&cmd.args, "--allow-empty-message");
1032
1033         if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1034                 return run_command_silent_on_success(&cmd);
1035         else
1036                 return run_command(&cmd);
1037 }
1038
1039 static int rest_is_empty(const struct strbuf *sb, int start)
1040 {
1041         int i, eol;
1042         const char *nl;
1043
1044         /* Check if the rest is just whitespace and Signed-off-by's. */
1045         for (i = start; i < sb->len; i++) {
1046                 nl = memchr(sb->buf + i, '\n', sb->len - i);
1047                 if (nl)
1048                         eol = nl - sb->buf;
1049                 else
1050                         eol = sb->len;
1051
1052                 if (strlen(sign_off_header) <= eol - i &&
1053                     starts_with(sb->buf + i, sign_off_header)) {
1054                         i = eol;
1055                         continue;
1056                 }
1057                 while (i < eol)
1058                         if (!isspace(sb->buf[i++]))
1059                                 return 0;
1060         }
1061
1062         return 1;
1063 }
1064
1065 void cleanup_message(struct strbuf *msgbuf,
1066         enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1067 {
1068         if (verbose || /* Truncate the message just before the diff, if any. */
1069             cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1070                 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1071         if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1072                 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1073 }
1074
1075 /*
1076  * Find out if the message in the strbuf contains only whitespace and
1077  * Signed-off-by lines.
1078  */
1079 int message_is_empty(const struct strbuf *sb,
1080                      enum commit_msg_cleanup_mode cleanup_mode)
1081 {
1082         if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1083                 return 0;
1084         return rest_is_empty(sb, 0);
1085 }
1086
1087 /*
1088  * See if the user edited the message in the editor or left what
1089  * was in the template intact
1090  */
1091 int template_untouched(const struct strbuf *sb, const char *template_file,
1092                        enum commit_msg_cleanup_mode cleanup_mode)
1093 {
1094         struct strbuf tmpl = STRBUF_INIT;
1095         const char *start;
1096
1097         if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1098                 return 0;
1099
1100         if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1101                 return 0;
1102
1103         strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1104         if (!skip_prefix(sb->buf, tmpl.buf, &start))
1105                 start = sb->buf;
1106         strbuf_release(&tmpl);
1107         return rest_is_empty(sb, start - sb->buf);
1108 }
1109
1110 int update_head_with_reflog(const struct commit *old_head,
1111                             const struct object_id *new_head,
1112                             const char *action, const struct strbuf *msg,
1113                             struct strbuf *err)
1114 {
1115         struct ref_transaction *transaction;
1116         struct strbuf sb = STRBUF_INIT;
1117         const char *nl;
1118         int ret = 0;
1119
1120         if (action) {
1121                 strbuf_addstr(&sb, action);
1122                 strbuf_addstr(&sb, ": ");
1123         }
1124
1125         nl = strchr(msg->buf, '\n');
1126         if (nl) {
1127                 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1128         } else {
1129                 strbuf_addbuf(&sb, msg);
1130                 strbuf_addch(&sb, '\n');
1131         }
1132
1133         transaction = ref_transaction_begin(err);
1134         if (!transaction ||
1135             ref_transaction_update(transaction, "HEAD", new_head,
1136                                    old_head ? &old_head->object.oid : null_oid(),
1137                                    0, sb.buf, err) ||
1138             ref_transaction_commit(transaction, err)) {
1139                 ret = -1;
1140         }
1141         ref_transaction_free(transaction);
1142         strbuf_release(&sb);
1143
1144         return ret;
1145 }
1146
1147 static int run_rewrite_hook(const struct object_id *oldoid,
1148                             const struct object_id *newoid)
1149 {
1150         struct child_process proc = CHILD_PROCESS_INIT;
1151         const char *argv[3];
1152         int code;
1153         struct strbuf sb = STRBUF_INIT;
1154
1155         argv[0] = find_hook("post-rewrite");
1156         if (!argv[0])
1157                 return 0;
1158
1159         argv[1] = "amend";
1160         argv[2] = NULL;
1161
1162         proc.argv = argv;
1163         proc.in = -1;
1164         proc.stdout_to_stderr = 1;
1165         proc.trace2_hook_name = "post-rewrite";
1166
1167         code = start_command(&proc);
1168         if (code)
1169                 return code;
1170         strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1171         sigchain_push(SIGPIPE, SIG_IGN);
1172         write_in_full(proc.in, sb.buf, sb.len);
1173         close(proc.in);
1174         strbuf_release(&sb);
1175         sigchain_pop(SIGPIPE);
1176         return finish_command(&proc);
1177 }
1178
1179 void commit_post_rewrite(struct repository *r,
1180                          const struct commit *old_head,
1181                          const struct object_id *new_head)
1182 {
1183         struct notes_rewrite_cfg *cfg;
1184
1185         cfg = init_copy_notes_for_rewrite("amend");
1186         if (cfg) {
1187                 /* we are amending, so old_head is not NULL */
1188                 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1189                 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1190         }
1191         run_rewrite_hook(&old_head->object.oid, new_head);
1192 }
1193
1194 static int run_prepare_commit_msg_hook(struct repository *r,
1195                                        struct strbuf *msg,
1196                                        const char *commit)
1197 {
1198         int ret = 0;
1199         const char *name, *arg1 = NULL, *arg2 = NULL;
1200
1201         name = git_path_commit_editmsg();
1202         if (write_message(msg->buf, msg->len, name, 0))
1203                 return -1;
1204
1205         if (commit) {
1206                 arg1 = "commit";
1207                 arg2 = commit;
1208         } else {
1209                 arg1 = "message";
1210         }
1211         if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1212                             arg1, arg2, NULL))
1213                 ret = error(_("'prepare-commit-msg' hook failed"));
1214
1215         return ret;
1216 }
1217
1218 static const char implicit_ident_advice_noconfig[] =
1219 N_("Your name and email address were configured automatically based\n"
1220 "on your username and hostname. Please check that they are accurate.\n"
1221 "You can suppress this message by setting them explicitly. Run the\n"
1222 "following command and follow the instructions in your editor to edit\n"
1223 "your configuration file:\n"
1224 "\n"
1225 "    git config --global --edit\n"
1226 "\n"
1227 "After doing this, you may fix the identity used for this commit with:\n"
1228 "\n"
1229 "    git commit --amend --reset-author\n");
1230
1231 static const char implicit_ident_advice_config[] =
1232 N_("Your name and email address were configured automatically based\n"
1233 "on your username and hostname. Please check that they are accurate.\n"
1234 "You can suppress this message by setting them explicitly:\n"
1235 "\n"
1236 "    git config --global user.name \"Your Name\"\n"
1237 "    git config --global user.email you@example.com\n"
1238 "\n"
1239 "After doing this, you may fix the identity used for this commit with:\n"
1240 "\n"
1241 "    git commit --amend --reset-author\n");
1242
1243 static const char *implicit_ident_advice(void)
1244 {
1245         char *user_config = expand_user_path("~/.gitconfig", 0);
1246         char *xdg_config = xdg_config_home("config");
1247         int config_exists = file_exists(user_config) || file_exists(xdg_config);
1248
1249         free(user_config);
1250         free(xdg_config);
1251
1252         if (config_exists)
1253                 return _(implicit_ident_advice_config);
1254         else
1255                 return _(implicit_ident_advice_noconfig);
1256
1257 }
1258
1259 void print_commit_summary(struct repository *r,
1260                           const char *prefix,
1261                           const struct object_id *oid,
1262                           unsigned int flags)
1263 {
1264         struct rev_info rev;
1265         struct commit *commit;
1266         struct strbuf format = STRBUF_INIT;
1267         const char *head;
1268         struct pretty_print_context pctx = {0};
1269         struct strbuf author_ident = STRBUF_INIT;
1270         struct strbuf committer_ident = STRBUF_INIT;
1271
1272         commit = lookup_commit(r, oid);
1273         if (!commit)
1274                 die(_("couldn't look up newly created commit"));
1275         if (parse_commit(commit))
1276                 die(_("could not parse newly created commit"));
1277
1278         strbuf_addstr(&format, "format:%h] %s");
1279
1280         format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1281         format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1282         if (strbuf_cmp(&author_ident, &committer_ident)) {
1283                 strbuf_addstr(&format, "\n Author: ");
1284                 strbuf_addbuf_percentquote(&format, &author_ident);
1285         }
1286         if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1287                 struct strbuf date = STRBUF_INIT;
1288
1289                 format_commit_message(commit, "%ad", &date, &pctx);
1290                 strbuf_addstr(&format, "\n Date: ");
1291                 strbuf_addbuf_percentquote(&format, &date);
1292                 strbuf_release(&date);
1293         }
1294         if (!committer_ident_sufficiently_given()) {
1295                 strbuf_addstr(&format, "\n Committer: ");
1296                 strbuf_addbuf_percentquote(&format, &committer_ident);
1297                 if (advice_implicit_identity) {
1298                         strbuf_addch(&format, '\n');
1299                         strbuf_addstr(&format, implicit_ident_advice());
1300                 }
1301         }
1302         strbuf_release(&author_ident);
1303         strbuf_release(&committer_ident);
1304
1305         repo_init_revisions(r, &rev, prefix);
1306         setup_revisions(0, NULL, &rev, NULL);
1307
1308         rev.diff = 1;
1309         rev.diffopt.output_format =
1310                 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1311
1312         rev.verbose_header = 1;
1313         rev.show_root_diff = 1;
1314         get_commit_format(format.buf, &rev);
1315         rev.always_show_header = 0;
1316         rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1317         rev.diffopt.break_opt = 0;
1318         diff_setup_done(&rev.diffopt);
1319
1320         head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1321         if (!head)
1322                 die_errno(_("unable to resolve HEAD after creating commit"));
1323         if (!strcmp(head, "HEAD"))
1324                 head = _("detached HEAD");
1325         else
1326                 skip_prefix(head, "refs/heads/", &head);
1327         printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1328                                                 _(" (root-commit)") : "");
1329
1330         if (!log_tree_commit(&rev, commit)) {
1331                 rev.always_show_header = 1;
1332                 rev.use_terminator = 1;
1333                 log_tree_commit(&rev, commit);
1334         }
1335
1336         strbuf_release(&format);
1337 }
1338
1339 static int parse_head(struct repository *r, struct commit **head)
1340 {
1341         struct commit *current_head;
1342         struct object_id oid;
1343
1344         if (get_oid("HEAD", &oid)) {
1345                 current_head = NULL;
1346         } else {
1347                 current_head = lookup_commit_reference(r, &oid);
1348                 if (!current_head)
1349                         return error(_("could not parse HEAD"));
1350                 if (!oideq(&oid, &current_head->object.oid)) {
1351                         warning(_("HEAD %s is not a commit!"),
1352                                 oid_to_hex(&oid));
1353                 }
1354                 if (parse_commit(current_head))
1355                         return error(_("could not parse HEAD commit"));
1356         }
1357         *head = current_head;
1358
1359         return 0;
1360 }
1361
1362 /*
1363  * Try to commit without forking 'git commit'. In some cases we need
1364  * to run 'git commit' to display an error message
1365  *
1366  * Returns:
1367  *  -1 - error unable to commit
1368  *   0 - success
1369  *   1 - run 'git commit'
1370  */
1371 static int try_to_commit(struct repository *r,
1372                          struct strbuf *msg, const char *author,
1373                          struct replay_opts *opts, unsigned int flags,
1374                          struct object_id *oid)
1375 {
1376         struct object_id tree;
1377         struct commit *current_head = NULL;
1378         struct commit_list *parents = NULL;
1379         struct commit_extra_header *extra = NULL;
1380         struct strbuf err = STRBUF_INIT;
1381         struct strbuf commit_msg = STRBUF_INIT;
1382         char *amend_author = NULL;
1383         const char *committer = NULL;
1384         const char *hook_commit = NULL;
1385         enum commit_msg_cleanup_mode cleanup;
1386         int res = 0;
1387
1388         if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1389                 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1390
1391         if (parse_head(r, &current_head))
1392                 return -1;
1393
1394         if (flags & AMEND_MSG) {
1395                 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1396                 const char *out_enc = get_commit_output_encoding();
1397                 const char *message = logmsg_reencode(current_head, NULL,
1398                                                       out_enc);
1399
1400                 if (!msg) {
1401                         const char *orig_message = NULL;
1402
1403                         find_commit_subject(message, &orig_message);
1404                         msg = &commit_msg;
1405                         strbuf_addstr(msg, orig_message);
1406                         hook_commit = "HEAD";
1407                 }
1408                 author = amend_author = get_author(message);
1409                 unuse_commit_buffer(current_head, message);
1410                 if (!author) {
1411                         res = error(_("unable to parse commit author"));
1412                         goto out;
1413                 }
1414                 parents = copy_commit_list(current_head->parents);
1415                 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1416         } else if (current_head &&
1417                    (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1418                 commit_list_insert(current_head, &parents);
1419         }
1420
1421         if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1422                 res = error(_("git write-tree failed to write a tree"));
1423                 goto out;
1424         }
1425
1426         if (!(flags & ALLOW_EMPTY)) {
1427                 struct commit *first_parent = current_head;
1428
1429                 if (flags & AMEND_MSG) {
1430                         if (current_head->parents) {
1431                                 first_parent = current_head->parents->item;
1432                                 if (repo_parse_commit(r, first_parent)) {
1433                                         res = error(_("could not parse HEAD commit"));
1434                                         goto out;
1435                                 }
1436                         } else {
1437                                 first_parent = NULL;
1438                         }
1439                 }
1440                 if (oideq(first_parent
1441                           ? get_commit_tree_oid(first_parent)
1442                           : the_hash_algo->empty_tree,
1443                           &tree)) {
1444                         res = 1; /* run 'git commit' to display error message */
1445                         goto out;
1446                 }
1447         }
1448
1449         if (hook_exists("prepare-commit-msg")) {
1450                 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1451                 if (res)
1452                         goto out;
1453                 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1454                                      2048) < 0) {
1455                         res = error_errno(_("unable to read commit message "
1456                                               "from '%s'"),
1457                                             git_path_commit_editmsg());
1458                         goto out;
1459                 }
1460                 msg = &commit_msg;
1461         }
1462
1463         if (flags & CLEANUP_MSG)
1464                 cleanup = COMMIT_MSG_CLEANUP_ALL;
1465         else if (flags & VERBATIM_MSG)
1466                 cleanup = COMMIT_MSG_CLEANUP_NONE;
1467         else if ((opts->signoff || opts->record_origin) &&
1468                  !opts->explicit_cleanup)
1469                 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1470         else
1471                 cleanup = opts->default_msg_cleanup;
1472
1473         if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1474                 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1475         if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1476                 res = 1; /* run 'git commit' to display error message */
1477                 goto out;
1478         }
1479
1480         if (opts->committer_date_is_author_date) {
1481                 struct ident_split id;
1482                 struct strbuf date = STRBUF_INIT;
1483
1484                 if (!opts->ignore_date) {
1485                         if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1486                                 res = error(_("invalid author identity '%s'"),
1487                                             author);
1488                                 goto out;
1489                         }
1490                         if (!id.date_begin) {
1491                                 res = error(_(
1492                                         "corrupt author: missing date information"));
1493                                 goto out;
1494                         }
1495                         strbuf_addf(&date, "@%.*s %.*s",
1496                                     (int)(id.date_end - id.date_begin),
1497                                     id.date_begin,
1498                                     (int)(id.tz_end - id.tz_begin),
1499                                     id.tz_begin);
1500                 } else {
1501                         reset_ident_date();
1502                 }
1503                 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1504                                       getenv("GIT_COMMITTER_EMAIL"),
1505                                       WANT_COMMITTER_IDENT,
1506                                       opts->ignore_date ? NULL : date.buf,
1507                                       IDENT_STRICT);
1508                 strbuf_release(&date);
1509         } else {
1510                 reset_ident_date();
1511         }
1512
1513         if (opts->ignore_date) {
1514                 struct ident_split id;
1515                 char *name, *email;
1516
1517                 if (split_ident_line(&id, author, strlen(author)) < 0) {
1518                         error(_("invalid author identity '%s'"), author);
1519                         goto out;
1520                 }
1521                 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1522                 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1523                 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1524                                    IDENT_STRICT);
1525                 free(name);
1526                 free(email);
1527         }
1528
1529         if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1530                                  author, committer, opts->gpg_sign, extra)) {
1531                 res = error(_("failed to write commit object"));
1532                 goto out;
1533         }
1534
1535         if (update_head_with_reflog(current_head, oid,
1536                                     getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1537                 res = error("%s", err.buf);
1538                 goto out;
1539         }
1540
1541         run_commit_hook(0, r->index_file, "post-commit", NULL);
1542         if (flags & AMEND_MSG)
1543                 commit_post_rewrite(r, current_head, oid);
1544
1545 out:
1546         free_commit_extra_headers(extra);
1547         strbuf_release(&err);
1548         strbuf_release(&commit_msg);
1549         free(amend_author);
1550
1551         return res;
1552 }
1553
1554 static int write_rebase_head(struct object_id *oid)
1555 {
1556         if (update_ref("rebase", "REBASE_HEAD", oid,
1557                        NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1558                 return error(_("could not update %s"), "REBASE_HEAD");
1559
1560         return 0;
1561 }
1562
1563 static int do_commit(struct repository *r,
1564                      const char *msg_file, const char *author,
1565                      struct replay_opts *opts, unsigned int flags,
1566                      struct object_id *oid)
1567 {
1568         int res = 1;
1569
1570         if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1571                 struct object_id oid;
1572                 struct strbuf sb = STRBUF_INIT;
1573
1574                 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1575                         return error_errno(_("unable to read commit message "
1576                                              "from '%s'"),
1577                                            msg_file);
1578
1579                 res = try_to_commit(r, msg_file ? &sb : NULL,
1580                                     author, opts, flags, &oid);
1581                 strbuf_release(&sb);
1582                 if (!res) {
1583                         refs_delete_ref(get_main_ref_store(r), "",
1584                                         "CHERRY_PICK_HEAD", NULL, 0);
1585                         unlink(git_path_merge_msg(r));
1586                         if (!is_rebase_i(opts))
1587                                 print_commit_summary(r, NULL, &oid,
1588                                                 SUMMARY_SHOW_AUTHOR_DATE);
1589                         return res;
1590                 }
1591         }
1592         if (res == 1) {
1593                 if (is_rebase_i(opts) && oid)
1594                         if (write_rebase_head(oid))
1595                             return -1;
1596                 return run_git_commit(msg_file, opts, flags);
1597         }
1598
1599         return res;
1600 }
1601
1602 static int is_original_commit_empty(struct commit *commit)
1603 {
1604         const struct object_id *ptree_oid;
1605
1606         if (parse_commit(commit))
1607                 return error(_("could not parse commit %s"),
1608                              oid_to_hex(&commit->object.oid));
1609         if (commit->parents) {
1610                 struct commit *parent = commit->parents->item;
1611                 if (parse_commit(parent))
1612                         return error(_("could not parse parent commit %s"),
1613                                 oid_to_hex(&parent->object.oid));
1614                 ptree_oid = get_commit_tree_oid(parent);
1615         } else {
1616                 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1617         }
1618
1619         return oideq(ptree_oid, get_commit_tree_oid(commit));
1620 }
1621
1622 /*
1623  * Should empty commits be allowed?  Return status:
1624  *    <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1625  *     0: Halt on empty commit
1626  *     1: Allow empty commit
1627  *     2: Drop empty commit
1628  */
1629 static int allow_empty(struct repository *r,
1630                        struct replay_opts *opts,
1631                        struct commit *commit)
1632 {
1633         int index_unchanged, originally_empty;
1634
1635         /*
1636          * Four cases:
1637          *
1638          * (1) we do not allow empty at all and error out.
1639          *
1640          * (2) we allow ones that were initially empty, and
1641          *     just drop the ones that become empty
1642          *
1643          * (3) we allow ones that were initially empty, but
1644          *     halt for the ones that become empty;
1645          *
1646          * (4) we allow both.
1647          */
1648         if (!opts->allow_empty)
1649                 return 0; /* let "git commit" barf as necessary */
1650
1651         index_unchanged = is_index_unchanged(r);
1652         if (index_unchanged < 0)
1653                 return index_unchanged;
1654         if (!index_unchanged)
1655                 return 0; /* we do not have to say --allow-empty */
1656
1657         if (opts->keep_redundant_commits)
1658                 return 1;
1659
1660         originally_empty = is_original_commit_empty(commit);
1661         if (originally_empty < 0)
1662                 return originally_empty;
1663         if (originally_empty)
1664                 return 1;
1665         else if (opts->drop_redundant_commits)
1666                 return 2;
1667         else
1668                 return 0;
1669 }
1670
1671 static struct {
1672         char c;
1673         const char *str;
1674 } todo_command_info[] = {
1675         { 'p', "pick" },
1676         { 0,   "revert" },
1677         { 'e', "edit" },
1678         { 'r', "reword" },
1679         { 'f', "fixup" },
1680         { 's', "squash" },
1681         { 'x', "exec" },
1682         { 'b', "break" },
1683         { 'l', "label" },
1684         { 't', "reset" },
1685         { 'm', "merge" },
1686         { 0,   "noop" },
1687         { 'd', "drop" },
1688         { 0,   NULL }
1689 };
1690
1691 static const char *command_to_string(const enum todo_command command)
1692 {
1693         if (command < TODO_COMMENT)
1694                 return todo_command_info[command].str;
1695         die(_("unknown command: %d"), command);
1696 }
1697
1698 static char command_to_char(const enum todo_command command)
1699 {
1700         if (command < TODO_COMMENT)
1701                 return todo_command_info[command].c;
1702         return comment_line_char;
1703 }
1704
1705 static int is_noop(const enum todo_command command)
1706 {
1707         return TODO_NOOP <= command;
1708 }
1709
1710 static int is_fixup(enum todo_command command)
1711 {
1712         return command == TODO_FIXUP || command == TODO_SQUASH;
1713 }
1714
1715 /* Does this command create a (non-merge) commit? */
1716 static int is_pick_or_similar(enum todo_command command)
1717 {
1718         switch (command) {
1719         case TODO_PICK:
1720         case TODO_REVERT:
1721         case TODO_EDIT:
1722         case TODO_REWORD:
1723         case TODO_FIXUP:
1724         case TODO_SQUASH:
1725                 return 1;
1726         default:
1727                 return 0;
1728         }
1729 }
1730
1731 enum todo_item_flags {
1732         TODO_EDIT_MERGE_MSG    = (1 << 0),
1733         TODO_REPLACE_FIXUP_MSG = (1 << 1),
1734         TODO_EDIT_FIXUP_MSG    = (1 << 2),
1735 };
1736
1737 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1738 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1739 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1740 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1741 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1742
1743 static int is_fixup_flag(enum todo_command command, unsigned flag)
1744 {
1745         return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1746                                          (flag & TODO_EDIT_FIXUP_MSG));
1747 }
1748
1749 /*
1750  * Wrapper around strbuf_add_commented_lines() which avoids double
1751  * commenting commit subjects.
1752  */
1753 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1754 {
1755         const char *s = str;
1756         while (len > 0 && s[0] == comment_line_char) {
1757                 size_t count;
1758                 const char *n = memchr(s, '\n', len);
1759                 if (!n)
1760                         count = len;
1761                 else
1762                         count = n - s + 1;
1763                 strbuf_add(buf, s, count);
1764                 s += count;
1765                 len -= count;
1766         }
1767         strbuf_add_commented_lines(buf, s, len);
1768 }
1769
1770 /* Does the current fixup chain contain a squash command? */
1771 static int seen_squash(struct replay_opts *opts)
1772 {
1773         return starts_with(opts->current_fixups.buf, "squash") ||
1774                 strstr(opts->current_fixups.buf, "\nsquash");
1775 }
1776
1777 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1778 {
1779         strbuf_setlen(buf1, 2);
1780         strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1781         strbuf_addch(buf1, '\n');
1782         strbuf_setlen(buf2, 2);
1783         strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1784         strbuf_addch(buf2, '\n');
1785 }
1786
1787 /*
1788  * Comment out any un-commented commit messages, updating the message comments
1789  * to say they will be skipped but do not comment out the empty lines that
1790  * surround commit messages and their comments.
1791  */
1792 static void update_squash_message_for_fixup(struct strbuf *msg)
1793 {
1794         void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1795         struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1796         const char *s, *start;
1797         char *orig_msg;
1798         size_t orig_msg_len;
1799         int i = 1;
1800
1801         strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1802         strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1803         s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1804         while (s) {
1805                 const char *next;
1806                 size_t off;
1807                 if (skip_prefix(s, buf1.buf, &next)) {
1808                         /*
1809                          * Copy the last message, preserving the blank line
1810                          * preceding the current line
1811                          */
1812                         off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1813                         copy_lines(msg, start, s - start - off);
1814                         if (off)
1815                                 strbuf_addch(msg, '\n');
1816                         /*
1817                          * The next message needs to be commented out but the
1818                          * message header is already commented out so just copy
1819                          * it and the blank line that follows it.
1820                          */
1821                         strbuf_addbuf(msg, &buf2);
1822                         if (*next == '\n')
1823                                 strbuf_addch(msg, *next++);
1824                         start = s = next;
1825                         copy_lines = add_commented_lines;
1826                         update_comment_bufs(&buf1, &buf2, ++i);
1827                 } else if (skip_prefix(s, buf2.buf, &next)) {
1828                         off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1829                         copy_lines(msg, start, s - start - off);
1830                         start = s - off;
1831                         s = next;
1832                         copy_lines = strbuf_add;
1833                         update_comment_bufs(&buf1, &buf2, ++i);
1834                 } else {
1835                         s = strchr(s, '\n');
1836                         if (s)
1837                                 s++;
1838                 }
1839         }
1840         copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1841         free(orig_msg);
1842         strbuf_release(&buf1);
1843         strbuf_release(&buf2);
1844 }
1845
1846 static int append_squash_message(struct strbuf *buf, const char *body,
1847                          enum todo_command command, struct replay_opts *opts,
1848                          unsigned flag)
1849 {
1850         const char *fixup_msg;
1851         size_t commented_len = 0, fixup_off;
1852         /*
1853          * amend is non-interactive and not normally used with fixup!
1854          * or squash! commits, so only comment out those subjects when
1855          * squashing commit messages.
1856          */
1857         if (starts_with(body, "amend!") ||
1858             ((command == TODO_SQUASH || seen_squash(opts)) &&
1859              (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1860                 commented_len = commit_subject_length(body);
1861
1862         strbuf_addf(buf, "\n%c ", comment_line_char);
1863         strbuf_addf(buf, _(nth_commit_msg_fmt),
1864                     ++opts->current_fixup_count + 1);
1865         strbuf_addstr(buf, "\n\n");
1866         strbuf_add_commented_lines(buf, body, commented_len);
1867         /* buf->buf may be reallocated so store an offset into the buffer */
1868         fixup_off = buf->len;
1869         strbuf_addstr(buf, body + commented_len);
1870
1871         /* fixup -C after squash behaves like squash */
1872         if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1873                 /*
1874                  * We're replacing the commit message so we need to
1875                  * append the Signed-off-by: trailer if the user
1876                  * requested '--signoff'.
1877                  */
1878                 if (opts->signoff)
1879                         append_signoff(buf, 0, 0);
1880
1881                 if ((command == TODO_FIXUP) &&
1882                     (flag & TODO_REPLACE_FIXUP_MSG) &&
1883                     (file_exists(rebase_path_fixup_msg()) ||
1884                      !file_exists(rebase_path_squash_msg()))) {
1885                         fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1886                         if (write_message(fixup_msg, strlen(fixup_msg),
1887                                         rebase_path_fixup_msg(), 0) < 0)
1888                                 return error(_("cannot write '%s'"),
1889                                         rebase_path_fixup_msg());
1890                 } else {
1891                         unlink(rebase_path_fixup_msg());
1892                 }
1893         } else  {
1894                 unlink(rebase_path_fixup_msg());
1895         }
1896
1897         return 0;
1898 }
1899
1900 static int update_squash_messages(struct repository *r,
1901                                   enum todo_command command,
1902                                   struct commit *commit,
1903                                   struct replay_opts *opts,
1904                                   unsigned flag)
1905 {
1906         struct strbuf buf = STRBUF_INIT;
1907         int res = 0;
1908         const char *message, *body;
1909         const char *encoding = get_commit_output_encoding();
1910
1911         if (opts->current_fixup_count > 0) {
1912                 struct strbuf header = STRBUF_INIT;
1913                 char *eol;
1914
1915                 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1916                         return error(_("could not read '%s'"),
1917                                 rebase_path_squash_msg());
1918
1919                 eol = buf.buf[0] != comment_line_char ?
1920                         buf.buf : strchrnul(buf.buf, '\n');
1921
1922                 strbuf_addf(&header, "%c ", comment_line_char);
1923                 strbuf_addf(&header, _(combined_commit_msg_fmt),
1924                             opts->current_fixup_count + 2);
1925                 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1926                 strbuf_release(&header);
1927                 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1928                         update_squash_message_for_fixup(&buf);
1929         } else {
1930                 struct object_id head;
1931                 struct commit *head_commit;
1932                 const char *head_message, *body;
1933
1934                 if (get_oid("HEAD", &head))
1935                         return error(_("need a HEAD to fixup"));
1936                 if (!(head_commit = lookup_commit_reference(r, &head)))
1937                         return error(_("could not read HEAD"));
1938                 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1939                         return error(_("could not read HEAD's commit message"));
1940
1941                 find_commit_subject(head_message, &body);
1942                 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1943                                                         rebase_path_fixup_msg(), 0) < 0) {
1944                         unuse_commit_buffer(head_commit, head_message);
1945                         return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1946                 }
1947                 strbuf_addf(&buf, "%c ", comment_line_char);
1948                 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1949                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1950                 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1951                               _(skip_first_commit_msg_str) :
1952                               _(first_commit_msg_str));
1953                 strbuf_addstr(&buf, "\n\n");
1954                 if (is_fixup_flag(command, flag))
1955                         strbuf_add_commented_lines(&buf, body, strlen(body));
1956                 else
1957                         strbuf_addstr(&buf, body);
1958
1959                 unuse_commit_buffer(head_commit, head_message);
1960         }
1961
1962         if (!(message = logmsg_reencode(commit, NULL, encoding)))
1963                 return error(_("could not read commit message of %s"),
1964                              oid_to_hex(&commit->object.oid));
1965         find_commit_subject(message, &body);
1966
1967         if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1968                 res = append_squash_message(&buf, body, command, opts, flag);
1969         } else if (command == TODO_FIXUP) {
1970                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1971                 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1972                             ++opts->current_fixup_count + 1);
1973                 strbuf_addstr(&buf, "\n\n");
1974                 strbuf_add_commented_lines(&buf, body, strlen(body));
1975         } else
1976                 return error(_("unknown command: %d"), command);
1977         unuse_commit_buffer(commit, message);
1978
1979         if (!res)
1980                 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1981                                     0);
1982         strbuf_release(&buf);
1983
1984         if (!res) {
1985                 strbuf_addf(&opts->current_fixups, "%s%s %s",
1986                             opts->current_fixups.len ? "\n" : "",
1987                             command_to_string(command),
1988                             oid_to_hex(&commit->object.oid));
1989                 res = write_message(opts->current_fixups.buf,
1990                                     opts->current_fixups.len,
1991                                     rebase_path_current_fixups(), 0);
1992         }
1993
1994         return res;
1995 }
1996
1997 static void flush_rewritten_pending(void)
1998 {
1999         struct strbuf buf = STRBUF_INIT;
2000         struct object_id newoid;
2001         FILE *out;
2002
2003         if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2004             !get_oid("HEAD", &newoid) &&
2005             (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2006                 char *bol = buf.buf, *eol;
2007
2008                 while (*bol) {
2009                         eol = strchrnul(bol, '\n');
2010                         fprintf(out, "%.*s %s\n", (int)(eol - bol),
2011                                         bol, oid_to_hex(&newoid));
2012                         if (!*eol)
2013                                 break;
2014                         bol = eol + 1;
2015                 }
2016                 fclose(out);
2017                 unlink(rebase_path_rewritten_pending());
2018         }
2019         strbuf_release(&buf);
2020 }
2021
2022 static void record_in_rewritten(struct object_id *oid,
2023                 enum todo_command next_command)
2024 {
2025         FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2026
2027         if (!out)
2028                 return;
2029
2030         fprintf(out, "%s\n", oid_to_hex(oid));
2031         fclose(out);
2032
2033         if (!is_fixup(next_command))
2034                 flush_rewritten_pending();
2035 }
2036
2037 static int should_edit(struct replay_opts *opts) {
2038         if (opts->edit < 0)
2039                 /*
2040                  * Note that we only handle the case of non-conflicted
2041                  * commits; continue_single_pick() handles the conflicted
2042                  * commits itself instead of calling this function.
2043                  */
2044                 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2045         return opts->edit;
2046 }
2047
2048 static int do_pick_commit(struct repository *r,
2049                           struct todo_item *item,
2050                           struct replay_opts *opts,
2051                           int final_fixup, int *check_todo)
2052 {
2053         unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2054         const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2055         struct object_id head;
2056         struct commit *base, *next, *parent;
2057         const char *base_label, *next_label;
2058         char *author = NULL;
2059         struct commit_message msg = { NULL, NULL, NULL, NULL };
2060         struct strbuf msgbuf = STRBUF_INIT;
2061         int res, unborn = 0, reword = 0, allow, drop_commit;
2062         enum todo_command command = item->command;
2063         struct commit *commit = item->commit;
2064
2065         if (opts->no_commit) {
2066                 /*
2067                  * We do not intend to commit immediately.  We just want to
2068                  * merge the differences in, so let's compute the tree
2069                  * that represents the "current" state for merge-recursive
2070                  * to work on.
2071                  */
2072                 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2073                         return error(_("your index file is unmerged."));
2074         } else {
2075                 unborn = get_oid("HEAD", &head);
2076                 /* Do we want to generate a root commit? */
2077                 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2078                     oideq(&head, &opts->squash_onto)) {
2079                         if (is_fixup(command))
2080                                 return error(_("cannot fixup root commit"));
2081                         flags |= CREATE_ROOT_COMMIT;
2082                         unborn = 1;
2083                 } else if (unborn)
2084                         oidcpy(&head, the_hash_algo->empty_tree);
2085                 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2086                                        NULL, 0))
2087                         return error_dirty_index(r, opts);
2088         }
2089         discard_index(r->index);
2090
2091         if (!commit->parents)
2092                 parent = NULL;
2093         else if (commit->parents->next) {
2094                 /* Reverting or cherry-picking a merge commit */
2095                 int cnt;
2096                 struct commit_list *p;
2097
2098                 if (!opts->mainline)
2099                         return error(_("commit %s is a merge but no -m option was given."),
2100                                 oid_to_hex(&commit->object.oid));
2101
2102                 for (cnt = 1, p = commit->parents;
2103                      cnt != opts->mainline && p;
2104                      cnt++)
2105                         p = p->next;
2106                 if (cnt != opts->mainline || !p)
2107                         return error(_("commit %s does not have parent %d"),
2108                                 oid_to_hex(&commit->object.oid), opts->mainline);
2109                 parent = p->item;
2110         } else if (1 < opts->mainline)
2111                 /*
2112                  *  Non-first parent explicitly specified as mainline for
2113                  *  non-merge commit
2114                  */
2115                 return error(_("commit %s does not have parent %d"),
2116                              oid_to_hex(&commit->object.oid), opts->mainline);
2117         else
2118                 parent = commit->parents->item;
2119
2120         if (get_message(commit, &msg) != 0)
2121                 return error(_("cannot get commit message for %s"),
2122                         oid_to_hex(&commit->object.oid));
2123
2124         if (opts->allow_ff && !is_fixup(command) &&
2125             ((parent && oideq(&parent->object.oid, &head)) ||
2126              (!parent && unborn))) {
2127                 if (is_rebase_i(opts))
2128                         write_author_script(msg.message);
2129                 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2130                         opts);
2131                 if (res || command != TODO_REWORD)
2132                         goto leave;
2133                 reword = 1;
2134                 msg_file = NULL;
2135                 goto fast_forward_edit;
2136         }
2137         if (parent && parse_commit(parent) < 0)
2138                 /* TRANSLATORS: The first %s will be a "todo" command like
2139                    "revert" or "pick", the second %s a SHA1. */
2140                 return error(_("%s: cannot parse parent commit %s"),
2141                         command_to_string(command),
2142                         oid_to_hex(&parent->object.oid));
2143
2144         /*
2145          * "commit" is an existing commit.  We would want to apply
2146          * the difference it introduces since its first parent "prev"
2147          * on top of the current HEAD if we are cherry-pick.  Or the
2148          * reverse of it if we are revert.
2149          */
2150
2151         if (command == TODO_REVERT) {
2152                 base = commit;
2153                 base_label = msg.label;
2154                 next = parent;
2155                 next_label = msg.parent_label;
2156                 strbuf_addstr(&msgbuf, "Revert \"");
2157                 strbuf_addstr(&msgbuf, msg.subject);
2158                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2159                 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2160
2161                 if (commit->parents && commit->parents->next) {
2162                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2163                         strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2164                 }
2165                 strbuf_addstr(&msgbuf, ".\n");
2166         } else {
2167                 const char *p;
2168
2169                 base = parent;
2170                 base_label = msg.parent_label;
2171                 next = commit;
2172                 next_label = msg.label;
2173
2174                 /* Append the commit log message to msgbuf. */
2175                 if (find_commit_subject(msg.message, &p))
2176                         strbuf_addstr(&msgbuf, p);
2177
2178                 if (opts->record_origin) {
2179                         strbuf_complete_line(&msgbuf);
2180                         if (!has_conforming_footer(&msgbuf, NULL, 0))
2181                                 strbuf_addch(&msgbuf, '\n');
2182                         strbuf_addstr(&msgbuf, cherry_picked_prefix);
2183                         strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2184                         strbuf_addstr(&msgbuf, ")\n");
2185                 }
2186                 if (!is_fixup(command))
2187                         author = get_author(msg.message);
2188         }
2189
2190         if (command == TODO_REWORD)
2191                 reword = 1;
2192         else if (is_fixup(command)) {
2193                 if (update_squash_messages(r, command, commit,
2194                                            opts, item->flags))
2195                         return -1;
2196                 flags |= AMEND_MSG;
2197                 if (!final_fixup)
2198                         msg_file = rebase_path_squash_msg();
2199                 else if (file_exists(rebase_path_fixup_msg())) {
2200                         flags |= VERBATIM_MSG;
2201                         msg_file = rebase_path_fixup_msg();
2202                 } else {
2203                         const char *dest = git_path_squash_msg(r);
2204                         unlink(dest);
2205                         if (copy_file(dest, rebase_path_squash_msg(), 0666))
2206                                 return error(_("could not rename '%s' to '%s'"),
2207                                              rebase_path_squash_msg(), dest);
2208                         unlink(git_path_merge_msg(r));
2209                         msg_file = dest;
2210                         flags |= EDIT_MSG;
2211                 }
2212         }
2213
2214         if (opts->signoff && !is_fixup(command))
2215                 append_signoff(&msgbuf, 0, 0);
2216
2217         if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2218                 res = -1;
2219         else if (!opts->strategy ||
2220                  !strcmp(opts->strategy, "recursive") ||
2221                  !strcmp(opts->strategy, "ort") ||
2222                  command == TODO_REVERT) {
2223                 res = do_recursive_merge(r, base, next, base_label, next_label,
2224                                          &head, &msgbuf, opts);
2225                 if (res < 0)
2226                         goto leave;
2227
2228                 res |= write_message(msgbuf.buf, msgbuf.len,
2229                                      git_path_merge_msg(r), 0);
2230         } else {
2231                 struct commit_list *common = NULL;
2232                 struct commit_list *remotes = NULL;
2233
2234                 res = write_message(msgbuf.buf, msgbuf.len,
2235                                     git_path_merge_msg(r), 0);
2236
2237                 commit_list_insert(base, &common);
2238                 commit_list_insert(next, &remotes);
2239                 res |= try_merge_command(r, opts->strategy,
2240                                          opts->xopts_nr, (const char **)opts->xopts,
2241                                         common, oid_to_hex(&head), remotes);
2242                 free_commit_list(common);
2243                 free_commit_list(remotes);
2244         }
2245         strbuf_release(&msgbuf);
2246
2247         /*
2248          * If the merge was clean or if it failed due to conflict, we write
2249          * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2250          * However, if the merge did not even start, then we don't want to
2251          * write it at all.
2252          */
2253         if ((command == TODO_PICK || command == TODO_REWORD ||
2254              command == TODO_EDIT) && !opts->no_commit &&
2255             (res == 0 || res == 1) &&
2256             update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2257                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2258                 res = -1;
2259         if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2260             update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2261                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2262                 res = -1;
2263
2264         if (res) {
2265                 error(command == TODO_REVERT
2266                       ? _("could not revert %s... %s")
2267                       : _("could not apply %s... %s"),
2268                       short_commit_name(commit), msg.subject);
2269                 print_advice(r, res == 1, opts);
2270                 repo_rerere(r, opts->allow_rerere_auto);
2271                 goto leave;
2272         }
2273
2274         drop_commit = 0;
2275         allow = allow_empty(r, opts, commit);
2276         if (allow < 0) {
2277                 res = allow;
2278                 goto leave;
2279         } else if (allow == 1) {
2280                 flags |= ALLOW_EMPTY;
2281         } else if (allow == 2) {
2282                 drop_commit = 1;
2283                 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2284                                 NULL, 0);
2285                 unlink(git_path_merge_msg(r));
2286                 unlink(git_path_auto_merge(r));
2287                 fprintf(stderr,
2288                         _("dropping %s %s -- patch contents already upstream\n"),
2289                         oid_to_hex(&commit->object.oid), msg.subject);
2290         } /* else allow == 0 and there's nothing special to do */
2291         if (!opts->no_commit && !drop_commit) {
2292                 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2293                         res = do_commit(r, msg_file, author, opts, flags,
2294                                         commit? &commit->object.oid : NULL);
2295                 else
2296                         res = error(_("unable to parse commit author"));
2297                 *check_todo = !!(flags & EDIT_MSG);
2298                 if (!res && reword) {
2299 fast_forward_edit:
2300                         res = run_git_commit(NULL, opts, EDIT_MSG |
2301                                              VERIFY_MSG | AMEND_MSG |
2302                                              (flags & ALLOW_EMPTY));
2303                         *check_todo = 1;
2304                 }
2305         }
2306
2307
2308         if (!res && final_fixup) {
2309                 unlink(rebase_path_fixup_msg());
2310                 unlink(rebase_path_squash_msg());
2311                 unlink(rebase_path_current_fixups());
2312                 strbuf_reset(&opts->current_fixups);
2313                 opts->current_fixup_count = 0;
2314         }
2315
2316 leave:
2317         free_message(commit, &msg);
2318         free(author);
2319         update_abort_safety_file();
2320
2321         return res;
2322 }
2323
2324 static int prepare_revs(struct replay_opts *opts)
2325 {
2326         /*
2327          * picking (but not reverting) ranges (but not individual revisions)
2328          * should be done in reverse
2329          */
2330         if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2331                 opts->revs->reverse ^= 1;
2332
2333         if (prepare_revision_walk(opts->revs))
2334                 return error(_("revision walk setup failed"));
2335
2336         return 0;
2337 }
2338
2339 static int read_and_refresh_cache(struct repository *r,
2340                                   struct replay_opts *opts)
2341 {
2342         struct lock_file index_lock = LOCK_INIT;
2343         int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2344         if (repo_read_index(r) < 0) {
2345                 rollback_lock_file(&index_lock);
2346                 return error(_("git %s: failed to read the index"),
2347                         _(action_name(opts)));
2348         }
2349         refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2350         if (index_fd >= 0) {
2351                 if (write_locked_index(r->index, &index_lock,
2352                                        COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2353                         return error(_("git %s: failed to refresh the index"),
2354                                 _(action_name(opts)));
2355                 }
2356         }
2357         return 0;
2358 }
2359
2360 void todo_list_release(struct todo_list *todo_list)
2361 {
2362         strbuf_release(&todo_list->buf);
2363         FREE_AND_NULL(todo_list->items);
2364         todo_list->nr = todo_list->alloc = 0;
2365 }
2366
2367 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2368 {
2369         ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2370         todo_list->total_nr++;
2371         return todo_list->items + todo_list->nr++;
2372 }
2373
2374 const char *todo_item_get_arg(struct todo_list *todo_list,
2375                               struct todo_item *item)
2376 {
2377         return todo_list->buf.buf + item->arg_offset;
2378 }
2379
2380 static int is_command(enum todo_command command, const char **bol)
2381 {
2382         const char *str = todo_command_info[command].str;
2383         const char nick = todo_command_info[command].c;
2384         const char *p = *bol + 1;
2385
2386         return skip_prefix(*bol, str, bol) ||
2387                 ((nick && **bol == nick) &&
2388                  (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2389                  (*bol = p));
2390 }
2391
2392 static int parse_insn_line(struct repository *r, struct todo_item *item,
2393                            const char *buf, const char *bol, char *eol)
2394 {
2395         struct object_id commit_oid;
2396         char *end_of_object_name;
2397         int i, saved, status, padding;
2398
2399         item->flags = 0;
2400
2401         /* left-trim */
2402         bol += strspn(bol, " \t");
2403
2404         if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2405                 item->command = TODO_COMMENT;
2406                 item->commit = NULL;
2407                 item->arg_offset = bol - buf;
2408                 item->arg_len = eol - bol;
2409                 return 0;
2410         }
2411
2412         for (i = 0; i < TODO_COMMENT; i++)
2413                 if (is_command(i, &bol)) {
2414                         item->command = i;
2415                         break;
2416                 }
2417         if (i >= TODO_COMMENT)
2418                 return -1;
2419
2420         /* Eat up extra spaces/ tabs before object name */
2421         padding = strspn(bol, " \t");
2422         bol += padding;
2423
2424         if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2425                 if (bol != eol)
2426                         return error(_("%s does not accept arguments: '%s'"),
2427                                      command_to_string(item->command), bol);
2428                 item->commit = NULL;
2429                 item->arg_offset = bol - buf;
2430                 item->arg_len = eol - bol;
2431                 return 0;
2432         }
2433
2434         if (!padding)
2435                 return error(_("missing arguments for %s"),
2436                              command_to_string(item->command));
2437
2438         if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2439             item->command == TODO_RESET) {
2440                 item->commit = NULL;
2441                 item->arg_offset = bol - buf;
2442                 item->arg_len = (int)(eol - bol);
2443                 return 0;
2444         }
2445
2446         if (item->command == TODO_FIXUP) {
2447                 if (skip_prefix(bol, "-C", &bol) &&
2448                    (*bol == ' ' || *bol == '\t')) {
2449                         bol += strspn(bol, " \t");
2450                         item->flags |= TODO_REPLACE_FIXUP_MSG;
2451                 } else if (skip_prefix(bol, "-c", &bol) &&
2452                                   (*bol == ' ' || *bol == '\t')) {
2453                         bol += strspn(bol, " \t");
2454                         item->flags |= TODO_EDIT_FIXUP_MSG;
2455                 }
2456         }
2457
2458         if (item->command == TODO_MERGE) {
2459                 if (skip_prefix(bol, "-C", &bol))
2460                         bol += strspn(bol, " \t");
2461                 else if (skip_prefix(bol, "-c", &bol)) {
2462                         bol += strspn(bol, " \t");
2463                         item->flags |= TODO_EDIT_MERGE_MSG;
2464                 } else {
2465                         item->flags |= TODO_EDIT_MERGE_MSG;
2466                         item->commit = NULL;
2467                         item->arg_offset = bol - buf;
2468                         item->arg_len = (int)(eol - bol);
2469                         return 0;
2470                 }
2471         }
2472
2473         end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2474         saved = *end_of_object_name;
2475         *end_of_object_name = '\0';
2476         status = get_oid(bol, &commit_oid);
2477         if (status < 0)
2478                 error(_("could not parse '%s'"), bol); /* return later */
2479         *end_of_object_name = saved;
2480
2481         bol = end_of_object_name + strspn(end_of_object_name, " \t");
2482         item->arg_offset = bol - buf;
2483         item->arg_len = (int)(eol - bol);
2484
2485         if (status < 0)
2486                 return status;
2487
2488         item->commit = lookup_commit_reference(r, &commit_oid);
2489         return item->commit ? 0 : -1;
2490 }
2491
2492 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2493 {
2494         const char *todo_file, *bol;
2495         struct strbuf buf = STRBUF_INIT;
2496         int ret = 0;
2497
2498         todo_file = git_path_todo_file();
2499         if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2500                 if (errno == ENOENT || errno == ENOTDIR)
2501                         return -1;
2502                 else
2503                         return error_errno("unable to open '%s'", todo_file);
2504         }
2505         bol = buf.buf + strspn(buf.buf, " \t\r\n");
2506         if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2507                 *action = REPLAY_PICK;
2508         else if (is_command(TODO_REVERT, &bol) &&
2509                  (*bol == ' ' || *bol == '\t'))
2510                 *action = REPLAY_REVERT;
2511         else
2512                 ret = -1;
2513
2514         strbuf_release(&buf);
2515
2516         return ret;
2517 }
2518
2519 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2520                                 struct todo_list *todo_list)
2521 {
2522         struct todo_item *item;
2523         char *p = buf, *next_p;
2524         int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2525
2526         todo_list->current = todo_list->nr = 0;
2527
2528         for (i = 1; *p; i++, p = next_p) {
2529                 char *eol = strchrnul(p, '\n');
2530
2531                 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2532
2533                 if (p != eol && eol[-1] == '\r')
2534                         eol--; /* strip Carriage Return */
2535
2536                 item = append_new_todo(todo_list);
2537                 item->offset_in_buf = p - todo_list->buf.buf;
2538                 if (parse_insn_line(r, item, buf, p, eol)) {
2539                         res = error(_("invalid line %d: %.*s"),
2540                                 i, (int)(eol - p), p);
2541                         item->command = TODO_COMMENT + 1;
2542                         item->arg_offset = p - buf;
2543                         item->arg_len = (int)(eol - p);
2544                         item->commit = NULL;
2545                 }
2546
2547                 if (fixup_okay)
2548                         ; /* do nothing */
2549                 else if (is_fixup(item->command))
2550                         return error(_("cannot '%s' without a previous commit"),
2551                                 command_to_string(item->command));
2552                 else if (!is_noop(item->command))
2553                         fixup_okay = 1;
2554         }
2555
2556         return res;
2557 }
2558
2559 static int count_commands(struct todo_list *todo_list)
2560 {
2561         int count = 0, i;
2562
2563         for (i = 0; i < todo_list->nr; i++)
2564                 if (todo_list->items[i].command != TODO_COMMENT)
2565                         count++;
2566
2567         return count;
2568 }
2569
2570 static int get_item_line_offset(struct todo_list *todo_list, int index)
2571 {
2572         return index < todo_list->nr ?
2573                 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2574 }
2575
2576 static const char *get_item_line(struct todo_list *todo_list, int index)
2577 {
2578         return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2579 }
2580
2581 static int get_item_line_length(struct todo_list *todo_list, int index)
2582 {
2583         return get_item_line_offset(todo_list, index + 1)
2584                 -  get_item_line_offset(todo_list, index);
2585 }
2586
2587 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2588 {
2589         int fd;
2590         ssize_t len;
2591
2592         fd = open(path, O_RDONLY);
2593         if (fd < 0)
2594                 return error_errno(_("could not open '%s'"), path);
2595         len = strbuf_read(sb, fd, 0);
2596         close(fd);
2597         if (len < 0)
2598                 return error(_("could not read '%s'."), path);
2599         return len;
2600 }
2601
2602 static int have_finished_the_last_pick(void)
2603 {
2604         struct strbuf buf = STRBUF_INIT;
2605         const char *eol;
2606         const char *todo_path = git_path_todo_file();
2607         int ret = 0;
2608
2609         if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2610                 if (errno == ENOENT) {
2611                         return 0;
2612                 } else {
2613                         error_errno("unable to open '%s'", todo_path);
2614                         return 0;
2615                 }
2616         }
2617         /* If there is only one line then we are done */
2618         eol = strchr(buf.buf, '\n');
2619         if (!eol || !eol[1])
2620                 ret = 1;
2621
2622         strbuf_release(&buf);
2623
2624         return ret;
2625 }
2626
2627 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2628 {
2629         struct replay_opts opts = REPLAY_OPTS_INIT;
2630         int need_cleanup = 0;
2631
2632         if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2633                 if (!refs_delete_ref(get_main_ref_store(r), "",
2634                                      "CHERRY_PICK_HEAD", NULL, 0) &&
2635                     verbose)
2636                         warning(_("cancelling a cherry picking in progress"));
2637                 opts.action = REPLAY_PICK;
2638                 need_cleanup = 1;
2639         }
2640
2641         if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2642                 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2643                                      NULL, 0) &&
2644                     verbose)
2645                         warning(_("cancelling a revert in progress"));
2646                 opts.action = REPLAY_REVERT;
2647                 need_cleanup = 1;
2648         }
2649
2650         unlink(git_path_auto_merge(r));
2651
2652         if (!need_cleanup)
2653                 return;
2654
2655         if (!have_finished_the_last_pick())
2656                 return;
2657
2658         sequencer_remove_state(&opts);
2659 }
2660
2661 static void todo_list_write_total_nr(struct todo_list *todo_list)
2662 {
2663         FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2664
2665         if (f) {
2666                 fprintf(f, "%d\n", todo_list->total_nr);
2667                 fclose(f);
2668         }
2669 }
2670
2671 static int read_populate_todo(struct repository *r,
2672                               struct todo_list *todo_list,
2673                               struct replay_opts *opts)
2674 {
2675         struct stat st;
2676         const char *todo_file = get_todo_path(opts);
2677         int res;
2678
2679         strbuf_reset(&todo_list->buf);
2680         if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2681                 return -1;
2682
2683         res = stat(todo_file, &st);
2684         if (res)
2685                 return error(_("could not stat '%s'"), todo_file);
2686         fill_stat_data(&todo_list->stat, &st);
2687
2688         res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2689         if (res) {
2690                 if (is_rebase_i(opts))
2691                         return error(_("please fix this using "
2692                                        "'git rebase --edit-todo'."));
2693                 return error(_("unusable instruction sheet: '%s'"), todo_file);
2694         }
2695
2696         if (!todo_list->nr &&
2697             (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2698                 return error(_("no commits parsed."));
2699
2700         if (!is_rebase_i(opts)) {
2701                 enum todo_command valid =
2702                         opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2703                 int i;
2704
2705                 for (i = 0; i < todo_list->nr; i++)
2706                         if (valid == todo_list->items[i].command)
2707                                 continue;
2708                         else if (valid == TODO_PICK)
2709                                 return error(_("cannot cherry-pick during a revert."));
2710                         else
2711                                 return error(_("cannot revert during a cherry-pick."));
2712         }
2713
2714         if (is_rebase_i(opts)) {
2715                 struct todo_list done = TODO_LIST_INIT;
2716
2717                 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2718                     !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2719                         todo_list->done_nr = count_commands(&done);
2720                 else
2721                         todo_list->done_nr = 0;
2722
2723                 todo_list->total_nr = todo_list->done_nr
2724                         + count_commands(todo_list);
2725                 todo_list_release(&done);
2726
2727                 todo_list_write_total_nr(todo_list);
2728         }
2729
2730         return 0;
2731 }
2732
2733 static int git_config_string_dup(char **dest,
2734                                  const char *var, const char *value)
2735 {
2736         if (!value)
2737                 return config_error_nonbool(var);
2738         free(*dest);
2739         *dest = xstrdup(value);
2740         return 0;
2741 }
2742
2743 static int populate_opts_cb(const char *key, const char *value, void *data)
2744 {
2745         struct replay_opts *opts = data;
2746         int error_flag = 1;
2747
2748         if (!value)
2749                 error_flag = 0;
2750         else if (!strcmp(key, "options.no-commit"))
2751                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2752         else if (!strcmp(key, "options.edit"))
2753                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2754         else if (!strcmp(key, "options.allow-empty"))
2755                 opts->allow_empty =
2756                         git_config_bool_or_int(key, value, &error_flag);
2757         else if (!strcmp(key, "options.allow-empty-message"))
2758                 opts->allow_empty_message =
2759                         git_config_bool_or_int(key, value, &error_flag);
2760         else if (!strcmp(key, "options.keep-redundant-commits"))
2761                 opts->keep_redundant_commits =
2762                         git_config_bool_or_int(key, value, &error_flag);
2763         else if (!strcmp(key, "options.signoff"))
2764                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2765         else if (!strcmp(key, "options.record-origin"))
2766                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2767         else if (!strcmp(key, "options.allow-ff"))
2768                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2769         else if (!strcmp(key, "options.mainline"))
2770                 opts->mainline = git_config_int(key, value);
2771         else if (!strcmp(key, "options.strategy"))
2772                 git_config_string_dup(&opts->strategy, key, value);
2773         else if (!strcmp(key, "options.gpg-sign"))
2774                 git_config_string_dup(&opts->gpg_sign, key, value);
2775         else if (!strcmp(key, "options.strategy-option")) {
2776                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2777                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2778         } else if (!strcmp(key, "options.allow-rerere-auto"))
2779                 opts->allow_rerere_auto =
2780                         git_config_bool_or_int(key, value, &error_flag) ?
2781                                 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2782         else if (!strcmp(key, "options.default-msg-cleanup")) {
2783                 opts->explicit_cleanup = 1;
2784                 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2785         } else
2786                 return error(_("invalid key: %s"), key);
2787
2788         if (!error_flag)
2789                 return error(_("invalid value for %s: %s"), key, value);
2790
2791         return 0;
2792 }
2793
2794 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2795 {
2796         int i;
2797         char *strategy_opts_string = raw_opts;
2798
2799         if (*strategy_opts_string == ' ')
2800                 strategy_opts_string++;
2801
2802         opts->xopts_nr = split_cmdline(strategy_opts_string,
2803                                        (const char ***)&opts->xopts);
2804         for (i = 0; i < opts->xopts_nr; i++) {
2805                 const char *arg = opts->xopts[i];
2806
2807                 skip_prefix(arg, "--", &arg);
2808                 opts->xopts[i] = xstrdup(arg);
2809         }
2810 }
2811
2812 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2813 {
2814         strbuf_reset(buf);
2815         if (!read_oneliner(buf, rebase_path_strategy(), 0))
2816                 return;
2817         opts->strategy = strbuf_detach(buf, NULL);
2818         if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2819                 return;
2820
2821         parse_strategy_opts(opts, buf->buf);
2822 }
2823
2824 static int read_populate_opts(struct replay_opts *opts)
2825 {
2826         if (is_rebase_i(opts)) {
2827                 struct strbuf buf = STRBUF_INIT;
2828                 int ret = 0;
2829
2830                 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2831                                   READ_ONELINER_SKIP_IF_EMPTY)) {
2832                         if (!starts_with(buf.buf, "-S"))
2833                                 strbuf_reset(&buf);
2834                         else {
2835                                 free(opts->gpg_sign);
2836                                 opts->gpg_sign = xstrdup(buf.buf + 2);
2837                         }
2838                         strbuf_reset(&buf);
2839                 }
2840
2841                 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2842                                   READ_ONELINER_SKIP_IF_EMPTY)) {
2843                         if (!strcmp(buf.buf, "--rerere-autoupdate"))
2844                                 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2845                         else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2846                                 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2847                         strbuf_reset(&buf);
2848                 }
2849
2850                 if (file_exists(rebase_path_verbose()))
2851                         opts->verbose = 1;
2852
2853                 if (file_exists(rebase_path_quiet()))
2854                         opts->quiet = 1;
2855
2856                 if (file_exists(rebase_path_signoff())) {
2857                         opts->allow_ff = 0;
2858                         opts->signoff = 1;
2859                 }
2860
2861                 if (file_exists(rebase_path_cdate_is_adate())) {
2862                         opts->allow_ff = 0;
2863                         opts->committer_date_is_author_date = 1;
2864                 }
2865
2866                 if (file_exists(rebase_path_ignore_date())) {
2867                         opts->allow_ff = 0;
2868                         opts->ignore_date = 1;
2869                 }
2870
2871                 if (file_exists(rebase_path_reschedule_failed_exec()))
2872                         opts->reschedule_failed_exec = 1;
2873                 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
2874                         opts->reschedule_failed_exec = 0;
2875
2876                 if (file_exists(rebase_path_drop_redundant_commits()))
2877                         opts->drop_redundant_commits = 1;
2878
2879                 if (file_exists(rebase_path_keep_redundant_commits()))
2880                         opts->keep_redundant_commits = 1;
2881
2882                 read_strategy_opts(opts, &buf);
2883                 strbuf_reset(&buf);
2884
2885                 if (read_oneliner(&opts->current_fixups,
2886                                   rebase_path_current_fixups(),
2887                                   READ_ONELINER_SKIP_IF_EMPTY)) {
2888                         const char *p = opts->current_fixups.buf;
2889                         opts->current_fixup_count = 1;
2890                         while ((p = strchr(p, '\n'))) {
2891                                 opts->current_fixup_count++;
2892                                 p++;
2893                         }
2894                 }
2895
2896                 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2897                         if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2898                                 ret = error(_("unusable squash-onto"));
2899                                 goto done_rebase_i;
2900                         }
2901                         opts->have_squash_onto = 1;
2902                 }
2903
2904 done_rebase_i:
2905                 strbuf_release(&buf);
2906                 return ret;
2907         }
2908
2909         if (!file_exists(git_path_opts_file()))
2910                 return 0;
2911         /*
2912          * The function git_parse_source(), called from git_config_from_file(),
2913          * may die() in case of a syntactically incorrect file. We do not care
2914          * about this case, though, because we wrote that file ourselves, so we
2915          * are pretty certain that it is syntactically correct.
2916          */
2917         if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2918                 return error(_("malformed options sheet: '%s'"),
2919                         git_path_opts_file());
2920         return 0;
2921 }
2922
2923 static void write_strategy_opts(struct replay_opts *opts)
2924 {
2925         int i;
2926         struct strbuf buf = STRBUF_INIT;
2927
2928         for (i = 0; i < opts->xopts_nr; ++i)
2929                 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2930
2931         write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2932         strbuf_release(&buf);
2933 }
2934
2935 int write_basic_state(struct replay_opts *opts, const char *head_name,
2936                       struct commit *onto, const struct object_id *orig_head)
2937 {
2938         if (head_name)
2939                 write_file(rebase_path_head_name(), "%s\n", head_name);
2940         if (onto)
2941                 write_file(rebase_path_onto(), "%s\n",
2942                            oid_to_hex(&onto->object.oid));
2943         if (orig_head)
2944                 write_file(rebase_path_orig_head(), "%s\n",
2945                            oid_to_hex(orig_head));
2946
2947         if (opts->quiet)
2948                 write_file(rebase_path_quiet(), "%s", "");
2949         if (opts->verbose)
2950                 write_file(rebase_path_verbose(), "%s", "");
2951         if (opts->strategy)
2952                 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2953         if (opts->xopts_nr > 0)
2954                 write_strategy_opts(opts);
2955
2956         if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2957                 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2958         else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2959                 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2960
2961         if (opts->gpg_sign)
2962                 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2963         if (opts->signoff)
2964                 write_file(rebase_path_signoff(), "--signoff\n");
2965         if (opts->drop_redundant_commits)
2966                 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2967         if (opts->keep_redundant_commits)
2968                 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2969         if (opts->committer_date_is_author_date)
2970                 write_file(rebase_path_cdate_is_adate(), "%s", "");
2971         if (opts->ignore_date)
2972                 write_file(rebase_path_ignore_date(), "%s", "");
2973         if (opts->reschedule_failed_exec)
2974                 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2975         else
2976                 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
2977
2978         return 0;
2979 }
2980
2981 static int walk_revs_populate_todo(struct todo_list *todo_list,
2982                                 struct replay_opts *opts)
2983 {
2984         enum todo_command command = opts->action == REPLAY_PICK ?
2985                 TODO_PICK : TODO_REVERT;
2986         const char *command_string = todo_command_info[command].str;
2987         const char *encoding;
2988         struct commit *commit;
2989
2990         if (prepare_revs(opts))
2991                 return -1;
2992
2993         encoding = get_log_output_encoding();
2994
2995         while ((commit = get_revision(opts->revs))) {
2996                 struct todo_item *item = append_new_todo(todo_list);
2997                 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2998                 const char *subject;
2999                 int subject_len;
3000
3001                 item->command = command;
3002                 item->commit = commit;
3003                 item->arg_offset = 0;
3004                 item->arg_len = 0;
3005                 item->offset_in_buf = todo_list->buf.len;
3006                 subject_len = find_commit_subject(commit_buffer, &subject);
3007                 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3008                         short_commit_name(commit), subject_len, subject);
3009                 unuse_commit_buffer(commit, commit_buffer);
3010         }
3011
3012         if (!todo_list->nr)
3013                 return error(_("empty commit set passed"));
3014
3015         return 0;
3016 }
3017
3018 static int create_seq_dir(struct repository *r)
3019 {
3020         enum replay_action action;
3021         const char *in_progress_error = NULL;
3022         const char *in_progress_advice = NULL;
3023         unsigned int advise_skip =
3024                 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3025                 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3026
3027         if (!sequencer_get_last_command(r, &action)) {
3028                 switch (action) {
3029                 case REPLAY_REVERT:
3030                         in_progress_error = _("revert is already in progress");
3031                         in_progress_advice =
3032                         _("try \"git revert (--continue | %s--abort | --quit)\"");
3033                         break;
3034                 case REPLAY_PICK:
3035                         in_progress_error = _("cherry-pick is already in progress");
3036                         in_progress_advice =
3037                         _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3038                         break;
3039                 default:
3040                         BUG("unexpected action in create_seq_dir");
3041                 }
3042         }
3043         if (in_progress_error) {
3044                 error("%s", in_progress_error);
3045                 if (advice_sequencer_in_use)
3046                         advise(in_progress_advice,
3047                                 advise_skip ? "--skip | " : "");
3048                 return -1;
3049         }
3050         if (mkdir(git_path_seq_dir(), 0777) < 0)
3051                 return error_errno(_("could not create sequencer directory '%s'"),
3052                                    git_path_seq_dir());
3053
3054         return 0;
3055 }
3056
3057 static int save_head(const char *head)
3058 {
3059         struct lock_file head_lock = LOCK_INIT;
3060         struct strbuf buf = STRBUF_INIT;
3061         int fd;
3062         ssize_t written;
3063
3064         fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3065         if (fd < 0)
3066                 return error_errno(_("could not lock HEAD"));
3067         strbuf_addf(&buf, "%s\n", head);
3068         written = write_in_full(fd, buf.buf, buf.len);
3069         strbuf_release(&buf);
3070         if (written < 0) {
3071                 error_errno(_("could not write to '%s'"), git_path_head_file());
3072                 rollback_lock_file(&head_lock);
3073                 return -1;
3074         }
3075         if (commit_lock_file(&head_lock) < 0)
3076                 return error(_("failed to finalize '%s'"), git_path_head_file());
3077         return 0;
3078 }
3079
3080 static int rollback_is_safe(void)
3081 {
3082         struct strbuf sb = STRBUF_INIT;
3083         struct object_id expected_head, actual_head;
3084
3085         if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3086                 strbuf_trim(&sb);
3087                 if (get_oid_hex(sb.buf, &expected_head)) {
3088                         strbuf_release(&sb);
3089                         die(_("could not parse %s"), git_path_abort_safety_file());
3090                 }
3091                 strbuf_release(&sb);
3092         }
3093         else if (errno == ENOENT)
3094                 oidclr(&expected_head);
3095         else
3096                 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3097
3098         if (get_oid("HEAD", &actual_head))
3099                 oidclr(&actual_head);
3100
3101         return oideq(&actual_head, &expected_head);
3102 }
3103
3104 static int reset_merge(const struct object_id *oid)
3105 {
3106         int ret;
3107         struct strvec argv = STRVEC_INIT;
3108
3109         strvec_pushl(&argv, "reset", "--merge", NULL);
3110
3111         if (!is_null_oid(oid))
3112                 strvec_push(&argv, oid_to_hex(oid));
3113
3114         ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3115         strvec_clear(&argv);
3116
3117         return ret;
3118 }
3119
3120 static int rollback_single_pick(struct repository *r)
3121 {
3122         struct object_id head_oid;
3123
3124         if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3125             !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3126                 return error(_("no cherry-pick or revert in progress"));
3127         if (read_ref_full("HEAD", 0, &head_oid, NULL))
3128                 return error(_("cannot resolve HEAD"));
3129         if (is_null_oid(&head_oid))
3130                 return error(_("cannot abort from a branch yet to be born"));
3131         return reset_merge(&head_oid);
3132 }
3133
3134 static int skip_single_pick(void)
3135 {
3136         struct object_id head;
3137
3138         if (read_ref_full("HEAD", 0, &head, NULL))
3139                 return error(_("cannot resolve HEAD"));
3140         return reset_merge(&head);
3141 }
3142
3143 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3144 {
3145         FILE *f;
3146         struct object_id oid;
3147         struct strbuf buf = STRBUF_INIT;
3148         const char *p;
3149
3150         f = fopen(git_path_head_file(), "r");
3151         if (!f && errno == ENOENT) {
3152                 /*
3153                  * There is no multiple-cherry-pick in progress.
3154                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3155                  * a single-cherry-pick in progress, abort that.
3156                  */
3157                 return rollback_single_pick(r);
3158         }
3159         if (!f)
3160                 return error_errno(_("cannot open '%s'"), git_path_head_file());
3161         if (strbuf_getline_lf(&buf, f)) {
3162                 error(_("cannot read '%s': %s"), git_path_head_file(),
3163                       ferror(f) ?  strerror(errno) : _("unexpected end of file"));
3164                 fclose(f);
3165                 goto fail;
3166         }
3167         fclose(f);
3168         if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3169                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3170                         git_path_head_file());
3171                 goto fail;
3172         }
3173         if (is_null_oid(&oid)) {
3174                 error(_("cannot abort from a branch yet to be born"));
3175                 goto fail;
3176         }
3177
3178         if (!rollback_is_safe()) {
3179                 /* Do not error, just do not rollback */
3180                 warning(_("You seem to have moved HEAD. "
3181                           "Not rewinding, check your HEAD!"));
3182         } else
3183         if (reset_merge(&oid))
3184                 goto fail;
3185         strbuf_release(&buf);
3186         return sequencer_remove_state(opts);
3187 fail:
3188         strbuf_release(&buf);
3189         return -1;
3190 }
3191
3192 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3193 {
3194         enum replay_action action = -1;
3195         sequencer_get_last_command(r, &action);
3196
3197         /*
3198          * Check whether the subcommand requested to skip the commit is actually
3199          * in progress and that it's safe to skip the commit.
3200          *
3201          * opts->action tells us which subcommand requested to skip the commit.
3202          * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3203          * action is in progress and we can skip the commit.
3204          *
3205          * Otherwise we check that the last instruction was related to the
3206          * particular subcommand we're trying to execute and barf if that's not
3207          * the case.
3208          *
3209          * Finally we check that the rollback is "safe", i.e., has the HEAD
3210          * moved? In this case, it doesn't make sense to "reset the merge" and
3211          * "skip the commit" as the user already handled this by committing. But
3212          * we'd not want to barf here, instead give advice on how to proceed. We
3213          * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3214          * it gets removed when the user commits, so if it still exists we're
3215          * sure the user can't have committed before.
3216          */
3217         switch (opts->action) {
3218         case REPLAY_REVERT:
3219                 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3220                         if (action != REPLAY_REVERT)
3221                                 return error(_("no revert in progress"));
3222                         if (!rollback_is_safe())
3223                                 goto give_advice;
3224                 }
3225                 break;
3226         case REPLAY_PICK:
3227                 if (!refs_ref_exists(get_main_ref_store(r),
3228                                      "CHERRY_PICK_HEAD")) {
3229                         if (action != REPLAY_PICK)
3230                                 return error(_("no cherry-pick in progress"));
3231                         if (!rollback_is_safe())
3232                                 goto give_advice;
3233                 }
3234                 break;
3235         default:
3236                 BUG("unexpected action in sequencer_skip");
3237         }
3238
3239         if (skip_single_pick())
3240                 return error(_("failed to skip the commit"));
3241         if (!is_directory(git_path_seq_dir()))
3242                 return 0;
3243
3244         return sequencer_continue(r, opts);
3245
3246 give_advice:
3247         error(_("there is nothing to skip"));
3248
3249         if (advice_resolve_conflict) {
3250                 advise(_("have you committed already?\n"
3251                          "try \"git %s --continue\""),
3252                          action == REPLAY_REVERT ? "revert" : "cherry-pick");
3253         }
3254         return -1;
3255 }
3256
3257 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3258 {
3259         struct lock_file todo_lock = LOCK_INIT;
3260         const char *todo_path = get_todo_path(opts);
3261         int next = todo_list->current, offset, fd;
3262
3263         /*
3264          * rebase -i writes "git-rebase-todo" without the currently executing
3265          * command, appending it to "done" instead.
3266          */
3267         if (is_rebase_i(opts))
3268                 next++;
3269
3270         fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3271         if (fd < 0)
3272                 return error_errno(_("could not lock '%s'"), todo_path);
3273         offset = get_item_line_offset(todo_list, next);
3274         if (write_in_full(fd, todo_list->buf.buf + offset,
3275                         todo_list->buf.len - offset) < 0)
3276                 return error_errno(_("could not write to '%s'"), todo_path);
3277         if (commit_lock_file(&todo_lock) < 0)
3278                 return error(_("failed to finalize '%s'"), todo_path);
3279
3280         if (is_rebase_i(opts) && next > 0) {
3281                 const char *done = rebase_path_done();
3282                 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3283                 int ret = 0;
3284
3285                 if (fd < 0)
3286                         return 0;
3287                 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3288                                   get_item_line_length(todo_list, next - 1))
3289                     < 0)
3290                         ret = error_errno(_("could not write to '%s'"), done);
3291                 if (close(fd) < 0)
3292                         ret = error_errno(_("failed to finalize '%s'"), done);
3293                 return ret;
3294         }
3295         return 0;
3296 }
3297
3298 static int save_opts(struct replay_opts *opts)
3299 {
3300         const char *opts_file = git_path_opts_file();
3301         int res = 0;
3302
3303         if (opts->no_commit)
3304                 res |= git_config_set_in_file_gently(opts_file,
3305                                         "options.no-commit", "true");
3306         if (opts->edit >= 0)
3307                 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3308                                                      opts->edit ? "true" : "false");
3309         if (opts->allow_empty)
3310                 res |= git_config_set_in_file_gently(opts_file,
3311                                         "options.allow-empty", "true");
3312         if (opts->allow_empty_message)
3313                 res |= git_config_set_in_file_gently(opts_file,
3314                                 "options.allow-empty-message", "true");
3315         if (opts->keep_redundant_commits)
3316                 res |= git_config_set_in_file_gently(opts_file,
3317                                 "options.keep-redundant-commits", "true");
3318         if (opts->signoff)
3319                 res |= git_config_set_in_file_gently(opts_file,
3320                                         "options.signoff", "true");
3321         if (opts->record_origin)
3322                 res |= git_config_set_in_file_gently(opts_file,
3323                                         "options.record-origin", "true");
3324         if (opts->allow_ff)
3325                 res |= git_config_set_in_file_gently(opts_file,
3326                                         "options.allow-ff", "true");
3327         if (opts->mainline) {
3328                 struct strbuf buf = STRBUF_INIT;
3329                 strbuf_addf(&buf, "%d", opts->mainline);
3330                 res |= git_config_set_in_file_gently(opts_file,
3331                                         "options.mainline", buf.buf);
3332                 strbuf_release(&buf);
3333         }
3334         if (opts->strategy)
3335                 res |= git_config_set_in_file_gently(opts_file,
3336                                         "options.strategy", opts->strategy);
3337         if (opts->gpg_sign)
3338                 res |= git_config_set_in_file_gently(opts_file,
3339                                         "options.gpg-sign", opts->gpg_sign);
3340         if (opts->xopts) {
3341                 int i;
3342                 for (i = 0; i < opts->xopts_nr; i++)
3343                         res |= git_config_set_multivar_in_file_gently(opts_file,
3344                                         "options.strategy-option",
3345                                         opts->xopts[i], "^$", 0);
3346         }
3347         if (opts->allow_rerere_auto)
3348                 res |= git_config_set_in_file_gently(opts_file,
3349                                 "options.allow-rerere-auto",
3350                                 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3351                                 "true" : "false");
3352
3353         if (opts->explicit_cleanup)
3354                 res |= git_config_set_in_file_gently(opts_file,
3355                                 "options.default-msg-cleanup",
3356                                 describe_cleanup_mode(opts->default_msg_cleanup));
3357         return res;
3358 }
3359
3360 static int make_patch(struct repository *r,
3361                       struct commit *commit,
3362                       struct replay_opts *opts)
3363 {
3364         struct strbuf buf = STRBUF_INIT;
3365         struct rev_info log_tree_opt;
3366         const char *subject;
3367         char hex[GIT_MAX_HEXSZ + 1];
3368         int res = 0;
3369
3370         oid_to_hex_r(hex, &commit->object.oid);
3371         if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3372                 return -1;
3373         res |= write_rebase_head(&commit->object.oid);
3374
3375         strbuf_addf(&buf, "%s/patch", get_dir(opts));
3376         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3377         repo_init_revisions(r, &log_tree_opt, NULL);
3378         log_tree_opt.abbrev = 0;
3379         log_tree_opt.diff = 1;
3380         log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3381         log_tree_opt.disable_stdin = 1;
3382         log_tree_opt.no_commit_id = 1;
3383         log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3384         log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3385         if (!log_tree_opt.diffopt.file)
3386                 res |= error_errno(_("could not open '%s'"), buf.buf);
3387         else {
3388                 res |= log_tree_commit(&log_tree_opt, commit);
3389                 fclose(log_tree_opt.diffopt.file);
3390         }
3391         strbuf_reset(&buf);
3392
3393         strbuf_addf(&buf, "%s/message", get_dir(opts));
3394         if (!file_exists(buf.buf)) {
3395                 const char *encoding = get_commit_output_encoding();
3396                 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3397                 find_commit_subject(commit_buffer, &subject);
3398                 res |= write_message(subject, strlen(subject), buf.buf, 1);
3399                 unuse_commit_buffer(commit, commit_buffer);
3400         }
3401         strbuf_release(&buf);
3402
3403         return res;
3404 }
3405
3406 static int intend_to_amend(void)
3407 {
3408         struct object_id head;
3409         char *p;
3410
3411         if (get_oid("HEAD", &head))
3412                 return error(_("cannot read HEAD"));
3413
3414         p = oid_to_hex(&head);
3415         return write_message(p, strlen(p), rebase_path_amend(), 1);
3416 }
3417
3418 static int error_with_patch(struct repository *r,
3419                             struct commit *commit,
3420                             const char *subject, int subject_len,
3421                             struct replay_opts *opts,
3422                             int exit_code, int to_amend)
3423 {
3424         if (commit) {
3425                 if (make_patch(r, commit, opts))
3426                         return -1;
3427         } else if (copy_file(rebase_path_message(),
3428                              git_path_merge_msg(r), 0666))
3429                 return error(_("unable to copy '%s' to '%s'"),
3430                              git_path_merge_msg(r), rebase_path_message());
3431
3432         if (to_amend) {
3433                 if (intend_to_amend())
3434                         return -1;
3435
3436                 fprintf(stderr,
3437                         _("You can amend the commit now, with\n"
3438                           "\n"
3439                           "  git commit --amend %s\n"
3440                           "\n"
3441                           "Once you are satisfied with your changes, run\n"
3442                           "\n"
3443                           "  git rebase --continue\n"),
3444                         gpg_sign_opt_quoted(opts));
3445         } else if (exit_code) {
3446                 if (commit)
3447                         fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3448                                    short_commit_name(commit), subject_len, subject);
3449                 else
3450                         /*
3451                          * We don't have the hash of the parent so
3452                          * just print the line from the todo file.
3453                          */
3454                         fprintf_ln(stderr, _("Could not merge %.*s"),
3455                                    subject_len, subject);
3456         }
3457
3458         return exit_code;
3459 }
3460
3461 static int error_failed_squash(struct repository *r,
3462                                struct commit *commit,
3463                                struct replay_opts *opts,
3464                                int subject_len,
3465                                const char *subject)
3466 {
3467         if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3468                 return error(_("could not copy '%s' to '%s'"),
3469                         rebase_path_squash_msg(), rebase_path_message());
3470         unlink(git_path_merge_msg(r));
3471         if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3472                 return error(_("could not copy '%s' to '%s'"),
3473                              rebase_path_message(),
3474                              git_path_merge_msg(r));
3475         return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3476 }
3477
3478 static int do_exec(struct repository *r, const char *command_line)
3479 {
3480         struct strvec child_env = STRVEC_INIT;
3481         const char *child_argv[] = { NULL, NULL };
3482         int dirty, status;
3483
3484         fprintf(stderr, _("Executing: %s\n"), command_line);
3485         child_argv[0] = command_line;
3486         strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3487         strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3488                      absolute_path(get_git_work_tree()));
3489         status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3490                                           child_env.v);
3491
3492         /* force re-reading of the cache */
3493         if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3494                 return error(_("could not read index"));
3495
3496         dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3497
3498         if (status) {
3499                 warning(_("execution failed: %s\n%s"
3500                           "You can fix the problem, and then run\n"
3501                           "\n"
3502                           "  git rebase --continue\n"
3503                           "\n"),
3504                         command_line,
3505                         dirty ? N_("and made changes to the index and/or the "
3506                                 "working tree\n") : "");
3507                 if (status == 127)
3508                         /* command not found */
3509                         status = 1;
3510         } else if (dirty) {
3511                 warning(_("execution succeeded: %s\nbut "
3512                           "left changes to the index and/or the working tree\n"
3513                           "Commit or stash your changes, and then run\n"
3514                           "\n"
3515                           "  git rebase --continue\n"
3516                           "\n"), command_line);
3517                 status = 1;
3518         }
3519
3520         strvec_clear(&child_env);
3521
3522         return status;
3523 }
3524
3525 static int safe_append(const char *filename, const char *fmt, ...)
3526 {
3527         va_list ap;
3528         struct lock_file lock = LOCK_INIT;
3529         int fd = hold_lock_file_for_update(&lock, filename,
3530                                            LOCK_REPORT_ON_ERROR);
3531         struct strbuf buf = STRBUF_INIT;
3532
3533         if (fd < 0)
3534                 return -1;
3535
3536         if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3537                 error_errno(_("could not read '%s'"), filename);
3538                 rollback_lock_file(&lock);
3539                 return -1;
3540         }
3541         strbuf_complete(&buf, '\n');
3542         va_start(ap, fmt);
3543         strbuf_vaddf(&buf, fmt, ap);
3544         va_end(ap);
3545
3546         if (write_in_full(fd, buf.buf, buf.len) < 0) {
3547                 error_errno(_("could not write to '%s'"), filename);
3548                 strbuf_release(&buf);
3549                 rollback_lock_file(&lock);
3550                 return -1;
3551         }
3552         if (commit_lock_file(&lock) < 0) {
3553                 strbuf_release(&buf);
3554                 rollback_lock_file(&lock);
3555                 return error(_("failed to finalize '%s'"), filename);
3556         }
3557
3558         strbuf_release(&buf);
3559         return 0;
3560 }
3561
3562 static int do_label(struct repository *r, const char *name, int len)
3563 {
3564         struct ref_store *refs = get_main_ref_store(r);
3565         struct ref_transaction *transaction;
3566         struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3567         struct strbuf msg = STRBUF_INIT;
3568         int ret = 0;
3569         struct object_id head_oid;
3570
3571         if (len == 1 && *name == '#')
3572                 return error(_("illegal label name: '%.*s'"), len, name);
3573
3574         strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3575         strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3576
3577         transaction = ref_store_transaction_begin(refs, &err);
3578         if (!transaction) {
3579                 error("%s", err.buf);
3580                 ret = -1;
3581         } else if (get_oid("HEAD", &head_oid)) {
3582                 error(_("could not read HEAD"));
3583                 ret = -1;
3584         } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3585                                           NULL, 0, msg.buf, &err) < 0 ||
3586                    ref_transaction_commit(transaction, &err)) {
3587                 error("%s", err.buf);
3588                 ret = -1;
3589         }
3590         ref_transaction_free(transaction);
3591         strbuf_release(&err);
3592         strbuf_release(&msg);
3593
3594         if (!ret)
3595                 ret = safe_append(rebase_path_refs_to_delete(),
3596                                   "%s\n", ref_name.buf);
3597         strbuf_release(&ref_name);
3598
3599         return ret;
3600 }
3601
3602 static const char *reflog_message(struct replay_opts *opts,
3603         const char *sub_action, const char *fmt, ...);
3604
3605 static int do_reset(struct repository *r,
3606                     const char *name, int len,
3607                     struct replay_opts *opts)
3608 {
3609         struct strbuf ref_name = STRBUF_INIT;
3610         struct object_id oid;
3611         struct lock_file lock = LOCK_INIT;
3612         struct tree_desc desc;
3613         struct tree *tree;
3614         struct unpack_trees_options unpack_tree_opts;
3615         int ret = 0;
3616
3617         if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3618                 return -1;
3619
3620         if (len == 10 && !strncmp("[new root]", name, len)) {
3621                 if (!opts->have_squash_onto) {
3622                         const char *hex;
3623                         if (commit_tree("", 0, the_hash_algo->empty_tree,
3624                                         NULL, &opts->squash_onto,
3625                                         NULL, NULL))
3626                                 return error(_("writing fake root commit"));
3627                         opts->have_squash_onto = 1;
3628                         hex = oid_to_hex(&opts->squash_onto);
3629                         if (write_message(hex, strlen(hex),
3630                                           rebase_path_squash_onto(), 0))
3631                                 return error(_("writing squash-onto"));
3632                 }
3633                 oidcpy(&oid, &opts->squash_onto);
3634         } else {
3635                 int i;
3636
3637                 /* Determine the length of the label */
3638                 for (i = 0; i < len; i++)
3639                         if (isspace(name[i]))
3640                                 break;
3641                 len = i;
3642
3643                 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3644                 if (get_oid(ref_name.buf, &oid) &&
3645                     get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3646                         error(_("could not read '%s'"), ref_name.buf);
3647                         rollback_lock_file(&lock);
3648                         strbuf_release(&ref_name);
3649                         return -1;
3650                 }
3651         }
3652
3653         memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3654         setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3655         unpack_tree_opts.head_idx = 1;
3656         unpack_tree_opts.src_index = r->index;
3657         unpack_tree_opts.dst_index = r->index;
3658         unpack_tree_opts.fn = oneway_merge;
3659         unpack_tree_opts.merge = 1;
3660         unpack_tree_opts.update = 1;
3661         init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3662
3663         if (repo_read_index_unmerged(r)) {
3664                 rollback_lock_file(&lock);
3665                 strbuf_release(&ref_name);
3666                 return error_resolve_conflict(_(action_name(opts)));
3667         }
3668
3669         if (!fill_tree_descriptor(r, &desc, &oid)) {
3670                 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3671                 rollback_lock_file(&lock);
3672                 free((void *)desc.buffer);
3673                 strbuf_release(&ref_name);
3674                 return -1;
3675         }
3676
3677         if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3678                 rollback_lock_file(&lock);
3679                 free((void *)desc.buffer);
3680                 strbuf_release(&ref_name);
3681                 return -1;
3682         }
3683
3684         tree = parse_tree_indirect(&oid);
3685         prime_cache_tree(r, r->index, tree);
3686
3687         if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3688                 ret = error(_("could not write index"));
3689         free((void *)desc.buffer);
3690
3691         if (!ret)
3692                 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3693                                                 len, name), "HEAD", &oid,
3694                                  NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3695
3696         strbuf_release(&ref_name);
3697         return ret;
3698 }
3699
3700 static struct commit *lookup_label(const char *label, int len,
3701                                    struct strbuf *buf)
3702 {
3703         struct commit *commit;
3704
3705         strbuf_reset(buf);
3706         strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3707         commit = lookup_commit_reference_by_name(buf->buf);
3708         if (!commit) {
3709                 /* fall back to non-rewritten ref or commit */
3710                 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3711                 commit = lookup_commit_reference_by_name(buf->buf);
3712         }
3713
3714         if (!commit)
3715                 error(_("could not resolve '%s'"), buf->buf);
3716
3717         return commit;
3718 }
3719
3720 static int do_merge(struct repository *r,
3721                     struct commit *commit,
3722                     const char *arg, int arg_len,
3723                     int flags, struct replay_opts *opts)
3724 {
3725         int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3726                 EDIT_MSG | VERIFY_MSG : 0;
3727         struct strbuf ref_name = STRBUF_INIT;
3728         struct commit *head_commit, *merge_commit, *i;
3729         struct commit_list *bases, *j, *reversed = NULL;
3730         struct commit_list *to_merge = NULL, **tail = &to_merge;
3731         const char *strategy = !opts->xopts_nr &&
3732                 (!opts->strategy ||
3733                  !strcmp(opts->strategy, "recursive") ||
3734                  !strcmp(opts->strategy, "ort")) ?
3735                 NULL : opts->strategy;
3736         struct merge_options o;
3737         int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3738         static struct lock_file lock;
3739         const char *p;
3740
3741         if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3742                 ret = -1;
3743                 goto leave_merge;
3744         }
3745
3746         head_commit = lookup_commit_reference_by_name("HEAD");
3747         if (!head_commit) {
3748                 ret = error(_("cannot merge without a current revision"));
3749                 goto leave_merge;
3750         }
3751
3752         /*
3753          * For octopus merges, the arg starts with the list of revisions to be
3754          * merged. The list is optionally followed by '#' and the oneline.
3755          */
3756         merge_arg_len = oneline_offset = arg_len;
3757         for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3758                 if (!*p)
3759                         break;
3760                 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3761                         p += 1 + strspn(p + 1, " \t\n");
3762                         oneline_offset = p - arg;
3763                         break;
3764                 }
3765                 k = strcspn(p, " \t\n");
3766                 if (!k)
3767                         continue;
3768                 merge_commit = lookup_label(p, k, &ref_name);
3769                 if (!merge_commit) {
3770                         ret = error(_("unable to parse '%.*s'"), k, p);
3771                         goto leave_merge;
3772                 }
3773                 tail = &commit_list_insert(merge_commit, tail)->next;
3774                 p += k;
3775                 merge_arg_len = p - arg;
3776         }
3777
3778         if (!to_merge) {
3779                 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3780                 goto leave_merge;
3781         }
3782
3783         if (opts->have_squash_onto &&
3784             oideq(&head_commit->object.oid, &opts->squash_onto)) {
3785                 /*
3786                  * When the user tells us to "merge" something into a
3787                  * "[new root]", let's simply fast-forward to the merge head.
3788                  */
3789                 rollback_lock_file(&lock);
3790                 if (to_merge->next)
3791                         ret = error(_("octopus merge cannot be executed on "
3792                                       "top of a [new root]"));
3793                 else
3794                         ret = fast_forward_to(r, &to_merge->item->object.oid,
3795                                               &head_commit->object.oid, 0,
3796                                               opts);
3797                 goto leave_merge;
3798         }
3799
3800         if (commit) {
3801                 const char *encoding = get_commit_output_encoding();
3802                 const char *message = logmsg_reencode(commit, NULL, encoding);
3803                 const char *body;
3804                 int len;
3805
3806                 if (!message) {
3807                         ret = error(_("could not get commit message of '%s'"),
3808                                     oid_to_hex(&commit->object.oid));
3809                         goto leave_merge;
3810                 }
3811                 write_author_script(message);
3812                 find_commit_subject(message, &body);
3813                 len = strlen(body);
3814                 ret = write_message(body, len, git_path_merge_msg(r), 0);
3815                 unuse_commit_buffer(commit, message);
3816                 if (ret) {
3817                         error_errno(_("could not write '%s'"),
3818                                     git_path_merge_msg(r));
3819                         goto leave_merge;
3820                 }
3821         } else {
3822                 struct strbuf buf = STRBUF_INIT;
3823                 int len;
3824
3825                 strbuf_addf(&buf, "author %s", git_author_info(0));
3826                 write_author_script(buf.buf);
3827                 strbuf_reset(&buf);
3828
3829                 if (oneline_offset < arg_len) {
3830                         p = arg + oneline_offset;
3831                         len = arg_len - oneline_offset;
3832                 } else {
3833                         strbuf_addf(&buf, "Merge %s '%.*s'",
3834                                     to_merge->next ? "branches" : "branch",
3835                                     merge_arg_len, arg);
3836                         p = buf.buf;
3837                         len = buf.len;
3838                 }
3839
3840                 ret = write_message(p, len, git_path_merge_msg(r), 0);
3841                 strbuf_release(&buf);
3842                 if (ret) {
3843                         error_errno(_("could not write '%s'"),
3844                                     git_path_merge_msg(r));
3845                         goto leave_merge;
3846                 }
3847         }
3848
3849         /*
3850          * If HEAD is not identical to the first parent of the original merge
3851          * commit, we cannot fast-forward.
3852          */
3853         can_fast_forward = opts->allow_ff && commit && commit->parents &&
3854                 oideq(&commit->parents->item->object.oid,
3855                       &head_commit->object.oid);
3856
3857         /*
3858          * If any merge head is different from the original one, we cannot
3859          * fast-forward.
3860          */
3861         if (can_fast_forward) {
3862                 struct commit_list *p = commit->parents->next;
3863
3864                 for (j = to_merge; j && p; j = j->next, p = p->next)
3865                         if (!oideq(&j->item->object.oid,
3866                                    &p->item->object.oid)) {
3867                                 can_fast_forward = 0;
3868                                 break;
3869                         }
3870                 /*
3871                  * If the number of merge heads differs from the original merge
3872                  * commit, we cannot fast-forward.
3873                  */
3874                 if (j || p)
3875                         can_fast_forward = 0;
3876         }
3877
3878         if (can_fast_forward) {
3879                 rollback_lock_file(&lock);
3880                 ret = fast_forward_to(r, &commit->object.oid,
3881                                       &head_commit->object.oid, 0, opts);
3882                 if (flags & TODO_EDIT_MERGE_MSG) {
3883                         run_commit_flags |= AMEND_MSG;
3884                         goto fast_forward_edit;
3885                 }
3886                 goto leave_merge;
3887         }
3888
3889         if (strategy || to_merge->next) {
3890                 /* Octopus merge */
3891                 struct child_process cmd = CHILD_PROCESS_INIT;
3892
3893                 if (read_env_script(&cmd.env_array)) {
3894                         const char *gpg_opt = gpg_sign_opt_quoted(opts);
3895
3896                         ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3897                         goto leave_merge;
3898                 }
3899
3900                 if (opts->committer_date_is_author_date)
3901                         strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3902                                      opts->ignore_date ?
3903                                      "" :
3904                                      author_date_from_env_array(&cmd.env_array));
3905                 if (opts->ignore_date)
3906                         strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3907
3908                 cmd.git_cmd = 1;
3909                 strvec_push(&cmd.args, "merge");
3910                 strvec_push(&cmd.args, "-s");
3911                 if (!strategy)
3912                         strvec_push(&cmd.args, "octopus");
3913                 else {
3914                         strvec_push(&cmd.args, strategy);
3915                         for (k = 0; k < opts->xopts_nr; k++)
3916                                 strvec_pushf(&cmd.args,
3917                                              "-X%s", opts->xopts[k]);
3918                 }
3919                 strvec_push(&cmd.args, "--no-edit");
3920                 strvec_push(&cmd.args, "--no-ff");
3921                 strvec_push(&cmd.args, "--no-log");
3922                 strvec_push(&cmd.args, "--no-stat");
3923                 strvec_push(&cmd.args, "-F");
3924                 strvec_push(&cmd.args, git_path_merge_msg(r));
3925                 if (opts->gpg_sign)
3926                         strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3927                 else
3928                         strvec_push(&cmd.args, "--no-gpg-sign");
3929
3930                 /* Add the tips to be merged */
3931                 for (j = to_merge; j; j = j->next)
3932                         strvec_push(&cmd.args,
3933                                     oid_to_hex(&j->item->object.oid));
3934
3935                 strbuf_release(&ref_name);
3936                 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3937                                 NULL, 0);
3938                 rollback_lock_file(&lock);
3939
3940                 ret = run_command(&cmd);
3941
3942                 /* force re-reading of the cache */
3943                 if (!ret && (discard_index(r->index) < 0 ||
3944                              repo_read_index(r) < 0))
3945                         ret = error(_("could not read index"));
3946                 goto leave_merge;
3947         }
3948
3949         merge_commit = to_merge->item;
3950         bases = get_merge_bases(head_commit, merge_commit);
3951         if (bases && oideq(&merge_commit->object.oid,
3952                            &bases->item->object.oid)) {
3953                 ret = 0;
3954                 /* skip merging an ancestor of HEAD */
3955                 goto leave_merge;
3956         }
3957
3958         write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3959                       git_path_merge_head(r), 0);
3960         write_message("no-ff", 5, git_path_merge_mode(r), 0);
3961
3962         for (j = bases; j; j = j->next)
3963                 commit_list_insert(j->item, &reversed);
3964         free_commit_list(bases);
3965
3966         repo_read_index(r);
3967         init_merge_options(&o, r);
3968         o.branch1 = "HEAD";
3969         o.branch2 = ref_name.buf;
3970         o.buffer_output = 2;
3971
3972         if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3973                 /*
3974                  * TODO: Should use merge_incore_recursive() and
3975                  * merge_switch_to_result(), skipping the call to
3976                  * merge_switch_to_result() when we don't actually need to
3977                  * update the index and working copy immediately.
3978                  */
3979                 ret = merge_ort_recursive(&o,
3980                                           head_commit, merge_commit, reversed,
3981                                           &i);
3982         } else {
3983                 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
3984                                       &i);
3985         }
3986         if (ret <= 0)
3987                 fputs(o.obuf.buf, stdout);
3988         strbuf_release(&o.obuf);
3989         if (ret < 0) {
3990                 error(_("could not even attempt to merge '%.*s'"),
3991                       merge_arg_len, arg);
3992                 goto leave_merge;
3993         }
3994         /*
3995          * The return value of merge_recursive() is 1 on clean, and 0 on
3996          * unclean merge.
3997          *
3998          * Let's reverse that, so that do_merge() returns 0 upon success and
3999          * 1 upon failed merge (keeping the return value -1 for the cases where
4000          * we will want to reschedule the `merge` command).
4001          */
4002         ret = !ret;
4003
4004         if (r->index->cache_changed &&
4005             write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4006                 ret = error(_("merge: Unable to write new index file"));
4007                 goto leave_merge;
4008         }
4009
4010         rollback_lock_file(&lock);
4011         if (ret)
4012                 repo_rerere(r, opts->allow_rerere_auto);
4013         else
4014                 /*
4015                  * In case of problems, we now want to return a positive
4016                  * value (a negative one would indicate that the `merge`
4017                  * command needs to be rescheduled).
4018                  */
4019         fast_forward_edit:
4020                 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4021                                        run_commit_flags);
4022
4023 leave_merge:
4024         strbuf_release(&ref_name);
4025         rollback_lock_file(&lock);
4026         free_commit_list(to_merge);
4027         return ret;
4028 }
4029
4030 static int is_final_fixup(struct todo_list *todo_list)
4031 {
4032         int i = todo_list->current;
4033
4034         if (!is_fixup(todo_list->items[i].command))
4035                 return 0;
4036
4037         while (++i < todo_list->nr)
4038                 if (is_fixup(todo_list->items[i].command))
4039                         return 0;
4040                 else if (!is_noop(todo_list->items[i].command))
4041                         break;
4042         return 1;
4043 }
4044
4045 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4046 {
4047         int i;
4048
4049         for (i = todo_list->current + offset; i < todo_list->nr; i++)
4050                 if (!is_noop(todo_list->items[i].command))
4051                         return todo_list->items[i].command;
4052
4053         return -1;
4054 }
4055
4056 void create_autostash(struct repository *r, const char *path,
4057                       const char *default_reflog_action)
4058 {
4059         struct strbuf buf = STRBUF_INIT;
4060         struct lock_file lock_file = LOCK_INIT;
4061         int fd;
4062
4063         fd = repo_hold_locked_index(r, &lock_file, 0);
4064         refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4065         if (0 <= fd)
4066                 repo_update_index_if_able(r, &lock_file);
4067         rollback_lock_file(&lock_file);
4068
4069         if (has_unstaged_changes(r, 1) ||
4070             has_uncommitted_changes(r, 1)) {
4071                 struct child_process stash = CHILD_PROCESS_INIT;
4072                 struct object_id oid;
4073
4074                 strvec_pushl(&stash.args,
4075                              "stash", "create", "autostash", NULL);
4076                 stash.git_cmd = 1;
4077                 stash.no_stdin = 1;
4078                 strbuf_reset(&buf);
4079                 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4080                         die(_("Cannot autostash"));
4081                 strbuf_trim_trailing_newline(&buf);
4082                 if (get_oid(buf.buf, &oid))
4083                         die(_("Unexpected stash response: '%s'"),
4084                             buf.buf);
4085                 strbuf_reset(&buf);
4086                 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4087
4088                 if (safe_create_leading_directories_const(path))
4089                         die(_("Could not create directory for '%s'"),
4090                             path);
4091                 write_file(path, "%s", oid_to_hex(&oid));
4092                 printf(_("Created autostash: %s\n"), buf.buf);
4093                 if (reset_head(r, NULL, "reset --hard",
4094                                NULL, RESET_HEAD_HARD, NULL, NULL,
4095                                default_reflog_action) < 0)
4096                         die(_("could not reset --hard"));
4097
4098                 if (discard_index(r->index) < 0 ||
4099                         repo_read_index(r) < 0)
4100                         die(_("could not read index"));
4101         }
4102         strbuf_release(&buf);
4103 }
4104
4105 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4106 {
4107         struct child_process child = CHILD_PROCESS_INIT;
4108         int ret = 0;
4109
4110         if (attempt_apply) {
4111                 child.git_cmd = 1;
4112                 child.no_stdout = 1;
4113                 child.no_stderr = 1;
4114                 strvec_push(&child.args, "stash");
4115                 strvec_push(&child.args, "apply");
4116                 strvec_push(&child.args, stash_oid);
4117                 ret = run_command(&child);
4118         }
4119
4120         if (attempt_apply && !ret)
4121                 fprintf(stderr, _("Applied autostash.\n"));
4122         else {
4123                 struct child_process store = CHILD_PROCESS_INIT;
4124
4125                 store.git_cmd = 1;
4126                 strvec_push(&store.args, "stash");
4127                 strvec_push(&store.args, "store");
4128                 strvec_push(&store.args, "-m");
4129                 strvec_push(&store.args, "autostash");
4130                 strvec_push(&store.args, "-q");
4131                 strvec_push(&store.args, stash_oid);
4132                 if (run_command(&store))
4133                         ret = error(_("cannot store %s"), stash_oid);
4134                 else
4135                         fprintf(stderr,
4136                                 _("%s\n"
4137                                   "Your changes are safe in the stash.\n"
4138                                   "You can run \"git stash pop\" or"
4139                                   " \"git stash drop\" at any time.\n"),
4140                                 attempt_apply ?
4141                                 _("Applying autostash resulted in conflicts.") :
4142                                 _("Autostash exists; creating a new stash entry."));
4143         }
4144
4145         return ret;
4146 }
4147
4148 static int apply_save_autostash(const char *path, int attempt_apply)
4149 {
4150         struct strbuf stash_oid = STRBUF_INIT;
4151         int ret = 0;
4152
4153         if (!read_oneliner(&stash_oid, path,
4154                            READ_ONELINER_SKIP_IF_EMPTY)) {
4155                 strbuf_release(&stash_oid);
4156                 return 0;
4157         }
4158         strbuf_trim(&stash_oid);
4159
4160         ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4161
4162         unlink(path);
4163         strbuf_release(&stash_oid);
4164         return ret;
4165 }
4166
4167 int save_autostash(const char *path)
4168 {
4169         return apply_save_autostash(path, 0);
4170 }
4171
4172 int apply_autostash(const char *path)
4173 {
4174         return apply_save_autostash(path, 1);
4175 }
4176
4177 int apply_autostash_oid(const char *stash_oid)
4178 {
4179         return apply_save_autostash_oid(stash_oid, 1);
4180 }
4181
4182 static const char *reflog_message(struct replay_opts *opts,
4183         const char *sub_action, const char *fmt, ...)
4184 {
4185         va_list ap;
4186         static struct strbuf buf = STRBUF_INIT;
4187         char *reflog_action = getenv(GIT_REFLOG_ACTION);
4188
4189         va_start(ap, fmt);
4190         strbuf_reset(&buf);
4191         strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
4192         if (sub_action)
4193                 strbuf_addf(&buf, " (%s)", sub_action);
4194         if (fmt) {
4195                 strbuf_addstr(&buf, ": ");
4196                 strbuf_vaddf(&buf, fmt, ap);
4197         }
4198         va_end(ap);
4199
4200         return buf.buf;
4201 }
4202
4203 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4204                             const char *commit, const char *action)
4205 {
4206         struct child_process cmd = CHILD_PROCESS_INIT;
4207         int ret;
4208
4209         cmd.git_cmd = 1;
4210
4211         strvec_push(&cmd.args, "checkout");
4212         strvec_push(&cmd.args, commit);
4213         strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4214
4215         if (opts->verbose)
4216                 ret = run_command(&cmd);
4217         else
4218                 ret = run_command_silent_on_success(&cmd);
4219
4220         if (!ret)
4221                 discard_index(r->index);
4222
4223         return ret;
4224 }
4225
4226 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4227                          const char *onto_name, const struct object_id *onto,
4228                          const struct object_id *orig_head)
4229 {
4230         const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4231
4232         if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4233                 apply_autostash(rebase_path_autostash());
4234                 sequencer_remove_state(opts);
4235                 return error(_("could not detach HEAD"));
4236         }
4237
4238         return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4239 }
4240
4241 static int stopped_at_head(struct repository *r)
4242 {
4243         struct object_id head;
4244         struct commit *commit;
4245         struct commit_message message;
4246
4247         if (get_oid("HEAD", &head) ||
4248             !(commit = lookup_commit(r, &head)) ||
4249             parse_commit(commit) || get_message(commit, &message))
4250                 fprintf(stderr, _("Stopped at HEAD\n"));
4251         else {
4252                 fprintf(stderr, _("Stopped at %s\n"), message.label);
4253                 free_message(commit, &message);
4254         }
4255         return 0;
4256
4257 }
4258
4259 static const char rescheduled_advice[] =
4260 N_("Could not execute the todo command\n"
4261 "\n"
4262 "    %.*s"
4263 "\n"
4264 "It has been rescheduled; To edit the command before continuing, please\n"
4265 "edit the todo list first:\n"
4266 "\n"
4267 "    git rebase --edit-todo\n"
4268 "    git rebase --continue\n");
4269
4270 static int pick_commits(struct repository *r,
4271                         struct todo_list *todo_list,
4272                         struct replay_opts *opts)
4273 {
4274         int res = 0, reschedule = 0;
4275         char *prev_reflog_action;
4276
4277         /* Note that 0 for 3rd parameter of setenv means set only if not set */
4278         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4279         prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4280         if (opts->allow_ff)
4281                 assert(!(opts->signoff || opts->no_commit ||
4282                          opts->record_origin || should_edit(opts) ||
4283                          opts->committer_date_is_author_date ||
4284                          opts->ignore_date));
4285         if (read_and_refresh_cache(r, opts))
4286                 return -1;
4287
4288         while (todo_list->current < todo_list->nr) {
4289                 struct todo_item *item = todo_list->items + todo_list->current;
4290                 const char *arg = todo_item_get_arg(todo_list, item);
4291                 int check_todo = 0;
4292
4293                 if (save_todo(todo_list, opts))
4294                         return -1;
4295                 if (is_rebase_i(opts)) {
4296                         if (item->command != TODO_COMMENT) {
4297                                 FILE *f = fopen(rebase_path_msgnum(), "w");
4298
4299                                 todo_list->done_nr++;
4300
4301                                 if (f) {
4302                                         fprintf(f, "%d\n", todo_list->done_nr);
4303                                         fclose(f);
4304                                 }
4305                                 if (!opts->quiet)
4306                                         fprintf(stderr, _("Rebasing (%d/%d)%s"),
4307                                                 todo_list->done_nr,
4308                                                 todo_list->total_nr,
4309                                                 opts->verbose ? "\n" : "\r");
4310                         }
4311                         unlink(rebase_path_message());
4312                         unlink(rebase_path_author_script());
4313                         unlink(rebase_path_stopped_sha());
4314                         unlink(rebase_path_amend());
4315                         unlink(git_path_merge_head(r));
4316                         unlink(git_path_auto_merge(r));
4317                         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4318
4319                         if (item->command == TODO_BREAK) {
4320                                 if (!opts->verbose)
4321                                         term_clear_line();
4322                                 return stopped_at_head(r);
4323                         }
4324                 }
4325                 if (item->command <= TODO_SQUASH) {
4326                         if (is_rebase_i(opts))
4327                                 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4328                                         command_to_string(item->command), NULL),
4329                                         1);
4330                         res = do_pick_commit(r, item, opts,
4331                                              is_final_fixup(todo_list),
4332                                              &check_todo);
4333                         if (is_rebase_i(opts))
4334                                 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4335                         if (is_rebase_i(opts) && res < 0) {
4336                                 /* Reschedule */
4337                                 advise(_(rescheduled_advice),
4338                                        get_item_line_length(todo_list,
4339                                                             todo_list->current),
4340                                        get_item_line(todo_list,
4341                                                      todo_list->current));
4342                                 todo_list->current--;
4343                                 if (save_todo(todo_list, opts))
4344                                         return -1;
4345                         }
4346                         if (item->command == TODO_EDIT) {
4347                                 struct commit *commit = item->commit;
4348                                 if (!res) {
4349                                         if (!opts->verbose)
4350                                                 term_clear_line();
4351                                         fprintf(stderr,
4352                                                 _("Stopped at %s...  %.*s\n"),
4353                                                 short_commit_name(commit),
4354                                                 item->arg_len, arg);
4355                                 }
4356                                 return error_with_patch(r, commit,
4357                                         arg, item->arg_len, opts, res, !res);
4358                         }
4359                         if (is_rebase_i(opts) && !res)
4360                                 record_in_rewritten(&item->commit->object.oid,
4361                                         peek_command(todo_list, 1));
4362                         if (res && is_fixup(item->command)) {
4363                                 if (res == 1)
4364                                         intend_to_amend();
4365                                 return error_failed_squash(r, item->commit, opts,
4366                                         item->arg_len, arg);
4367                         } else if (res && is_rebase_i(opts) && item->commit) {
4368                                 int to_amend = 0;
4369                                 struct object_id oid;
4370
4371                                 /*
4372                                  * If we are rewording and have either
4373                                  * fast-forwarded already, or are about to
4374                                  * create a new root commit, we want to amend,
4375                                  * otherwise we do not.
4376                                  */
4377                                 if (item->command == TODO_REWORD &&
4378                                     !get_oid("HEAD", &oid) &&
4379                                     (oideq(&item->commit->object.oid, &oid) ||
4380                                      (opts->have_squash_onto &&
4381                                       oideq(&opts->squash_onto, &oid))))
4382                                         to_amend = 1;
4383
4384                                 return res | error_with_patch(r, item->commit,
4385                                                 arg, item->arg_len, opts,
4386                                                 res, to_amend);
4387                         }
4388                 } else if (item->command == TODO_EXEC) {
4389                         char *end_of_arg = (char *)(arg + item->arg_len);
4390                         int saved = *end_of_arg;
4391
4392                         if (!opts->verbose)
4393                                 term_clear_line();
4394                         *end_of_arg = '\0';
4395                         res = do_exec(r, arg);
4396                         *end_of_arg = saved;
4397
4398                         if (res) {
4399                                 if (opts->reschedule_failed_exec)
4400                                         reschedule = 1;
4401                         }
4402                         check_todo = 1;
4403                 } else if (item->command == TODO_LABEL) {
4404                         if ((res = do_label(r, arg, item->arg_len)))
4405                                 reschedule = 1;
4406                 } else if (item->command == TODO_RESET) {
4407                         if ((res = do_reset(r, arg, item->arg_len, opts)))
4408                                 reschedule = 1;
4409                 } else if (item->command == TODO_MERGE) {
4410                         if ((res = do_merge(r, item->commit,
4411                                             arg, item->arg_len,
4412                                             item->flags, opts)) < 0)
4413                                 reschedule = 1;
4414                         else if (item->commit)
4415                                 record_in_rewritten(&item->commit->object.oid,
4416                                                     peek_command(todo_list, 1));
4417                         if (res > 0)
4418                                 /* failed with merge conflicts */
4419                                 return error_with_patch(r, item->commit,
4420                                                         arg, item->arg_len,
4421                                                         opts, res, 0);
4422                 } else if (!is_noop(item->command))
4423                         return error(_("unknown command %d"), item->command);
4424
4425                 if (reschedule) {
4426                         advise(_(rescheduled_advice),
4427                                get_item_line_length(todo_list,
4428                                                     todo_list->current),
4429                                get_item_line(todo_list, todo_list->current));
4430                         todo_list->current--;
4431                         if (save_todo(todo_list, opts))
4432                                 return -1;
4433                         if (item->commit)
4434                                 return error_with_patch(r,
4435                                                         item->commit,
4436                                                         arg, item->arg_len,
4437                                                         opts, res, 0);
4438                 } else if (is_rebase_i(opts) && check_todo && !res) {
4439                         struct stat st;
4440
4441                         if (stat(get_todo_path(opts), &st)) {
4442                                 res = error_errno(_("could not stat '%s'"),
4443                                                   get_todo_path(opts));
4444                         } else if (match_stat_data(&todo_list->stat, &st)) {
4445                                 /* Reread the todo file if it has changed. */
4446                                 todo_list_release(todo_list);
4447                                 if (read_populate_todo(r, todo_list, opts))
4448                                         res = -1; /* message was printed */
4449                                 /* `current` will be incremented below */
4450                                 todo_list->current = -1;
4451                         }
4452                 }
4453
4454                 todo_list->current++;
4455                 if (res)
4456                         return res;
4457         }
4458
4459         if (is_rebase_i(opts)) {
4460                 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4461                 struct stat st;
4462
4463                 /* Stopped in the middle, as planned? */
4464                 if (todo_list->current < todo_list->nr)
4465                         return 0;
4466
4467                 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4468                                 starts_with(head_ref.buf, "refs/")) {
4469                         const char *msg;
4470                         struct object_id head, orig;
4471                         int res;
4472
4473                         if (get_oid("HEAD", &head)) {
4474                                 res = error(_("cannot read HEAD"));
4475 cleanup_head_ref:
4476                                 strbuf_release(&head_ref);
4477                                 strbuf_release(&buf);
4478                                 return res;
4479                         }
4480                         if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4481                                         get_oid_hex(buf.buf, &orig)) {
4482                                 res = error(_("could not read orig-head"));
4483                                 goto cleanup_head_ref;
4484                         }
4485                         strbuf_reset(&buf);
4486                         if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4487                                 res = error(_("could not read 'onto'"));
4488                                 goto cleanup_head_ref;
4489                         }
4490                         msg = reflog_message(opts, "finish", "%s onto %s",
4491                                 head_ref.buf, buf.buf);
4492                         if (update_ref(msg, head_ref.buf, &head, &orig,
4493                                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4494                                 res = error(_("could not update %s"),
4495                                         head_ref.buf);
4496                                 goto cleanup_head_ref;
4497                         }
4498                         msg = reflog_message(opts, "finish", "returning to %s",
4499                                 head_ref.buf);
4500                         if (create_symref("HEAD", head_ref.buf, msg)) {
4501                                 res = error(_("could not update HEAD to %s"),
4502                                         head_ref.buf);
4503                                 goto cleanup_head_ref;
4504                         }
4505                         strbuf_reset(&buf);
4506                 }
4507
4508                 if (opts->verbose) {
4509                         struct rev_info log_tree_opt;
4510                         struct object_id orig, head;
4511
4512                         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4513                         repo_init_revisions(r, &log_tree_opt, NULL);
4514                         log_tree_opt.diff = 1;
4515                         log_tree_opt.diffopt.output_format =
4516                                 DIFF_FORMAT_DIFFSTAT;
4517                         log_tree_opt.disable_stdin = 1;
4518
4519                         if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4520                             !get_oid(buf.buf, &orig) &&
4521                             !get_oid("HEAD", &head)) {
4522                                 diff_tree_oid(&orig, &head, "",
4523                                               &log_tree_opt.diffopt);
4524                                 log_tree_diff_flush(&log_tree_opt);
4525                         }
4526                 }
4527                 flush_rewritten_pending();
4528                 if (!stat(rebase_path_rewritten_list(), &st) &&
4529                                 st.st_size > 0) {
4530                         struct child_process child = CHILD_PROCESS_INIT;
4531                         const char *post_rewrite_hook =
4532                                 find_hook("post-rewrite");
4533
4534                         child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4535                         child.git_cmd = 1;
4536                         strvec_push(&child.args, "notes");
4537                         strvec_push(&child.args, "copy");
4538                         strvec_push(&child.args, "--for-rewrite=rebase");
4539                         /* we don't care if this copying failed */
4540                         run_command(&child);
4541
4542                         if (post_rewrite_hook) {
4543                                 struct child_process hook = CHILD_PROCESS_INIT;
4544
4545                                 hook.in = open(rebase_path_rewritten_list(),
4546                                         O_RDONLY);
4547                                 hook.stdout_to_stderr = 1;
4548                                 hook.trace2_hook_name = "post-rewrite";
4549                                 strvec_push(&hook.args, post_rewrite_hook);
4550                                 strvec_push(&hook.args, "rebase");
4551                                 /* we don't care if this hook failed */
4552                                 run_command(&hook);
4553                         }
4554                 }
4555                 apply_autostash(rebase_path_autostash());
4556
4557                 if (!opts->quiet) {
4558                         if (!opts->verbose)
4559                                 term_clear_line();
4560                         fprintf(stderr,
4561                                 _("Successfully rebased and updated %s.\n"),
4562                                 head_ref.buf);
4563                 }
4564
4565                 strbuf_release(&buf);
4566                 strbuf_release(&head_ref);
4567         }
4568
4569         /*
4570          * Sequence of picks finished successfully; cleanup by
4571          * removing the .git/sequencer directory
4572          */
4573         return sequencer_remove_state(opts);
4574 }
4575
4576 static int continue_single_pick(struct repository *r, struct replay_opts *opts)
4577 {
4578         struct strvec argv = STRVEC_INIT;
4579         int ret;
4580
4581         if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4582             !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4583                 return error(_("no cherry-pick or revert in progress"));
4584
4585         strvec_push(&argv, "commit");
4586
4587         /*
4588          * continue_single_pick() handles the case of recovering from a
4589          * conflict.  should_edit() doesn't handle that case; for a conflict,
4590          * we want to edit if the user asked for it, or if they didn't specify
4591          * and stdin is a tty.
4592          */
4593         if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4594                 /*
4595                  * Include --cleanup=strip as well because we don't want the
4596                  * "# Conflicts:" messages.
4597                  */
4598                 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4599
4600         ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4601         strvec_clear(&argv);
4602         return ret;
4603 }
4604
4605 static int commit_staged_changes(struct repository *r,
4606                                  struct replay_opts *opts,
4607                                  struct todo_list *todo_list)
4608 {
4609         unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4610         unsigned int final_fixup = 0, is_clean;
4611
4612         if (has_unstaged_changes(r, 1))
4613                 return error(_("cannot rebase: You have unstaged changes."));
4614
4615         is_clean = !has_uncommitted_changes(r, 0);
4616
4617         if (file_exists(rebase_path_amend())) {
4618                 struct strbuf rev = STRBUF_INIT;
4619                 struct object_id head, to_amend;
4620
4621                 if (get_oid("HEAD", &head))
4622                         return error(_("cannot amend non-existing commit"));
4623                 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4624                         return error(_("invalid file: '%s'"), rebase_path_amend());
4625                 if (get_oid_hex(rev.buf, &to_amend))
4626                         return error(_("invalid contents: '%s'"),
4627                                 rebase_path_amend());
4628                 if (!is_clean && !oideq(&head, &to_amend))
4629                         return error(_("\nYou have uncommitted changes in your "
4630                                        "working tree. Please, commit them\n"
4631                                        "first and then run 'git rebase "
4632                                        "--continue' again."));
4633                 /*
4634                  * When skipping a failed fixup/squash, we need to edit the
4635                  * commit message, the current fixup list and count, and if it
4636                  * was the last fixup/squash in the chain, we need to clean up
4637                  * the commit message and if there was a squash, let the user
4638                  * edit it.
4639                  */
4640                 if (!is_clean || !opts->current_fixup_count)
4641                         ; /* this is not the final fixup */
4642                 else if (!oideq(&head, &to_amend) ||
4643                          !file_exists(rebase_path_stopped_sha())) {
4644                         /* was a final fixup or squash done manually? */
4645                         if (!is_fixup(peek_command(todo_list, 0))) {
4646                                 unlink(rebase_path_fixup_msg());
4647                                 unlink(rebase_path_squash_msg());
4648                                 unlink(rebase_path_current_fixups());
4649                                 strbuf_reset(&opts->current_fixups);
4650                                 opts->current_fixup_count = 0;
4651                         }
4652                 } else {
4653                         /* we are in a fixup/squash chain */
4654                         const char *p = opts->current_fixups.buf;
4655                         int len = opts->current_fixups.len;
4656
4657                         opts->current_fixup_count--;
4658                         if (!len)
4659                                 BUG("Incorrect current_fixups:\n%s", p);
4660                         while (len && p[len - 1] != '\n')
4661                                 len--;
4662                         strbuf_setlen(&opts->current_fixups, len);
4663                         if (write_message(p, len, rebase_path_current_fixups(),
4664                                           0) < 0)
4665                                 return error(_("could not write file: '%s'"),
4666                                              rebase_path_current_fixups());
4667
4668                         /*
4669                          * If a fixup/squash in a fixup/squash chain failed, the
4670                          * commit message is already correct, no need to commit
4671                          * it again.
4672                          *
4673                          * Only if it is the final command in the fixup/squash
4674                          * chain, and only if the chain is longer than a single
4675                          * fixup/squash command (which was just skipped), do we
4676                          * actually need to re-commit with a cleaned up commit
4677                          * message.
4678                          */
4679                         if (opts->current_fixup_count > 0 &&
4680                             !is_fixup(peek_command(todo_list, 0))) {
4681                                 final_fixup = 1;
4682                                 /*
4683                                  * If there was not a single "squash" in the
4684                                  * chain, we only need to clean up the commit
4685                                  * message, no need to bother the user with
4686                                  * opening the commit message in the editor.
4687                                  */
4688                                 if (!starts_with(p, "squash ") &&
4689                                     !strstr(p, "\nsquash "))
4690                                         flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4691                         } else if (is_fixup(peek_command(todo_list, 0))) {
4692                                 /*
4693                                  * We need to update the squash message to skip
4694                                  * the latest commit message.
4695                                  */
4696                                 struct commit *commit;
4697                                 const char *path = rebase_path_squash_msg();
4698                                 const char *encoding = get_commit_output_encoding();
4699
4700                                 if (parse_head(r, &commit) ||
4701                                     !(p = logmsg_reencode(commit, NULL, encoding)) ||
4702                                     write_message(p, strlen(p), path, 0)) {
4703                                         unuse_commit_buffer(commit, p);
4704                                         return error(_("could not write file: "
4705                                                        "'%s'"), path);
4706                                 }
4707                                 unuse_commit_buffer(commit, p);
4708                         }
4709                 }
4710
4711                 strbuf_release(&rev);
4712                 flags |= AMEND_MSG;
4713         }
4714
4715         if (is_clean) {
4716                 if (refs_ref_exists(get_main_ref_store(r),
4717                                     "CHERRY_PICK_HEAD") &&
4718                     refs_delete_ref(get_main_ref_store(r), "",
4719                                     "CHERRY_PICK_HEAD", NULL, 0))
4720                         return error(_("could not remove CHERRY_PICK_HEAD"));
4721                 if (!final_fixup)
4722                         return 0;
4723         }
4724
4725         if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4726                            opts, flags))
4727                 return error(_("could not commit staged changes."));
4728         unlink(rebase_path_amend());
4729         unlink(git_path_merge_head(r));
4730         unlink(git_path_auto_merge(r));
4731         if (final_fixup) {
4732                 unlink(rebase_path_fixup_msg());
4733                 unlink(rebase_path_squash_msg());
4734         }
4735         if (opts->current_fixup_count > 0) {
4736                 /*
4737                  * Whether final fixup or not, we just cleaned up the commit
4738                  * message...
4739                  */
4740                 unlink(rebase_path_current_fixups());
4741                 strbuf_reset(&opts->current_fixups);
4742                 opts->current_fixup_count = 0;
4743         }
4744         return 0;
4745 }
4746
4747 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4748 {
4749         struct todo_list todo_list = TODO_LIST_INIT;
4750         int res;
4751
4752         if (read_and_refresh_cache(r, opts))
4753                 return -1;
4754
4755         if (read_populate_opts(opts))
4756                 return -1;
4757         if (is_rebase_i(opts)) {
4758                 if ((res = read_populate_todo(r, &todo_list, opts)))
4759                         goto release_todo_list;
4760
4761                 if (file_exists(rebase_path_dropped())) {
4762                         if ((res = todo_list_check_against_backup(r, &todo_list)))
4763                                 goto release_todo_list;
4764
4765                         unlink(rebase_path_dropped());
4766                 }
4767
4768                 if (commit_staged_changes(r, opts, &todo_list)) {
4769                         res = -1;
4770                         goto release_todo_list;
4771                 }
4772         } else if (!file_exists(get_todo_path(opts)))
4773                 return continue_single_pick(r, opts);
4774         else if ((res = read_populate_todo(r, &todo_list, opts)))
4775                 goto release_todo_list;
4776
4777         if (!is_rebase_i(opts)) {
4778                 /* Verify that the conflict has been resolved */
4779                 if (refs_ref_exists(get_main_ref_store(r),
4780                                     "CHERRY_PICK_HEAD") ||
4781                     refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4782                         res = continue_single_pick(r, opts);
4783                         if (res)
4784                                 goto release_todo_list;
4785                 }
4786                 if (index_differs_from(r, "HEAD", NULL, 0)) {
4787                         res = error_dirty_index(r, opts);
4788                         goto release_todo_list;
4789                 }
4790                 todo_list.current++;
4791         } else if (file_exists(rebase_path_stopped_sha())) {
4792                 struct strbuf buf = STRBUF_INIT;
4793                 struct object_id oid;
4794
4795                 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4796                                   READ_ONELINER_SKIP_IF_EMPTY) &&
4797                     !get_oid_hex(buf.buf, &oid))
4798                         record_in_rewritten(&oid, peek_command(&todo_list, 0));
4799                 strbuf_release(&buf);
4800         }
4801
4802         res = pick_commits(r, &todo_list, opts);
4803 release_todo_list:
4804         todo_list_release(&todo_list);
4805         return res;
4806 }
4807
4808 static int single_pick(struct repository *r,
4809                        struct commit *cmit,
4810                        struct replay_opts *opts)
4811 {
4812         int check_todo;
4813         struct todo_item item;
4814
4815         item.command = opts->action == REPLAY_PICK ?
4816                         TODO_PICK : TODO_REVERT;
4817         item.commit = cmit;
4818
4819         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4820         return do_pick_commit(r, &item, opts, 0, &check_todo);
4821 }
4822
4823 int sequencer_pick_revisions(struct repository *r,
4824                              struct replay_opts *opts)
4825 {
4826         struct todo_list todo_list = TODO_LIST_INIT;
4827         struct object_id oid;
4828         int i, res;
4829
4830         assert(opts->revs);
4831         if (read_and_refresh_cache(r, opts))
4832                 return -1;
4833
4834         for (i = 0; i < opts->revs->pending.nr; i++) {
4835                 struct object_id oid;
4836                 const char *name = opts->revs->pending.objects[i].name;
4837
4838                 /* This happens when using --stdin. */
4839                 if (!strlen(name))
4840                         continue;
4841
4842                 if (!get_oid(name, &oid)) {
4843                         if (!lookup_commit_reference_gently(r, &oid, 1)) {
4844                                 enum object_type type = oid_object_info(r,
4845                                                                         &oid,
4846                                                                         NULL);
4847                                 return error(_("%s: can't cherry-pick a %s"),
4848                                         name, type_name(type));
4849                         }
4850                 } else
4851                         return error(_("%s: bad revision"), name);
4852         }
4853
4854         /*
4855          * If we were called as "git cherry-pick <commit>", just
4856          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4857          * REVERT_HEAD, and don't touch the sequencer state.
4858          * This means it is possible to cherry-pick in the middle
4859          * of a cherry-pick sequence.
4860          */
4861         if (opts->revs->cmdline.nr == 1 &&
4862             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4863             opts->revs->no_walk &&
4864             !opts->revs->cmdline.rev->flags) {
4865                 struct commit *cmit;
4866                 if (prepare_revision_walk(opts->revs))
4867                         return error(_("revision walk setup failed"));
4868                 cmit = get_revision(opts->revs);
4869                 if (!cmit)
4870                         return error(_("empty commit set passed"));
4871                 if (get_revision(opts->revs))
4872                         BUG("unexpected extra commit from walk");
4873                 return single_pick(r, cmit, opts);
4874         }
4875
4876         /*
4877          * Start a new cherry-pick/ revert sequence; but
4878          * first, make sure that an existing one isn't in
4879          * progress
4880          */
4881
4882         if (walk_revs_populate_todo(&todo_list, opts) ||
4883                         create_seq_dir(r) < 0)
4884                 return -1;
4885         if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4886                 return error(_("can't revert as initial commit"));
4887         if (save_head(oid_to_hex(&oid)))
4888                 return -1;
4889         if (save_opts(opts))
4890                 return -1;
4891         update_abort_safety_file();
4892         res = pick_commits(r, &todo_list, opts);
4893         todo_list_release(&todo_list);
4894         return res;
4895 }
4896
4897 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4898 {
4899         unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4900         struct strbuf sob = STRBUF_INIT;
4901         int has_footer;
4902
4903         strbuf_addstr(&sob, sign_off_header);
4904         strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4905         strbuf_addch(&sob, '\n');
4906
4907         if (!ignore_footer)
4908                 strbuf_complete_line(msgbuf);
4909
4910         /*
4911          * If the whole message buffer is equal to the sob, pretend that we
4912          * found a conforming footer with a matching sob
4913          */
4914         if (msgbuf->len - ignore_footer == sob.len &&
4915             !strncmp(msgbuf->buf, sob.buf, sob.len))
4916                 has_footer = 3;
4917         else
4918                 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4919
4920         if (!has_footer) {
4921                 const char *append_newlines = NULL;
4922                 size_t len = msgbuf->len - ignore_footer;
4923
4924                 if (!len) {
4925                         /*
4926                          * The buffer is completely empty.  Leave foom for
4927                          * the title and body to be filled in by the user.
4928                          */
4929                         append_newlines = "\n\n";
4930                 } else if (len == 1) {
4931                         /*
4932                          * Buffer contains a single newline.  Add another
4933                          * so that we leave room for the title and body.
4934                          */
4935                         append_newlines = "\n";
4936                 } else if (msgbuf->buf[len - 2] != '\n') {
4937                         /*
4938                          * Buffer ends with a single newline.  Add another
4939                          * so that there is an empty line between the message
4940                          * body and the sob.
4941                          */
4942                         append_newlines = "\n";
4943                 } /* else, the buffer already ends with two newlines. */
4944
4945                 if (append_newlines)
4946                         strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4947                                 append_newlines, strlen(append_newlines));
4948         }
4949
4950         if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4951                 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4952                                 sob.buf, sob.len);
4953
4954         strbuf_release(&sob);
4955 }
4956
4957 struct labels_entry {
4958         struct hashmap_entry entry;
4959         char label[FLEX_ARRAY];
4960 };
4961
4962 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4963                       const struct hashmap_entry *entry_or_key, const void *key)
4964 {
4965         const struct labels_entry *a, *b;
4966
4967         a = container_of(eptr, const struct labels_entry, entry);
4968         b = container_of(entry_or_key, const struct labels_entry, entry);
4969
4970         return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4971 }
4972
4973 struct string_entry {
4974         struct oidmap_entry entry;
4975         char string[FLEX_ARRAY];
4976 };
4977
4978 struct label_state {
4979         struct oidmap commit2label;
4980         struct hashmap labels;
4981         struct strbuf buf;
4982 };
4983
4984 static const char *label_oid(struct object_id *oid, const char *label,
4985                              struct label_state *state)
4986 {
4987         struct labels_entry *labels_entry;
4988         struct string_entry *string_entry;
4989         struct object_id dummy;
4990         int i;
4991
4992         string_entry = oidmap_get(&state->commit2label, oid);
4993         if (string_entry)
4994                 return string_entry->string;
4995
4996         /*
4997          * For "uninteresting" commits, i.e. commits that are not to be
4998          * rebased, and which can therefore not be labeled, we use a unique
4999          * abbreviation of the commit name. This is slightly more complicated
5000          * than calling find_unique_abbrev() because we also need to make
5001          * sure that the abbreviation does not conflict with any other
5002          * label.
5003          *
5004          * We disallow "interesting" commits to be labeled by a string that
5005          * is a valid full-length hash, to ensure that we always can find an
5006          * abbreviation for any uninteresting commit's names that does not
5007          * clash with any other label.
5008          */
5009         strbuf_reset(&state->buf);
5010         if (!label) {
5011                 char *p;
5012
5013                 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5014                 label = p = state->buf.buf;
5015
5016                 find_unique_abbrev_r(p, oid, default_abbrev);
5017
5018                 /*
5019                  * We may need to extend the abbreviated hash so that there is
5020                  * no conflicting label.
5021                  */
5022                 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5023                         size_t i = strlen(p) + 1;
5024
5025                         oid_to_hex_r(p, oid);
5026                         for (; i < the_hash_algo->hexsz; i++) {
5027                                 char save = p[i];
5028                                 p[i] = '\0';
5029                                 if (!hashmap_get_from_hash(&state->labels,
5030                                                            strihash(p), p))
5031                                         break;
5032                                 p[i] = save;
5033                         }
5034                 }
5035         } else {
5036                 struct strbuf *buf = &state->buf;
5037
5038                 /*
5039                  * Sanitize labels by replacing non-alpha-numeric characters
5040                  * (including white-space ones) by dashes, as they might be
5041                  * illegal in file names (and hence in ref names).
5042                  *
5043                  * Note that we retain non-ASCII UTF-8 characters (identified
5044                  * via the most significant bit). They should be all acceptable
5045                  * in file names. We do not validate the UTF-8 here, that's not
5046                  * the job of this function.
5047                  */
5048                 for (; *label; label++)
5049                         if ((*label & 0x80) || isalnum(*label))
5050                                 strbuf_addch(buf, *label);
5051                         /* avoid leading dash and double-dashes */
5052                         else if (buf->len && buf->buf[buf->len - 1] != '-')
5053                                 strbuf_addch(buf, '-');
5054                 if (!buf->len) {
5055                         strbuf_addstr(buf, "rev-");
5056                         strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5057                 }
5058                 label = buf->buf;
5059
5060                 if ((buf->len == the_hash_algo->hexsz &&
5061                      !get_oid_hex(label, &dummy)) ||
5062                     (buf->len == 1 && *label == '#') ||
5063                     hashmap_get_from_hash(&state->labels,
5064                                           strihash(label), label)) {
5065                         /*
5066                          * If the label already exists, or if the label is a
5067                          * valid full OID, or the label is a '#' (which we use
5068                          * as a separator between merge heads and oneline), we
5069                          * append a dash and a number to make it unique.
5070                          */
5071                         size_t len = buf->len;
5072
5073                         for (i = 2; ; i++) {
5074                                 strbuf_setlen(buf, len);
5075                                 strbuf_addf(buf, "-%d", i);
5076                                 if (!hashmap_get_from_hash(&state->labels,
5077                                                            strihash(buf->buf),
5078                                                            buf->buf))
5079                                         break;
5080                         }
5081
5082                         label = buf->buf;
5083                 }
5084         }
5085
5086         FLEX_ALLOC_STR(labels_entry, label, label);
5087         hashmap_entry_init(&labels_entry->entry, strihash(label));
5088         hashmap_add(&state->labels, &labels_entry->entry);
5089
5090         FLEX_ALLOC_STR(string_entry, string, label);
5091         oidcpy(&string_entry->entry.oid, oid);
5092         oidmap_put(&state->commit2label, string_entry);
5093
5094         return string_entry->string;
5095 }
5096
5097 static int make_script_with_merges(struct pretty_print_context *pp,
5098                                    struct rev_info *revs, struct strbuf *out,
5099                                    unsigned flags)
5100 {
5101         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5102         int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5103         int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5104         struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5105         struct strbuf label = STRBUF_INIT;
5106         struct commit_list *commits = NULL, **tail = &commits, *iter;
5107         struct commit_list *tips = NULL, **tips_tail = &tips;
5108         struct commit *commit;
5109         struct oidmap commit2todo = OIDMAP_INIT;
5110         struct string_entry *entry;
5111         struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5112                 shown = OIDSET_INIT;
5113         struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5114
5115         int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5116         const char *cmd_pick = abbr ? "p" : "pick",
5117                 *cmd_label = abbr ? "l" : "label",
5118                 *cmd_reset = abbr ? "t" : "reset",
5119                 *cmd_merge = abbr ? "m" : "merge";
5120
5121         oidmap_init(&commit2todo, 0);
5122         oidmap_init(&state.commit2label, 0);
5123         hashmap_init(&state.labels, labels_cmp, NULL, 0);
5124         strbuf_init(&state.buf, 32);
5125
5126         if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5127                 struct labels_entry *onto_label_entry;
5128                 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5129                 FLEX_ALLOC_STR(entry, string, "onto");
5130                 oidcpy(&entry->entry.oid, oid);
5131                 oidmap_put(&state.commit2label, entry);
5132
5133                 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5134                 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5135                 hashmap_add(&state.labels, &onto_label_entry->entry);
5136         }
5137
5138         /*
5139          * First phase:
5140          * - get onelines for all commits
5141          * - gather all branch tips (i.e. 2nd or later parents of merges)
5142          * - label all branch tips
5143          */
5144         while ((commit = get_revision(revs))) {
5145                 struct commit_list *to_merge;
5146                 const char *p1, *p2;
5147                 struct object_id *oid;
5148                 int is_empty;
5149
5150                 tail = &commit_list_insert(commit, tail)->next;
5151                 oidset_insert(&interesting, &commit->object.oid);
5152
5153                 is_empty = is_original_commit_empty(commit);
5154                 if (!is_empty && (commit->object.flags & PATCHSAME))
5155                         continue;
5156                 if (is_empty && !keep_empty)
5157                         continue;
5158
5159                 strbuf_reset(&oneline);
5160                 pretty_print_commit(pp, commit, &oneline);
5161
5162                 to_merge = commit->parents ? commit->parents->next : NULL;
5163                 if (!to_merge) {
5164                         /* non-merge commit: easy case */
5165                         strbuf_reset(&buf);
5166                         strbuf_addf(&buf, "%s %s %s", cmd_pick,
5167                                     oid_to_hex(&commit->object.oid),
5168                                     oneline.buf);
5169                         if (is_empty)
5170                                 strbuf_addf(&buf, " %c empty",
5171                                             comment_line_char);
5172
5173                         FLEX_ALLOC_STR(entry, string, buf.buf);
5174                         oidcpy(&entry->entry.oid, &commit->object.oid);
5175                         oidmap_put(&commit2todo, entry);
5176
5177                         continue;
5178                 }
5179
5180                 /* Create a label */
5181                 strbuf_reset(&label);
5182                 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5183                     (p1 = strchr(p1, '\'')) &&
5184                     (p2 = strchr(++p1, '\'')))
5185                         strbuf_add(&label, p1, p2 - p1);
5186                 else if (skip_prefix(oneline.buf, "Merge pull request ",
5187                                      &p1) &&
5188                          (p1 = strstr(p1, " from ")))
5189                         strbuf_addstr(&label, p1 + strlen(" from "));
5190                 else
5191                         strbuf_addbuf(&label, &oneline);
5192
5193                 strbuf_reset(&buf);
5194                 strbuf_addf(&buf, "%s -C %s",
5195                             cmd_merge, oid_to_hex(&commit->object.oid));
5196
5197                 /* label the tips of merged branches */
5198                 for (; to_merge; to_merge = to_merge->next) {
5199                         oid = &to_merge->item->object.oid;
5200                         strbuf_addch(&buf, ' ');
5201
5202                         if (!oidset_contains(&interesting, oid)) {
5203                                 strbuf_addstr(&buf, label_oid(oid, NULL,
5204                                                               &state));
5205                                 continue;
5206                         }
5207
5208                         tips_tail = &commit_list_insert(to_merge->item,
5209                                                         tips_tail)->next;
5210
5211                         strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5212                 }
5213                 strbuf_addf(&buf, " # %s", oneline.buf);
5214
5215                 FLEX_ALLOC_STR(entry, string, buf.buf);
5216                 oidcpy(&entry->entry.oid, &commit->object.oid);
5217                 oidmap_put(&commit2todo, entry);
5218         }
5219
5220         /*
5221          * Second phase:
5222          * - label branch points
5223          * - add HEAD to the branch tips
5224          */
5225         for (iter = commits; iter; iter = iter->next) {
5226                 struct commit_list *parent = iter->item->parents;
5227                 for (; parent; parent = parent->next) {
5228                         struct object_id *oid = &parent->item->object.oid;
5229                         if (!oidset_contains(&interesting, oid))
5230                                 continue;
5231                         if (oidset_insert(&child_seen, oid))
5232                                 label_oid(oid, "branch-point", &state);
5233                 }
5234
5235                 /* Add HEAD as implicit "tip of branch" */
5236                 if (!iter->next)
5237                         tips_tail = &commit_list_insert(iter->item,
5238                                                         tips_tail)->next;
5239         }
5240
5241         /*
5242          * Third phase: output the todo list. This is a bit tricky, as we
5243          * want to avoid jumping back and forth between revisions. To
5244          * accomplish that goal, we walk backwards from the branch tips,
5245          * gathering commits not yet shown, reversing the list on the fly,
5246          * then outputting that list (labeling revisions as needed).
5247          */
5248         strbuf_addf(out, "%s onto\n", cmd_label);
5249         for (iter = tips; iter; iter = iter->next) {
5250                 struct commit_list *list = NULL, *iter2;
5251
5252                 commit = iter->item;
5253                 if (oidset_contains(&shown, &commit->object.oid))
5254                         continue;
5255                 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5256
5257                 if (entry)
5258                         strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5259                 else
5260                         strbuf_addch(out, '\n');
5261
5262                 while (oidset_contains(&interesting, &commit->object.oid) &&
5263                        !oidset_contains(&shown, &commit->object.oid)) {
5264                         commit_list_insert(commit, &list);
5265                         if (!commit->parents) {
5266                                 commit = NULL;
5267                                 break;
5268                         }
5269                         commit = commit->parents->item;
5270                 }
5271
5272                 if (!commit)
5273                         strbuf_addf(out, "%s %s\n", cmd_reset,
5274                                     rebase_cousins || root_with_onto ?
5275                                     "onto" : "[new root]");
5276                 else {
5277                         const char *to = NULL;
5278
5279                         entry = oidmap_get(&state.commit2label,
5280                                            &commit->object.oid);
5281                         if (entry)
5282                                 to = entry->string;
5283                         else if (!rebase_cousins)
5284                                 to = label_oid(&commit->object.oid, NULL,
5285                                                &state);
5286
5287                         if (!to || !strcmp(to, "onto"))
5288                                 strbuf_addf(out, "%s onto\n", cmd_reset);
5289                         else {
5290                                 strbuf_reset(&oneline);
5291                                 pretty_print_commit(pp, commit, &oneline);
5292                                 strbuf_addf(out, "%s %s # %s\n",
5293                                             cmd_reset, to, oneline.buf);
5294                         }
5295                 }
5296
5297                 for (iter2 = list; iter2; iter2 = iter2->next) {
5298                         struct object_id *oid = &iter2->item->object.oid;
5299                         entry = oidmap_get(&commit2todo, oid);
5300                         /* only show if not already upstream */
5301                         if (entry)
5302                                 strbuf_addf(out, "%s\n", entry->string);
5303                         entry = oidmap_get(&state.commit2label, oid);
5304                         if (entry)
5305                                 strbuf_addf(out, "%s %s\n",
5306                                             cmd_label, entry->string);
5307                         oidset_insert(&shown, oid);
5308                 }
5309
5310                 free_commit_list(list);
5311         }
5312
5313         free_commit_list(commits);
5314         free_commit_list(tips);
5315
5316         strbuf_release(&label);
5317         strbuf_release(&oneline);
5318         strbuf_release(&buf);
5319
5320         oidmap_free(&commit2todo, 1);
5321         oidmap_free(&state.commit2label, 1);
5322         hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5323         strbuf_release(&state.buf);
5324
5325         return 0;
5326 }
5327
5328 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5329                           const char **argv, unsigned flags)
5330 {
5331         char *format = NULL;
5332         struct pretty_print_context pp = {0};
5333         struct rev_info revs;
5334         struct commit *commit;
5335         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5336         const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5337         int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5338         int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5339
5340         repo_init_revisions(r, &revs, NULL);
5341         revs.verbose_header = 1;
5342         if (!rebase_merges)
5343                 revs.max_parents = 1;
5344         revs.cherry_mark = !reapply_cherry_picks;
5345         revs.limited = 1;
5346         revs.reverse = 1;
5347         revs.right_only = 1;
5348         revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5349         revs.topo_order = 1;
5350
5351         revs.pretty_given = 1;
5352         git_config_get_string("rebase.instructionFormat", &format);
5353         if (!format || !*format) {
5354                 free(format);
5355                 format = xstrdup("%s");
5356         }
5357         get_commit_format(format, &revs);
5358         free(format);
5359         pp.fmt = revs.commit_format;
5360         pp.output_encoding = get_log_output_encoding();
5361
5362         if (setup_revisions(argc, argv, &revs, NULL) > 1)
5363                 return error(_("make_script: unhandled options"));
5364
5365         if (prepare_revision_walk(&revs) < 0)
5366                 return error(_("make_script: error preparing revisions"));
5367
5368         if (rebase_merges)
5369                 return make_script_with_merges(&pp, &revs, out, flags);
5370
5371         while ((commit = get_revision(&revs))) {
5372                 int is_empty = is_original_commit_empty(commit);
5373
5374                 if (!is_empty && (commit->object.flags & PATCHSAME))
5375                         continue;
5376                 if (is_empty && !keep_empty)
5377                         continue;
5378                 strbuf_addf(out, "%s %s ", insn,
5379                             oid_to_hex(&commit->object.oid));
5380                 pretty_print_commit(&pp, commit, out);
5381                 if (is_empty)
5382                         strbuf_addf(out, " %c empty", comment_line_char);
5383                 strbuf_addch(out, '\n');
5384         }
5385         return 0;
5386 }
5387
5388 /*
5389  * Add commands after pick and (series of) squash/fixup commands
5390  * in the todo list.
5391  */
5392 void todo_list_add_exec_commands(struct todo_list *todo_list,
5393                                  struct string_list *commands)
5394 {
5395         struct strbuf *buf = &todo_list->buf;
5396         size_t base_offset = buf->len;
5397         int i, insert, nr = 0, alloc = 0;
5398         struct todo_item *items = NULL, *base_items = NULL;
5399
5400         CALLOC_ARRAY(base_items, commands->nr);
5401         for (i = 0; i < commands->nr; i++) {
5402                 size_t command_len = strlen(commands->items[i].string);
5403
5404                 strbuf_addstr(buf, commands->items[i].string);
5405                 strbuf_addch(buf, '\n');
5406
5407                 base_items[i].command = TODO_EXEC;
5408                 base_items[i].offset_in_buf = base_offset;
5409                 base_items[i].arg_offset = base_offset + strlen("exec ");
5410                 base_items[i].arg_len = command_len - strlen("exec ");
5411
5412                 base_offset += command_len + 1;
5413         }
5414
5415         /*
5416          * Insert <commands> after every pick. Here, fixup/squash chains
5417          * are considered part of the pick, so we insert the commands *after*
5418          * those chains if there are any.
5419          *
5420          * As we insert the exec commands immediately after rearranging
5421          * any fixups and before the user edits the list, a fixup chain
5422          * can never contain comments (any comments are empty picks that
5423          * have been commented out because the user did not specify
5424          * --keep-empty).  So, it is safe to insert an exec command
5425          * without looking at the command following a comment.
5426          */
5427         insert = 0;
5428         for (i = 0; i < todo_list->nr; i++) {
5429                 enum todo_command command = todo_list->items[i].command;
5430                 if (insert && !is_fixup(command)) {
5431                         ALLOC_GROW(items, nr + commands->nr, alloc);
5432                         COPY_ARRAY(items + nr, base_items, commands->nr);
5433                         nr += commands->nr;
5434
5435                         insert = 0;
5436                 }
5437
5438                 ALLOC_GROW(items, nr + 1, alloc);
5439                 items[nr++] = todo_list->items[i];
5440
5441                 if (command == TODO_PICK || command == TODO_MERGE)
5442                         insert = 1;
5443         }
5444
5445         /* insert or append final <commands> */
5446         if (insert || nr == todo_list->nr) {
5447                 ALLOC_GROW(items, nr + commands->nr, alloc);
5448                 COPY_ARRAY(items + nr, base_items, commands->nr);
5449                 nr += commands->nr;
5450         }
5451
5452         free(base_items);
5453         FREE_AND_NULL(todo_list->items);
5454         todo_list->items = items;
5455         todo_list->nr = nr;
5456         todo_list->alloc = alloc;
5457 }
5458
5459 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5460                                 struct strbuf *buf, int num, unsigned flags)
5461 {
5462         struct todo_item *item;
5463         int i, max = todo_list->nr;
5464
5465         if (num > 0 && num < max)
5466                 max = num;
5467
5468         for (item = todo_list->items, i = 0; i < max; i++, item++) {
5469                 char cmd;
5470
5471                 /* if the item is not a command write it and continue */
5472                 if (item->command >= TODO_COMMENT) {
5473                         strbuf_addf(buf, "%.*s\n", item->arg_len,
5474                                     todo_item_get_arg(todo_list, item));
5475                         continue;
5476                 }
5477
5478                 /* add command to the buffer */
5479                 cmd = command_to_char(item->command);
5480                 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5481                         strbuf_addch(buf, cmd);
5482                 else
5483                         strbuf_addstr(buf, command_to_string(item->command));
5484
5485                 /* add commit id */
5486                 if (item->commit) {
5487                         const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5488                                           short_commit_name(item->commit) :
5489                                           oid_to_hex(&item->commit->object.oid);
5490
5491                         if (item->command == TODO_FIXUP) {
5492                                 if (item->flags & TODO_EDIT_FIXUP_MSG)
5493                                         strbuf_addstr(buf, " -c");
5494                                 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5495                                         strbuf_addstr(buf, " -C");
5496                                 }
5497                         }
5498
5499                         if (item->command == TODO_MERGE) {
5500                                 if (item->flags & TODO_EDIT_MERGE_MSG)
5501                                         strbuf_addstr(buf, " -c");
5502                                 else
5503                                         strbuf_addstr(buf, " -C");
5504                         }
5505
5506                         strbuf_addf(buf, " %s", oid);
5507                 }
5508
5509                 /* add all the rest */
5510                 if (!item->arg_len)
5511                         strbuf_addch(buf, '\n');
5512                 else
5513                         strbuf_addf(buf, " %.*s\n", item->arg_len,
5514                                     todo_item_get_arg(todo_list, item));
5515         }
5516 }
5517
5518 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5519                             const char *file, const char *shortrevisions,
5520                             const char *shortonto, int num, unsigned flags)
5521 {
5522         int res;
5523         struct strbuf buf = STRBUF_INIT;
5524
5525         todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5526         if (flags & TODO_LIST_APPEND_TODO_HELP)
5527                 append_todo_help(count_commands(todo_list),
5528                                  shortrevisions, shortonto, &buf);
5529
5530         res = write_message(buf.buf, buf.len, file, 0);
5531         strbuf_release(&buf);
5532
5533         return res;
5534 }
5535
5536 /* skip picking commits whose parents are unchanged */
5537 static int skip_unnecessary_picks(struct repository *r,
5538                                   struct todo_list *todo_list,
5539                                   struct object_id *base_oid)
5540 {
5541         struct object_id *parent_oid;
5542         int i;
5543
5544         for (i = 0; i < todo_list->nr; i++) {
5545                 struct todo_item *item = todo_list->items + i;
5546
5547                 if (item->command >= TODO_NOOP)
5548                         continue;
5549                 if (item->command != TODO_PICK)
5550                         break;
5551                 if (parse_commit(item->commit)) {
5552                         return error(_("could not parse commit '%s'"),
5553                                 oid_to_hex(&item->commit->object.oid));
5554                 }
5555                 if (!item->commit->parents)
5556                         break; /* root commit */
5557                 if (item->commit->parents->next)
5558                         break; /* merge commit */
5559                 parent_oid = &item->commit->parents->item->object.oid;
5560                 if (!oideq(parent_oid, base_oid))
5561                         break;
5562                 oidcpy(base_oid, &item->commit->object.oid);
5563         }
5564         if (i > 0) {
5565                 const char *done_path = rebase_path_done();
5566
5567                 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5568                         error_errno(_("could not write to '%s'"), done_path);
5569                         return -1;
5570                 }
5571
5572                 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5573                 todo_list->nr -= i;
5574                 todo_list->current = 0;
5575                 todo_list->done_nr += i;
5576
5577                 if (is_fixup(peek_command(todo_list, 0)))
5578                         record_in_rewritten(base_oid, peek_command(todo_list, 0));
5579         }
5580
5581         return 0;
5582 }
5583
5584 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5585                     const char *shortrevisions, const char *onto_name,
5586                     struct commit *onto, const struct object_id *orig_head,
5587                     struct string_list *commands, unsigned autosquash,
5588                     struct todo_list *todo_list)
5589 {
5590         char shortonto[GIT_MAX_HEXSZ + 1];
5591         const char *todo_file = rebase_path_todo();
5592         struct todo_list new_todo = TODO_LIST_INIT;
5593         struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5594         struct object_id oid = onto->object.oid;
5595         int res;
5596
5597         find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5598
5599         if (buf->len == 0) {
5600                 struct todo_item *item = append_new_todo(todo_list);
5601                 item->command = TODO_NOOP;
5602                 item->commit = NULL;
5603                 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5604         }
5605
5606         if (autosquash && todo_list_rearrange_squash(todo_list))
5607                 return -1;
5608
5609         if (commands->nr)
5610                 todo_list_add_exec_commands(todo_list, commands);
5611
5612         if (count_commands(todo_list) == 0) {
5613                 apply_autostash(rebase_path_autostash());
5614                 sequencer_remove_state(opts);
5615
5616                 return error(_("nothing to do"));
5617         }
5618
5619         res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5620                              shortonto, flags);
5621         if (res == -1)
5622                 return -1;
5623         else if (res == -2) {
5624                 apply_autostash(rebase_path_autostash());
5625                 sequencer_remove_state(opts);
5626
5627                 return -1;
5628         } else if (res == -3) {
5629                 apply_autostash(rebase_path_autostash());
5630                 sequencer_remove_state(opts);
5631                 todo_list_release(&new_todo);
5632
5633                 return error(_("nothing to do"));
5634         } else if (res == -4) {
5635                 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5636                 todo_list_release(&new_todo);
5637
5638                 return -1;
5639         }
5640
5641         /* Expand the commit IDs */
5642         todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5643         strbuf_swap(&new_todo.buf, &buf2);
5644         strbuf_release(&buf2);
5645         new_todo.total_nr -= new_todo.nr;
5646         if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5647                 BUG("invalid todo list after expanding IDs:\n%s",
5648                     new_todo.buf.buf);
5649
5650         if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5651                 todo_list_release(&new_todo);
5652                 return error(_("could not skip unnecessary pick commands"));
5653         }
5654
5655         if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5656                                     flags & ~(TODO_LIST_SHORTEN_IDS))) {
5657                 todo_list_release(&new_todo);
5658                 return error_errno(_("could not write '%s'"), todo_file);
5659         }
5660
5661         res = -1;
5662
5663         if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5664                 goto cleanup;
5665
5666         if (require_clean_work_tree(r, "rebase", "", 1, 1))
5667                 goto cleanup;
5668
5669         todo_list_write_total_nr(&new_todo);
5670         res = pick_commits(r, &new_todo, opts);
5671
5672 cleanup:
5673         todo_list_release(&new_todo);
5674
5675         return res;
5676 }
5677
5678 struct subject2item_entry {
5679         struct hashmap_entry entry;
5680         int i;
5681         char subject[FLEX_ARRAY];
5682 };
5683
5684 static int subject2item_cmp(const void *fndata,
5685                             const struct hashmap_entry *eptr,
5686                             const struct hashmap_entry *entry_or_key,
5687                             const void *key)
5688 {
5689         const struct subject2item_entry *a, *b;
5690
5691         a = container_of(eptr, const struct subject2item_entry, entry);
5692         b = container_of(entry_or_key, const struct subject2item_entry, entry);
5693
5694         return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5695 }
5696
5697 define_commit_slab(commit_todo_item, struct todo_item *);
5698
5699 static int skip_fixupish(const char *subject, const char **p) {
5700         return skip_prefix(subject, "fixup! ", p) ||
5701                skip_prefix(subject, "amend! ", p) ||
5702                skip_prefix(subject, "squash! ", p);
5703 }
5704
5705 /*
5706  * Rearrange the todo list that has both "pick commit-id msg" and "pick
5707  * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5708  * after the former, and change "pick" to "fixup"/"squash".
5709  *
5710  * Note that if the config has specified a custom instruction format, each log
5711  * message will have to be retrieved from the commit (as the oneline in the
5712  * script cannot be trusted) in order to normalize the autosquash arrangement.
5713  */
5714 int todo_list_rearrange_squash(struct todo_list *todo_list)
5715 {
5716         struct hashmap subject2item;
5717         int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5718         char **subjects;
5719         struct commit_todo_item commit_todo;
5720         struct todo_item *items = NULL;
5721
5722         init_commit_todo_item(&commit_todo);
5723         /*
5724          * The hashmap maps onelines to the respective todo list index.
5725          *
5726          * If any items need to be rearranged, the next[i] value will indicate
5727          * which item was moved directly after the i'th.
5728          *
5729          * In that case, last[i] will indicate the index of the latest item to
5730          * be moved to appear after the i'th.
5731          */
5732         hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5733         ALLOC_ARRAY(next, todo_list->nr);
5734         ALLOC_ARRAY(tail, todo_list->nr);
5735         ALLOC_ARRAY(subjects, todo_list->nr);
5736         for (i = 0; i < todo_list->nr; i++) {
5737                 struct strbuf buf = STRBUF_INIT;
5738                 struct todo_item *item = todo_list->items + i;
5739                 const char *commit_buffer, *subject, *p;
5740                 size_t subject_len;
5741                 int i2 = -1;
5742                 struct subject2item_entry *entry;
5743
5744                 next[i] = tail[i] = -1;
5745                 if (!item->commit || item->command == TODO_DROP) {
5746                         subjects[i] = NULL;
5747                         continue;
5748                 }
5749
5750                 if (is_fixup(item->command)) {
5751                         clear_commit_todo_item(&commit_todo);
5752                         return error(_("the script was already rearranged."));
5753                 }
5754
5755                 *commit_todo_item_at(&commit_todo, item->commit) = item;
5756
5757                 parse_commit(item->commit);
5758                 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5759                 find_commit_subject(commit_buffer, &subject);
5760                 format_subject(&buf, subject, " ");
5761                 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5762                 unuse_commit_buffer(item->commit, commit_buffer);
5763                 if (skip_fixupish(subject, &p)) {
5764                         struct commit *commit2;
5765
5766                         for (;;) {
5767                                 while (isspace(*p))
5768                                         p++;
5769                                 if (!skip_fixupish(p, &p))
5770                                         break;
5771                         }
5772
5773                         entry = hashmap_get_entry_from_hash(&subject2item,
5774                                                 strhash(p), p,
5775                                                 struct subject2item_entry,
5776                                                 entry);
5777                         if (entry)
5778                                 /* found by title */
5779                                 i2 = entry->i;
5780                         else if (!strchr(p, ' ') &&
5781                                  (commit2 =
5782                                   lookup_commit_reference_by_name(p)) &&
5783                                  *commit_todo_item_at(&commit_todo, commit2))
5784                                 /* found by commit name */
5785                                 i2 = *commit_todo_item_at(&commit_todo, commit2)
5786                                         - todo_list->items;
5787                         else {
5788                                 /* copy can be a prefix of the commit subject */
5789                                 for (i2 = 0; i2 < i; i2++)
5790                                         if (subjects[i2] &&
5791                                             starts_with(subjects[i2], p))
5792                                                 break;
5793                                 if (i2 == i)
5794                                         i2 = -1;
5795                         }
5796                 }
5797                 if (i2 >= 0) {
5798                         rearranged = 1;
5799                         if (starts_with(subject, "fixup!")) {
5800                                 todo_list->items[i].command = TODO_FIXUP;
5801                         } else if (starts_with(subject, "amend!")) {
5802                                 todo_list->items[i].command = TODO_FIXUP;
5803                                 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5804                         } else {
5805                                 todo_list->items[i].command = TODO_SQUASH;
5806                         }
5807                         if (tail[i2] < 0) {
5808                                 next[i] = next[i2];
5809                                 next[i2] = i;
5810                         } else {
5811                                 next[i] = next[tail[i2]];
5812                                 next[tail[i2]] = i;
5813                         }
5814                         tail[i2] = i;
5815                 } else if (!hashmap_get_from_hash(&subject2item,
5816                                                 strhash(subject), subject)) {
5817                         FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5818                         entry->i = i;
5819                         hashmap_entry_init(&entry->entry,
5820                                         strhash(entry->subject));
5821                         hashmap_put(&subject2item, &entry->entry);
5822                 }
5823         }
5824
5825         if (rearranged) {
5826                 for (i = 0; i < todo_list->nr; i++) {
5827                         enum todo_command command = todo_list->items[i].command;
5828                         int cur = i;
5829
5830                         /*
5831                          * Initially, all commands are 'pick's. If it is a
5832                          * fixup or a squash now, we have rearranged it.
5833                          */
5834                         if (is_fixup(command))
5835                                 continue;
5836
5837                         while (cur >= 0) {
5838                                 ALLOC_GROW(items, nr + 1, alloc);
5839                                 items[nr++] = todo_list->items[cur];
5840                                 cur = next[cur];
5841                         }
5842                 }
5843
5844                 FREE_AND_NULL(todo_list->items);
5845                 todo_list->items = items;
5846                 todo_list->nr = nr;
5847                 todo_list->alloc = alloc;
5848         }
5849
5850         free(next);
5851         free(tail);
5852         for (i = 0; i < todo_list->nr; i++)
5853                 free(subjects[i]);
5854         free(subjects);
5855         hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5856
5857         clear_commit_todo_item(&commit_todo);
5858
5859         return 0;
5860 }
5861
5862 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5863 {
5864         if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5865                 struct object_id cherry_pick_head, rebase_head;
5866
5867                 if (file_exists(git_path_seq_dir()))
5868                         *whence = FROM_CHERRY_PICK_MULTI;
5869                 if (file_exists(rebase_path()) &&
5870                     !get_oid("REBASE_HEAD", &rebase_head) &&
5871                     !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5872                     oideq(&rebase_head, &cherry_pick_head))
5873                         *whence = FROM_REBASE_PICK;
5874                 else
5875                         *whence = FROM_CHERRY_PICK_SINGLE;
5876
5877                 return 1;
5878         }
5879
5880         return 0;
5881 }