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