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