merge-ort: handle interactions of caching and rename/rename(1to1) cases
[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_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
168 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
169
170 static int git_sequencer_config(const char *k, const char *v, void *cb)
171 {
172         struct replay_opts *opts = cb;
173         int status;
174
175         if (!strcmp(k, "commit.cleanup")) {
176                 const char *s;
177
178                 status = git_config_string(&s, k, v);
179                 if (status)
180                         return status;
181
182                 if (!strcmp(s, "verbatim")) {
183                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
184                         opts->explicit_cleanup = 1;
185                 } else if (!strcmp(s, "whitespace")) {
186                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
187                         opts->explicit_cleanup = 1;
188                 } else if (!strcmp(s, "strip")) {
189                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
190                         opts->explicit_cleanup = 1;
191                 } else if (!strcmp(s, "scissors")) {
192                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
193                         opts->explicit_cleanup = 1;
194                 } else {
195                         warning(_("invalid commit message cleanup mode '%s'"),
196                                   s);
197                 }
198
199                 free((char *)s);
200                 return status;
201         }
202
203         if (!strcmp(k, "commit.gpgsign")) {
204                 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
205                 return 0;
206         }
207
208         if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
209                 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
210                 if (ret == 0) {
211                         /*
212                          * pull.twohead is allowed to be multi-valued; we only
213                          * care about the first value.
214                          */
215                         char *tmp = strchr(opts->default_strategy, ' ');
216                         if (tmp)
217                                 *tmp = '\0';
218                 }
219                 return ret;
220         }
221
222         status = git_gpg_config(k, v, NULL);
223         if (status)
224                 return status;
225
226         return git_diff_basic_config(k, v, NULL);
227 }
228
229 void sequencer_init_config(struct replay_opts *opts)
230 {
231         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
232         git_config(git_sequencer_config, opts);
233 }
234
235 static inline int is_rebase_i(const struct replay_opts *opts)
236 {
237         return opts->action == REPLAY_INTERACTIVE_REBASE;
238 }
239
240 static const char *get_dir(const struct replay_opts *opts)
241 {
242         if (is_rebase_i(opts))
243                 return rebase_path();
244         return git_path_seq_dir();
245 }
246
247 static const char *get_todo_path(const struct replay_opts *opts)
248 {
249         if (is_rebase_i(opts))
250                 return rebase_path_todo();
251         return git_path_todo_file();
252 }
253
254 /*
255  * Returns 0 for non-conforming footer
256  * Returns 1 for conforming footer
257  * Returns 2 when sob exists within conforming footer
258  * Returns 3 when sob exists within conforming footer as last entry
259  */
260 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
261         size_t ignore_footer)
262 {
263         struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
264         struct trailer_info info;
265         size_t i;
266         int found_sob = 0, found_sob_last = 0;
267         char saved_char;
268
269         opts.no_divider = 1;
270
271         if (ignore_footer) {
272                 saved_char = sb->buf[sb->len - ignore_footer];
273                 sb->buf[sb->len - ignore_footer] = '\0';
274         }
275
276         trailer_info_get(&info, sb->buf, &opts);
277
278         if (ignore_footer)
279                 sb->buf[sb->len - ignore_footer] = saved_char;
280
281         if (info.trailer_start == info.trailer_end)
282                 return 0;
283
284         for (i = 0; i < info.trailer_nr; i++)
285                 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
286                         found_sob = 1;
287                         if (i == info.trailer_nr - 1)
288                                 found_sob_last = 1;
289                 }
290
291         trailer_info_release(&info);
292
293         if (found_sob_last)
294                 return 3;
295         if (found_sob)
296                 return 2;
297         return 1;
298 }
299
300 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
301 {
302         static struct strbuf buf = STRBUF_INIT;
303
304         strbuf_reset(&buf);
305         if (opts->gpg_sign)
306                 sq_quotef(&buf, "-S%s", opts->gpg_sign);
307         return buf.buf;
308 }
309
310 int sequencer_remove_state(struct replay_opts *opts)
311 {
312         struct strbuf buf = STRBUF_INIT;
313         int i, ret = 0;
314
315         if (is_rebase_i(opts) &&
316             strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
317                 char *p = buf.buf;
318                 while (*p) {
319                         char *eol = strchr(p, '\n');
320                         if (eol)
321                                 *eol = '\0';
322                         if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
323                                 warning(_("could not delete '%s'"), p);
324                                 ret = -1;
325                         }
326                         if (!eol)
327                                 break;
328                         p = eol + 1;
329                 }
330         }
331
332         free(opts->gpg_sign);
333         free(opts->default_strategy);
334         free(opts->strategy);
335         for (i = 0; i < opts->xopts_nr; i++)
336                 free(opts->xopts[i]);
337         free(opts->xopts);
338         strbuf_release(&opts->current_fixups);
339
340         strbuf_reset(&buf);
341         strbuf_addstr(&buf, get_dir(opts));
342         if (remove_dir_recursively(&buf, 0))
343                 ret = error(_("could not remove '%s'"), buf.buf);
344         strbuf_release(&buf);
345
346         return ret;
347 }
348
349 static const char *action_name(const struct replay_opts *opts)
350 {
351         switch (opts->action) {
352         case REPLAY_REVERT:
353                 return N_("revert");
354         case REPLAY_PICK:
355                 return N_("cherry-pick");
356         case REPLAY_INTERACTIVE_REBASE:
357                 return N_("rebase");
358         }
359         die(_("unknown action: %d"), opts->action);
360 }
361
362 struct commit_message {
363         char *parent_label;
364         char *label;
365         char *subject;
366         const char *message;
367 };
368
369 static const char *short_commit_name(struct commit *commit)
370 {
371         return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
372 }
373
374 static int get_message(struct commit *commit, struct commit_message *out)
375 {
376         const char *abbrev, *subject;
377         int subject_len;
378
379         out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
380         abbrev = short_commit_name(commit);
381
382         subject_len = find_commit_subject(out->message, &subject);
383
384         out->subject = xmemdupz(subject, subject_len);
385         out->label = xstrfmt("%s (%s)", abbrev, out->subject);
386         out->parent_label = xstrfmt("parent of %s", out->label);
387
388         return 0;
389 }
390
391 static void free_message(struct commit *commit, struct commit_message *msg)
392 {
393         free(msg->parent_label);
394         free(msg->label);
395         free(msg->subject);
396         unuse_commit_buffer(commit, msg->message);
397 }
398
399 static void print_advice(struct repository *r, int show_hint,
400                          struct replay_opts *opts)
401 {
402         char *msg = getenv("GIT_CHERRY_PICK_HELP");
403
404         if (msg) {
405                 fprintf(stderr, "%s\n", msg);
406                 /*
407                  * A conflict has occurred but the porcelain
408                  * (typically rebase --interactive) wants to take care
409                  * of the commit itself so remove CHERRY_PICK_HEAD
410                  */
411                 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
412                                 NULL, 0);
413                 return;
414         }
415
416         if (show_hint) {
417                 if (opts->no_commit)
418                         advise(_("after resolving the conflicts, mark the corrected paths\n"
419                                  "with 'git add <paths>' or 'git rm <paths>'"));
420                 else
421                         advise(_("after resolving the conflicts, mark the corrected paths\n"
422                                  "with 'git add <paths>' or 'git rm <paths>'\n"
423                                  "and commit the result with 'git commit'"));
424         }
425 }
426
427 static int write_message(const void *buf, size_t len, const char *filename,
428                          int append_eol)
429 {
430         struct lock_file msg_file = LOCK_INIT;
431
432         int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
433         if (msg_fd < 0)
434                 return error_errno(_("could not lock '%s'"), filename);
435         if (write_in_full(msg_fd, buf, len) < 0) {
436                 error_errno(_("could not write to '%s'"), filename);
437                 rollback_lock_file(&msg_file);
438                 return -1;
439         }
440         if (append_eol && write(msg_fd, "\n", 1) < 0) {
441                 error_errno(_("could not write eol to '%s'"), filename);
442                 rollback_lock_file(&msg_file);
443                 return -1;
444         }
445         if (commit_lock_file(&msg_file) < 0)
446                 return error(_("failed to finalize '%s'"), filename);
447
448         return 0;
449 }
450
451 int read_oneliner(struct strbuf *buf,
452         const char *path, unsigned flags)
453 {
454         int orig_len = buf->len;
455
456         if (strbuf_read_file(buf, path, 0) < 0) {
457                 if ((flags & READ_ONELINER_WARN_MISSING) ||
458                     (errno != ENOENT && errno != ENOTDIR))
459                         warning_errno(_("could not read '%s'"), path);
460                 return 0;
461         }
462
463         if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
464                 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
465                         --buf->len;
466                 buf->buf[buf->len] = '\0';
467         }
468
469         if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
470                 return 0;
471
472         return 1;
473 }
474
475 static struct tree *empty_tree(struct repository *r)
476 {
477         return lookup_tree(r, the_hash_algo->empty_tree);
478 }
479
480 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
481 {
482         if (repo_read_index_unmerged(repo))
483                 return error_resolve_conflict(_(action_name(opts)));
484
485         error(_("your local changes would be overwritten by %s."),
486                 _(action_name(opts)));
487
488         if (advice_commit_before_merge)
489                 advise(_("commit your changes or stash them to proceed."));
490         return -1;
491 }
492
493 static void update_abort_safety_file(void)
494 {
495         struct object_id head;
496
497         /* Do nothing on a single-pick */
498         if (!file_exists(git_path_seq_dir()))
499                 return;
500
501         if (!get_oid("HEAD", &head))
502                 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
503         else
504                 write_file(git_path_abort_safety_file(), "%s", "");
505 }
506
507 static int fast_forward_to(struct repository *r,
508                            const struct object_id *to,
509                            const struct object_id *from,
510                            int unborn,
511                            struct replay_opts *opts)
512 {
513         struct ref_transaction *transaction;
514         struct strbuf sb = STRBUF_INIT;
515         struct strbuf err = STRBUF_INIT;
516
517         repo_read_index(r);
518         if (checkout_fast_forward(r, from, to, 1))
519                 return -1; /* the callee should have complained already */
520
521         strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
522
523         transaction = ref_transaction_begin(&err);
524         if (!transaction ||
525             ref_transaction_update(transaction, "HEAD",
526                                    to, unborn && !is_rebase_i(opts) ?
527                                    &null_oid : from,
528                                    0, sb.buf, &err) ||
529             ref_transaction_commit(transaction, &err)) {
530                 ref_transaction_free(transaction);
531                 error("%s", err.buf);
532                 strbuf_release(&sb);
533                 strbuf_release(&err);
534                 return -1;
535         }
536
537         strbuf_release(&sb);
538         strbuf_release(&err);
539         ref_transaction_free(transaction);
540         update_abort_safety_file();
541         return 0;
542 }
543
544 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
545         int use_editor)
546 {
547         if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
548                 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
549                                     COMMIT_MSG_CLEANUP_SPACE;
550         else if (!strcmp(cleanup_arg, "verbatim"))
551                 return COMMIT_MSG_CLEANUP_NONE;
552         else if (!strcmp(cleanup_arg, "whitespace"))
553                 return COMMIT_MSG_CLEANUP_SPACE;
554         else if (!strcmp(cleanup_arg, "strip"))
555                 return COMMIT_MSG_CLEANUP_ALL;
556         else if (!strcmp(cleanup_arg, "scissors"))
557                 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
558                                     COMMIT_MSG_CLEANUP_SPACE;
559         else
560                 die(_("Invalid cleanup mode %s"), cleanup_arg);
561 }
562
563 /*
564  * NB using int rather than enum cleanup_mode to stop clang's
565  * -Wtautological-constant-out-of-range-compare complaining that the comparison
566  * is always true.
567  */
568 static const char *describe_cleanup_mode(int cleanup_mode)
569 {
570         static const char *modes[] = { "whitespace",
571                                        "verbatim",
572                                        "scissors",
573                                        "strip" };
574
575         if (cleanup_mode < ARRAY_SIZE(modes))
576                 return modes[cleanup_mode];
577
578         BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
579 }
580
581 void append_conflicts_hint(struct index_state *istate,
582         struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
583 {
584         int i;
585
586         if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
587                 strbuf_addch(msgbuf, '\n');
588                 wt_status_append_cut_line(msgbuf);
589                 strbuf_addch(msgbuf, comment_line_char);
590         }
591
592         strbuf_addch(msgbuf, '\n');
593         strbuf_commented_addf(msgbuf, "Conflicts:\n");
594         for (i = 0; i < istate->cache_nr;) {
595                 const struct cache_entry *ce = istate->cache[i++];
596                 if (ce_stage(ce)) {
597                         strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
598                         while (i < istate->cache_nr &&
599                                !strcmp(ce->name, istate->cache[i]->name))
600                                 i++;
601                 }
602         }
603 }
604
605 static int do_recursive_merge(struct repository *r,
606                               struct commit *base, struct commit *next,
607                               const char *base_label, const char *next_label,
608                               struct object_id *head, struct strbuf *msgbuf,
609                               struct replay_opts *opts)
610 {
611         struct merge_options o;
612         struct merge_result result;
613         struct tree *next_tree, *base_tree, *head_tree;
614         int clean, show_output;
615         int i;
616         struct lock_file index_lock = LOCK_INIT;
617
618         if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
619                 return -1;
620
621         repo_read_index(r);
622
623         init_merge_options(&o, r);
624         o.ancestor = base ? base_label : "(empty tree)";
625         o.branch1 = "HEAD";
626         o.branch2 = next ? next_label : "(empty tree)";
627         if (is_rebase_i(opts))
628                 o.buffer_output = 2;
629         o.show_rename_progress = 1;
630
631         head_tree = parse_tree_indirect(head);
632         next_tree = next ? get_commit_tree(next) : empty_tree(r);
633         base_tree = base ? get_commit_tree(base) : empty_tree(r);
634
635         for (i = 0; i < opts->xopts_nr; i++)
636                 parse_merge_opt(&o, opts->xopts[i]);
637
638         if (opts->strategy && !strcmp(opts->strategy, "ort")) {
639                 memset(&result, 0, sizeof(result));
640                 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
641                                             &result);
642                 show_output = !is_rebase_i(opts) || !result.clean;
643                 /*
644                  * TODO: merge_switch_to_result will update index/working tree;
645                  * we only really want to do that if !result.clean || this is
646                  * the final patch to be picked.  But determining this is the
647                  * final patch would take some work, and "head_tree" would need
648                  * to be replace with the tree the index matched before we
649                  * started doing any picks.
650                  */
651                 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
652                 clean = result.clean;
653         } else {
654                 clean = merge_trees(&o, head_tree, next_tree, base_tree);
655                 if (is_rebase_i(opts) && clean <= 0)
656                         fputs(o.obuf.buf, stdout);
657                 strbuf_release(&o.obuf);
658         }
659         if (clean < 0) {
660                 rollback_lock_file(&index_lock);
661                 return clean;
662         }
663
664         if (write_locked_index(r->index, &index_lock,
665                                COMMIT_LOCK | SKIP_IF_UNCHANGED))
666                 /*
667                  * TRANSLATORS: %s will be "revert", "cherry-pick" or
668                  * "rebase".
669                  */
670                 return error(_("%s: Unable to write new index file"),
671                         _(action_name(opts)));
672
673         if (!clean)
674                 append_conflicts_hint(r->index, msgbuf,
675                                       opts->default_msg_cleanup);
676
677         return !clean;
678 }
679
680 static struct object_id *get_cache_tree_oid(struct index_state *istate)
681 {
682         if (!cache_tree_fully_valid(istate->cache_tree))
683                 if (cache_tree_update(istate, 0)) {
684                         error(_("unable to update cache tree"));
685                         return NULL;
686                 }
687
688         return &istate->cache_tree->oid;
689 }
690
691 static int is_index_unchanged(struct repository *r)
692 {
693         struct object_id head_oid, *cache_tree_oid;
694         struct commit *head_commit;
695         struct index_state *istate = r->index;
696
697         if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
698                 return error(_("could not resolve HEAD commit"));
699
700         head_commit = lookup_commit(r, &head_oid);
701
702         /*
703          * If head_commit is NULL, check_commit, called from
704          * lookup_commit, would have indicated that head_commit is not
705          * a commit object already.  parse_commit() will return failure
706          * without further complaints in such a case.  Otherwise, if
707          * the commit is invalid, parse_commit() will complain.  So
708          * there is nothing for us to say here.  Just return failure.
709          */
710         if (parse_commit(head_commit))
711                 return -1;
712
713         if (!(cache_tree_oid = get_cache_tree_oid(istate)))
714                 return -1;
715
716         return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
717 }
718
719 static int write_author_script(const char *message)
720 {
721         struct strbuf buf = STRBUF_INIT;
722         const char *eol;
723         int res;
724
725         for (;;)
726                 if (!*message || starts_with(message, "\n")) {
727 missing_author:
728                         /* Missing 'author' line? */
729                         unlink(rebase_path_author_script());
730                         return 0;
731                 } else if (skip_prefix(message, "author ", &message))
732                         break;
733                 else if ((eol = strchr(message, '\n')))
734                         message = eol + 1;
735                 else
736                         goto missing_author;
737
738         strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
739         while (*message && *message != '\n' && *message != '\r')
740                 if (skip_prefix(message, " <", &message))
741                         break;
742                 else if (*message != '\'')
743                         strbuf_addch(&buf, *(message++));
744                 else
745                         strbuf_addf(&buf, "'\\%c'", *(message++));
746         strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
747         while (*message && *message != '\n' && *message != '\r')
748                 if (skip_prefix(message, "> ", &message))
749                         break;
750                 else if (*message != '\'')
751                         strbuf_addch(&buf, *(message++));
752                 else
753                         strbuf_addf(&buf, "'\\%c'", *(message++));
754         strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
755         while (*message && *message != '\n' && *message != '\r')
756                 if (*message != '\'')
757                         strbuf_addch(&buf, *(message++));
758                 else
759                         strbuf_addf(&buf, "'\\%c'", *(message++));
760         strbuf_addch(&buf, '\'');
761         res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
762         strbuf_release(&buf);
763         return res;
764 }
765
766 /**
767  * Take a series of KEY='VALUE' lines where VALUE part is
768  * sq-quoted, and append <KEY, VALUE> at the end of the string list
769  */
770 static int parse_key_value_squoted(char *buf, struct string_list *list)
771 {
772         while (*buf) {
773                 struct string_list_item *item;
774                 char *np;
775                 char *cp = strchr(buf, '=');
776                 if (!cp) {
777                         np = strchrnul(buf, '\n');
778                         return error(_("no key present in '%.*s'"),
779                                      (int) (np - buf), buf);
780                 }
781                 np = strchrnul(cp, '\n');
782                 *cp++ = '\0';
783                 item = string_list_append(list, buf);
784
785                 buf = np + (*np == '\n');
786                 *np = '\0';
787                 cp = sq_dequote(cp);
788                 if (!cp)
789                         return error(_("unable to dequote value of '%s'"),
790                                      item->string);
791                 item->util = xstrdup(cp);
792         }
793         return 0;
794 }
795
796 /**
797  * Reads and parses the state directory's "author-script" file, and sets name,
798  * email and date accordingly.
799  * Returns 0 on success, -1 if the file could not be parsed.
800  *
801  * The author script is of the format:
802  *
803  *      GIT_AUTHOR_NAME='$author_name'
804  *      GIT_AUTHOR_EMAIL='$author_email'
805  *      GIT_AUTHOR_DATE='$author_date'
806  *
807  * where $author_name, $author_email and $author_date are quoted. We are strict
808  * with our parsing, as the file was meant to be eval'd in the now-removed
809  * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
810  * from what this function expects, it is better to bail out than to do
811  * something that the user does not expect.
812  */
813 int read_author_script(const char *path, char **name, char **email, char **date,
814                        int allow_missing)
815 {
816         struct strbuf buf = STRBUF_INIT;
817         struct string_list kv = STRING_LIST_INIT_DUP;
818         int retval = -1; /* assume failure */
819         int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
820
821         if (strbuf_read_file(&buf, path, 256) <= 0) {
822                 strbuf_release(&buf);
823                 if (errno == ENOENT && allow_missing)
824                         return 0;
825                 else
826                         return error_errno(_("could not open '%s' for reading"),
827                                            path);
828         }
829
830         if (parse_key_value_squoted(buf.buf, &kv))
831                 goto finish;
832
833         for (i = 0; i < kv.nr; i++) {
834                 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
835                         if (name_i != -2)
836                                 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
837                         else
838                                 name_i = i;
839                 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
840                         if (email_i != -2)
841                                 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
842                         else
843                                 email_i = i;
844                 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
845                         if (date_i != -2)
846                                 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
847                         else
848                                 date_i = i;
849                 } else {
850                         err = error(_("unknown variable '%s'"),
851                                     kv.items[i].string);
852                 }
853         }
854         if (name_i == -2)
855                 error(_("missing 'GIT_AUTHOR_NAME'"));
856         if (email_i == -2)
857                 error(_("missing 'GIT_AUTHOR_EMAIL'"));
858         if (date_i == -2)
859                 error(_("missing 'GIT_AUTHOR_DATE'"));
860         if (date_i < 0 || email_i < 0 || date_i < 0 || err)
861                 goto finish;
862         *name = kv.items[name_i].util;
863         *email = kv.items[email_i].util;
864         *date = kv.items[date_i].util;
865         retval = 0;
866 finish:
867         string_list_clear(&kv, !!retval);
868         strbuf_release(&buf);
869         return retval;
870 }
871
872 /*
873  * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
874  * file with shell quoting into struct strvec. Returns -1 on
875  * error, 0 otherwise.
876  */
877 static int read_env_script(struct strvec *env)
878 {
879         char *name, *email, *date;
880
881         if (read_author_script(rebase_path_author_script(),
882                                &name, &email, &date, 0))
883                 return -1;
884
885         strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
886         strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
887         strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
888         free(name);
889         free(email);
890         free(date);
891
892         return 0;
893 }
894
895 static char *get_author(const char *message)
896 {
897         size_t len;
898         const char *a;
899
900         a = find_commit_header(message, "author", &len);
901         if (a)
902                 return xmemdupz(a, len);
903
904         return NULL;
905 }
906
907 static const char *author_date_from_env_array(const struct strvec *env)
908 {
909         int i;
910         const char *date;
911
912         for (i = 0; i < env->nr; i++)
913                 if (skip_prefix(env->v[i],
914                                 "GIT_AUTHOR_DATE=", &date))
915                         return date;
916         /*
917          * If GIT_AUTHOR_DATE is missing we should have already errored out when
918          * reading the script
919          */
920         BUG("GIT_AUTHOR_DATE missing from author script");
921 }
922
923 static const char staged_changes_advice[] =
924 N_("you have staged changes in your working tree\n"
925 "If these changes are meant to be squashed into the previous commit, run:\n"
926 "\n"
927 "  git commit --amend %s\n"
928 "\n"
929 "If they are meant to go into a new commit, run:\n"
930 "\n"
931 "  git commit %s\n"
932 "\n"
933 "In both cases, once you're done, continue with:\n"
934 "\n"
935 "  git rebase --continue\n");
936
937 #define ALLOW_EMPTY (1<<0)
938 #define EDIT_MSG    (1<<1)
939 #define AMEND_MSG   (1<<2)
940 #define CLEANUP_MSG (1<<3)
941 #define VERIFY_MSG  (1<<4)
942 #define CREATE_ROOT_COMMIT (1<<5)
943 #define VERBATIM_MSG (1<<6)
944
945 static int run_command_silent_on_success(struct child_process *cmd)
946 {
947         struct strbuf buf = STRBUF_INIT;
948         int rc;
949
950         cmd->stdout_to_stderr = 1;
951         rc = pipe_command(cmd,
952                           NULL, 0,
953                           NULL, 0,
954                           &buf, 0);
955
956         if (rc)
957                 fputs(buf.buf, stderr);
958         strbuf_release(&buf);
959         return rc;
960 }
961
962 /*
963  * If we are cherry-pick, and if the merge did not result in
964  * hand-editing, we will hit this commit and inherit the original
965  * author date and name.
966  *
967  * If we are revert, or if our cherry-pick results in a hand merge,
968  * we had better say that the current user is responsible for that.
969  *
970  * An exception is when run_git_commit() is called during an
971  * interactive rebase: in that case, we will want to retain the
972  * author metadata.
973  */
974 static int run_git_commit(const char *defmsg,
975                           struct replay_opts *opts,
976                           unsigned int flags)
977 {
978         struct child_process cmd = CHILD_PROCESS_INIT;
979
980         if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
981                 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
982
983         cmd.git_cmd = 1;
984
985         if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
986                 const char *gpg_opt = gpg_sign_opt_quoted(opts);
987
988                 return error(_(staged_changes_advice),
989                              gpg_opt, gpg_opt);
990         }
991
992         if (opts->committer_date_is_author_date)
993                 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
994                              opts->ignore_date ?
995                              "" :
996                              author_date_from_env_array(&cmd.env_array));
997         if (opts->ignore_date)
998                 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
999
1000         strvec_push(&cmd.args, "commit");
1001
1002         if (!(flags & VERIFY_MSG))
1003                 strvec_push(&cmd.args, "-n");
1004         if ((flags & AMEND_MSG))
1005                 strvec_push(&cmd.args, "--amend");
1006         if (opts->gpg_sign)
1007                 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1008         else
1009                 strvec_push(&cmd.args, "--no-gpg-sign");
1010         if (defmsg)
1011                 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1012         else if (!(flags & EDIT_MSG))
1013                 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1014         if ((flags & CLEANUP_MSG))
1015                 strvec_push(&cmd.args, "--cleanup=strip");
1016         if ((flags & VERBATIM_MSG))
1017                 strvec_push(&cmd.args, "--cleanup=verbatim");
1018         if ((flags & EDIT_MSG))
1019                 strvec_push(&cmd.args, "-e");
1020         else if (!(flags & CLEANUP_MSG) &&
1021                  !opts->signoff && !opts->record_origin &&
1022                  !opts->explicit_cleanup)
1023                 strvec_push(&cmd.args, "--cleanup=verbatim");
1024
1025         if ((flags & ALLOW_EMPTY))
1026                 strvec_push(&cmd.args, "--allow-empty");
1027
1028         if (!(flags & EDIT_MSG))
1029                 strvec_push(&cmd.args, "--allow-empty-message");
1030
1031         if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1032                 return run_command_silent_on_success(&cmd);
1033         else
1034                 return run_command(&cmd);
1035 }
1036
1037 static int rest_is_empty(const struct strbuf *sb, int start)
1038 {
1039         int i, eol;
1040         const char *nl;
1041
1042         /* Check if the rest is just whitespace and Signed-off-by's. */
1043         for (i = start; i < sb->len; i++) {
1044                 nl = memchr(sb->buf + i, '\n', sb->len - i);
1045                 if (nl)
1046                         eol = nl - sb->buf;
1047                 else
1048                         eol = sb->len;
1049
1050                 if (strlen(sign_off_header) <= eol - i &&
1051                     starts_with(sb->buf + i, sign_off_header)) {
1052                         i = eol;
1053                         continue;
1054                 }
1055                 while (i < eol)
1056                         if (!isspace(sb->buf[i++]))
1057                                 return 0;
1058         }
1059
1060         return 1;
1061 }
1062
1063 void cleanup_message(struct strbuf *msgbuf,
1064         enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1065 {
1066         if (verbose || /* Truncate the message just before the diff, if any. */
1067             cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1068                 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1069         if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1070                 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1071 }
1072
1073 /*
1074  * Find out if the message in the strbuf contains only whitespace and
1075  * Signed-off-by lines.
1076  */
1077 int message_is_empty(const struct strbuf *sb,
1078                      enum commit_msg_cleanup_mode cleanup_mode)
1079 {
1080         if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1081                 return 0;
1082         return rest_is_empty(sb, 0);
1083 }
1084
1085 /*
1086  * See if the user edited the message in the editor or left what
1087  * was in the template intact
1088  */
1089 int template_untouched(const struct strbuf *sb, const char *template_file,
1090                        enum commit_msg_cleanup_mode cleanup_mode)
1091 {
1092         struct strbuf tmpl = STRBUF_INIT;
1093         const char *start;
1094
1095         if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1096                 return 0;
1097
1098         if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1099                 return 0;
1100
1101         strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1102         if (!skip_prefix(sb->buf, tmpl.buf, &start))
1103                 start = sb->buf;
1104         strbuf_release(&tmpl);
1105         return rest_is_empty(sb, start - sb->buf);
1106 }
1107
1108 int update_head_with_reflog(const struct commit *old_head,
1109                             const struct object_id *new_head,
1110                             const char *action, const struct strbuf *msg,
1111                             struct strbuf *err)
1112 {
1113         struct ref_transaction *transaction;
1114         struct strbuf sb = STRBUF_INIT;
1115         const char *nl;
1116         int ret = 0;
1117
1118         if (action) {
1119                 strbuf_addstr(&sb, action);
1120                 strbuf_addstr(&sb, ": ");
1121         }
1122
1123         nl = strchr(msg->buf, '\n');
1124         if (nl) {
1125                 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1126         } else {
1127                 strbuf_addbuf(&sb, msg);
1128                 strbuf_addch(&sb, '\n');
1129         }
1130
1131         transaction = ref_transaction_begin(err);
1132         if (!transaction ||
1133             ref_transaction_update(transaction, "HEAD", new_head,
1134                                    old_head ? &old_head->object.oid : &null_oid,
1135                                    0, sb.buf, err) ||
1136             ref_transaction_commit(transaction, err)) {
1137                 ret = -1;
1138         }
1139         ref_transaction_free(transaction);
1140         strbuf_release(&sb);
1141
1142         return ret;
1143 }
1144
1145 static int run_rewrite_hook(const struct object_id *oldoid,
1146                             const struct object_id *newoid)
1147 {
1148         struct child_process proc = CHILD_PROCESS_INIT;
1149         const char *argv[3];
1150         int code;
1151         struct strbuf sb = STRBUF_INIT;
1152
1153         argv[0] = find_hook("post-rewrite");
1154         if (!argv[0])
1155                 return 0;
1156
1157         argv[1] = "amend";
1158         argv[2] = NULL;
1159
1160         proc.argv = argv;
1161         proc.in = -1;
1162         proc.stdout_to_stderr = 1;
1163         proc.trace2_hook_name = "post-rewrite";
1164
1165         code = start_command(&proc);
1166         if (code)
1167                 return code;
1168         strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1169         sigchain_push(SIGPIPE, SIG_IGN);
1170         write_in_full(proc.in, sb.buf, sb.len);
1171         close(proc.in);
1172         strbuf_release(&sb);
1173         sigchain_pop(SIGPIPE);
1174         return finish_command(&proc);
1175 }
1176
1177 void commit_post_rewrite(struct repository *r,
1178                          const struct commit *old_head,
1179                          const struct object_id *new_head)
1180 {
1181         struct notes_rewrite_cfg *cfg;
1182
1183         cfg = init_copy_notes_for_rewrite("amend");
1184         if (cfg) {
1185                 /* we are amending, so old_head is not NULL */
1186                 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1187                 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1188         }
1189         run_rewrite_hook(&old_head->object.oid, new_head);
1190 }
1191
1192 static int run_prepare_commit_msg_hook(struct repository *r,
1193                                        struct strbuf *msg,
1194                                        const char *commit)
1195 {
1196         int ret = 0;
1197         const char *name, *arg1 = NULL, *arg2 = NULL;
1198
1199         name = git_path_commit_editmsg();
1200         if (write_message(msg->buf, msg->len, name, 0))
1201                 return -1;
1202
1203         if (commit) {
1204                 arg1 = "commit";
1205                 arg2 = commit;
1206         } else {
1207                 arg1 = "message";
1208         }
1209         if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1210                             arg1, arg2, NULL))
1211                 ret = error(_("'prepare-commit-msg' hook failed"));
1212
1213         return ret;
1214 }
1215
1216 static const char implicit_ident_advice_noconfig[] =
1217 N_("Your name and email address were configured automatically based\n"
1218 "on your username and hostname. Please check that they are accurate.\n"
1219 "You can suppress this message by setting them explicitly. Run the\n"
1220 "following command and follow the instructions in your editor to edit\n"
1221 "your configuration file:\n"
1222 "\n"
1223 "    git config --global --edit\n"
1224 "\n"
1225 "After doing this, you may fix the identity used for this commit with:\n"
1226 "\n"
1227 "    git commit --amend --reset-author\n");
1228
1229 static const char implicit_ident_advice_config[] =
1230 N_("Your name and email address were configured automatically based\n"
1231 "on your username and hostname. Please check that they are accurate.\n"
1232 "You can suppress this message by setting them explicitly:\n"
1233 "\n"
1234 "    git config --global user.name \"Your Name\"\n"
1235 "    git config --global user.email you@example.com\n"
1236 "\n"
1237 "After doing this, you may fix the identity used for this commit with:\n"
1238 "\n"
1239 "    git commit --amend --reset-author\n");
1240
1241 static const char *implicit_ident_advice(void)
1242 {
1243         char *user_config = expand_user_path("~/.gitconfig", 0);
1244         char *xdg_config = xdg_config_home("config");
1245         int config_exists = file_exists(user_config) || file_exists(xdg_config);
1246
1247         free(user_config);
1248         free(xdg_config);
1249
1250         if (config_exists)
1251                 return _(implicit_ident_advice_config);
1252         else
1253                 return _(implicit_ident_advice_noconfig);
1254
1255 }
1256
1257 void print_commit_summary(struct repository *r,
1258                           const char *prefix,
1259                           const struct object_id *oid,
1260                           unsigned int flags)
1261 {
1262         struct rev_info rev;
1263         struct commit *commit;
1264         struct strbuf format = STRBUF_INIT;
1265         const char *head;
1266         struct pretty_print_context pctx = {0};
1267         struct strbuf author_ident = STRBUF_INIT;
1268         struct strbuf committer_ident = STRBUF_INIT;
1269
1270         commit = lookup_commit(r, oid);
1271         if (!commit)
1272                 die(_("couldn't look up newly created commit"));
1273         if (parse_commit(commit))
1274                 die(_("could not parse newly created commit"));
1275
1276         strbuf_addstr(&format, "format:%h] %s");
1277
1278         format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1279         format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1280         if (strbuf_cmp(&author_ident, &committer_ident)) {
1281                 strbuf_addstr(&format, "\n Author: ");
1282                 strbuf_addbuf_percentquote(&format, &author_ident);
1283         }
1284         if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1285                 struct strbuf date = STRBUF_INIT;
1286
1287                 format_commit_message(commit, "%ad", &date, &pctx);
1288                 strbuf_addstr(&format, "\n Date: ");
1289                 strbuf_addbuf_percentquote(&format, &date);
1290                 strbuf_release(&date);
1291         }
1292         if (!committer_ident_sufficiently_given()) {
1293                 strbuf_addstr(&format, "\n Committer: ");
1294                 strbuf_addbuf_percentquote(&format, &committer_ident);
1295                 if (advice_implicit_identity) {
1296                         strbuf_addch(&format, '\n');
1297                         strbuf_addstr(&format, implicit_ident_advice());
1298                 }
1299         }
1300         strbuf_release(&author_ident);
1301         strbuf_release(&committer_ident);
1302
1303         repo_init_revisions(r, &rev, prefix);
1304         setup_revisions(0, NULL, &rev, NULL);
1305
1306         rev.diff = 1;
1307         rev.diffopt.output_format =
1308                 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1309
1310         rev.verbose_header = 1;
1311         rev.show_root_diff = 1;
1312         get_commit_format(format.buf, &rev);
1313         rev.always_show_header = 0;
1314         rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1315         rev.diffopt.break_opt = 0;
1316         diff_setup_done(&rev.diffopt);
1317
1318         head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1319         if (!head)
1320                 die_errno(_("unable to resolve HEAD after creating commit"));
1321         if (!strcmp(head, "HEAD"))
1322                 head = _("detached HEAD");
1323         else
1324                 skip_prefix(head, "refs/heads/", &head);
1325         printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1326                                                 _(" (root-commit)") : "");
1327
1328         if (!log_tree_commit(&rev, commit)) {
1329                 rev.always_show_header = 1;
1330                 rev.use_terminator = 1;
1331                 log_tree_commit(&rev, commit);
1332         }
1333
1334         strbuf_release(&format);
1335 }
1336
1337 static int parse_head(struct repository *r, struct commit **head)
1338 {
1339         struct commit *current_head;
1340         struct object_id oid;
1341
1342         if (get_oid("HEAD", &oid)) {
1343                 current_head = NULL;
1344         } else {
1345                 current_head = lookup_commit_reference(r, &oid);
1346                 if (!current_head)
1347                         return error(_("could not parse HEAD"));
1348                 if (!oideq(&oid, &current_head->object.oid)) {
1349                         warning(_("HEAD %s is not a commit!"),
1350                                 oid_to_hex(&oid));
1351                 }
1352                 if (parse_commit(current_head))
1353                         return error(_("could not parse HEAD commit"));
1354         }
1355         *head = current_head;
1356
1357         return 0;
1358 }
1359
1360 /*
1361  * Try to commit without forking 'git commit'. In some cases we need
1362  * to run 'git commit' to display an error message
1363  *
1364  * Returns:
1365  *  -1 - error unable to commit
1366  *   0 - success
1367  *   1 - run 'git commit'
1368  */
1369 static int try_to_commit(struct repository *r,
1370                          struct strbuf *msg, const char *author,
1371                          struct replay_opts *opts, unsigned int flags,
1372                          struct object_id *oid)
1373 {
1374         struct object_id tree;
1375         struct commit *current_head = NULL;
1376         struct commit_list *parents = NULL;
1377         struct commit_extra_header *extra = NULL;
1378         struct strbuf err = STRBUF_INIT;
1379         struct strbuf commit_msg = STRBUF_INIT;
1380         char *amend_author = NULL;
1381         const char *committer = NULL;
1382         const char *hook_commit = NULL;
1383         enum commit_msg_cleanup_mode cleanup;
1384         int res = 0;
1385
1386         if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1387                 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1388
1389         if (parse_head(r, &current_head))
1390                 return -1;
1391
1392         if (flags & AMEND_MSG) {
1393                 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1394                 const char *out_enc = get_commit_output_encoding();
1395                 const char *message = logmsg_reencode(current_head, NULL,
1396                                                       out_enc);
1397
1398                 if (!msg) {
1399                         const char *orig_message = NULL;
1400
1401                         find_commit_subject(message, &orig_message);
1402                         msg = &commit_msg;
1403                         strbuf_addstr(msg, orig_message);
1404                         hook_commit = "HEAD";
1405                 }
1406                 author = amend_author = get_author(message);
1407                 unuse_commit_buffer(current_head, message);
1408                 if (!author) {
1409                         res = error(_("unable to parse commit author"));
1410                         goto out;
1411                 }
1412                 parents = copy_commit_list(current_head->parents);
1413                 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1414         } else if (current_head &&
1415                    (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1416                 commit_list_insert(current_head, &parents);
1417         }
1418
1419         if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1420                 res = error(_("git write-tree failed to write a tree"));
1421                 goto out;
1422         }
1423
1424         if (!(flags & ALLOW_EMPTY)) {
1425                 struct commit *first_parent = current_head;
1426
1427                 if (flags & AMEND_MSG) {
1428                         if (current_head->parents) {
1429                                 first_parent = current_head->parents->item;
1430                                 if (repo_parse_commit(r, first_parent)) {
1431                                         res = error(_("could not parse HEAD commit"));
1432                                         goto out;
1433                                 }
1434                         } else {
1435                                 first_parent = NULL;
1436                         }
1437                 }
1438                 if (oideq(first_parent
1439                           ? get_commit_tree_oid(first_parent)
1440                           : the_hash_algo->empty_tree,
1441                           &tree)) {
1442                         res = 1; /* run 'git commit' to display error message */
1443                         goto out;
1444                 }
1445         }
1446
1447         if (find_hook("prepare-commit-msg")) {
1448                 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1449                 if (res)
1450                         goto out;
1451                 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1452                                      2048) < 0) {
1453                         res = error_errno(_("unable to read commit message "
1454                                               "from '%s'"),
1455                                             git_path_commit_editmsg());
1456                         goto out;
1457                 }
1458                 msg = &commit_msg;
1459         }
1460
1461         if (flags & CLEANUP_MSG)
1462                 cleanup = COMMIT_MSG_CLEANUP_ALL;
1463         else if (flags & VERBATIM_MSG)
1464                 cleanup = COMMIT_MSG_CLEANUP_NONE;
1465         else if ((opts->signoff || opts->record_origin) &&
1466                  !opts->explicit_cleanup)
1467                 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1468         else
1469                 cleanup = opts->default_msg_cleanup;
1470
1471         if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1472                 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1473         if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1474                 res = 1; /* run 'git commit' to display error message */
1475                 goto out;
1476         }
1477
1478         if (opts->committer_date_is_author_date) {
1479                 struct ident_split id;
1480                 struct strbuf date = STRBUF_INIT;
1481
1482                 if (!opts->ignore_date) {
1483                         if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1484                                 res = error(_("invalid author identity '%s'"),
1485                                             author);
1486                                 goto out;
1487                         }
1488                         if (!id.date_begin) {
1489                                 res = error(_(
1490                                         "corrupt author: missing date information"));
1491                                 goto out;
1492                         }
1493                         strbuf_addf(&date, "@%.*s %.*s",
1494                                     (int)(id.date_end - id.date_begin),
1495                                     id.date_begin,
1496                                     (int)(id.tz_end - id.tz_begin),
1497                                     id.tz_begin);
1498                 } else {
1499                         reset_ident_date();
1500                 }
1501                 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1502                                       getenv("GIT_COMMITTER_EMAIL"),
1503                                       WANT_COMMITTER_IDENT,
1504                                       opts->ignore_date ? NULL : date.buf,
1505                                       IDENT_STRICT);
1506                 strbuf_release(&date);
1507         } else {
1508                 reset_ident_date();
1509         }
1510
1511         if (opts->ignore_date) {
1512                 struct ident_split id;
1513                 char *name, *email;
1514
1515                 if (split_ident_line(&id, author, strlen(author)) < 0) {
1516                         error(_("invalid author identity '%s'"), author);
1517                         goto out;
1518                 }
1519                 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1520                 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1521                 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1522                                    IDENT_STRICT);
1523                 free(name);
1524                 free(email);
1525         }
1526
1527         if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1528                                  author, committer, opts->gpg_sign, extra)) {
1529                 res = error(_("failed to write commit object"));
1530                 goto out;
1531         }
1532
1533         if (update_head_with_reflog(current_head, oid,
1534                                     getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1535                 res = error("%s", err.buf);
1536                 goto out;
1537         }
1538
1539         run_commit_hook(0, r->index_file, "post-commit", NULL);
1540         if (flags & AMEND_MSG)
1541                 commit_post_rewrite(r, current_head, oid);
1542
1543 out:
1544         free_commit_extra_headers(extra);
1545         strbuf_release(&err);
1546         strbuf_release(&commit_msg);
1547         free(amend_author);
1548
1549         return res;
1550 }
1551
1552 static int write_rebase_head(struct object_id *oid)
1553 {
1554         if (update_ref("rebase", "REBASE_HEAD", oid,
1555                        NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1556                 return error(_("could not update %s"), "REBASE_HEAD");
1557
1558         return 0;
1559 }
1560
1561 static int do_commit(struct repository *r,
1562                      const char *msg_file, const char *author,
1563                      struct replay_opts *opts, unsigned int flags,
1564                      struct object_id *oid)
1565 {
1566         int res = 1;
1567
1568         if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1569                 struct object_id oid;
1570                 struct strbuf sb = STRBUF_INIT;
1571
1572                 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1573                         return error_errno(_("unable to read commit message "
1574                                              "from '%s'"),
1575                                            msg_file);
1576
1577                 res = try_to_commit(r, msg_file ? &sb : NULL,
1578                                     author, opts, flags, &oid);
1579                 strbuf_release(&sb);
1580                 if (!res) {
1581                         refs_delete_ref(get_main_ref_store(r), "",
1582                                         "CHERRY_PICK_HEAD", NULL, 0);
1583                         unlink(git_path_merge_msg(r));
1584                         if (!is_rebase_i(opts))
1585                                 print_commit_summary(r, NULL, &oid,
1586                                                 SUMMARY_SHOW_AUTHOR_DATE);
1587                         return res;
1588                 }
1589         }
1590         if (res == 1) {
1591                 if (is_rebase_i(opts) && oid)
1592                         if (write_rebase_head(oid))
1593                             return -1;
1594                 return run_git_commit(msg_file, opts, flags);
1595         }
1596
1597         return res;
1598 }
1599
1600 static int is_original_commit_empty(struct commit *commit)
1601 {
1602         const struct object_id *ptree_oid;
1603
1604         if (parse_commit(commit))
1605                 return error(_("could not parse commit %s"),
1606                              oid_to_hex(&commit->object.oid));
1607         if (commit->parents) {
1608                 struct commit *parent = commit->parents->item;
1609                 if (parse_commit(parent))
1610                         return error(_("could not parse parent commit %s"),
1611                                 oid_to_hex(&parent->object.oid));
1612                 ptree_oid = get_commit_tree_oid(parent);
1613         } else {
1614                 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1615         }
1616
1617         return oideq(ptree_oid, get_commit_tree_oid(commit));
1618 }
1619
1620 /*
1621  * Should empty commits be allowed?  Return status:
1622  *    <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1623  *     0: Halt on empty commit
1624  *     1: Allow empty commit
1625  *     2: Drop empty commit
1626  */
1627 static int allow_empty(struct repository *r,
1628                        struct replay_opts *opts,
1629                        struct commit *commit)
1630 {
1631         int index_unchanged, originally_empty;
1632
1633         /*
1634          * Four cases:
1635          *
1636          * (1) we do not allow empty at all and error out.
1637          *
1638          * (2) we allow ones that were initially empty, and
1639          *     just drop the ones that become empty
1640          *
1641          * (3) we allow ones that were initially empty, but
1642          *     halt for the ones that become empty;
1643          *
1644          * (4) we allow both.
1645          */
1646         if (!opts->allow_empty)
1647                 return 0; /* let "git commit" barf as necessary */
1648
1649         index_unchanged = is_index_unchanged(r);
1650         if (index_unchanged < 0)
1651                 return index_unchanged;
1652         if (!index_unchanged)
1653                 return 0; /* we do not have to say --allow-empty */
1654
1655         if (opts->keep_redundant_commits)
1656                 return 1;
1657
1658         originally_empty = is_original_commit_empty(commit);
1659         if (originally_empty < 0)
1660                 return originally_empty;
1661         if (originally_empty)
1662                 return 1;
1663         else if (opts->drop_redundant_commits)
1664                 return 2;
1665         else
1666                 return 0;
1667 }
1668
1669 static struct {
1670         char c;
1671         const char *str;
1672 } todo_command_info[] = {
1673         { 'p', "pick" },
1674         { 0,   "revert" },
1675         { 'e', "edit" },
1676         { 'r', "reword" },
1677         { 'f', "fixup" },
1678         { 's', "squash" },
1679         { 'x', "exec" },
1680         { 'b', "break" },
1681         { 'l', "label" },
1682         { 't', "reset" },
1683         { 'm', "merge" },
1684         { 0,   "noop" },
1685         { 'd', "drop" },
1686         { 0,   NULL }
1687 };
1688
1689 static const char *command_to_string(const enum todo_command command)
1690 {
1691         if (command < TODO_COMMENT)
1692                 return todo_command_info[command].str;
1693         die(_("unknown command: %d"), command);
1694 }
1695
1696 static char command_to_char(const enum todo_command command)
1697 {
1698         if (command < TODO_COMMENT)
1699                 return todo_command_info[command].c;
1700         return comment_line_char;
1701 }
1702
1703 static int is_noop(const enum todo_command command)
1704 {
1705         return TODO_NOOP <= command;
1706 }
1707
1708 static int is_fixup(enum todo_command command)
1709 {
1710         return command == TODO_FIXUP || command == TODO_SQUASH;
1711 }
1712
1713 /* Does this command create a (non-merge) commit? */
1714 static int is_pick_or_similar(enum todo_command command)
1715 {
1716         switch (command) {
1717         case TODO_PICK:
1718         case TODO_REVERT:
1719         case TODO_EDIT:
1720         case TODO_REWORD:
1721         case TODO_FIXUP:
1722         case TODO_SQUASH:
1723                 return 1;
1724         default:
1725                 return 0;
1726         }
1727 }
1728
1729 static int update_squash_messages(struct repository *r,
1730                                   enum todo_command command,
1731                                   struct commit *commit,
1732                                   struct replay_opts *opts)
1733 {
1734         struct strbuf buf = STRBUF_INIT;
1735         int res;
1736         const char *message, *body;
1737         const char *encoding = get_commit_output_encoding();
1738
1739         if (opts->current_fixup_count > 0) {
1740                 struct strbuf header = STRBUF_INIT;
1741                 char *eol;
1742
1743                 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1744                         return error(_("could not read '%s'"),
1745                                 rebase_path_squash_msg());
1746
1747                 eol = buf.buf[0] != comment_line_char ?
1748                         buf.buf : strchrnul(buf.buf, '\n');
1749
1750                 strbuf_addf(&header, "%c ", comment_line_char);
1751                 strbuf_addf(&header, _("This is a combination of %d commits."),
1752                             opts->current_fixup_count + 2);
1753                 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1754                 strbuf_release(&header);
1755         } else {
1756                 struct object_id head;
1757                 struct commit *head_commit;
1758                 const char *head_message, *body;
1759
1760                 if (get_oid("HEAD", &head))
1761                         return error(_("need a HEAD to fixup"));
1762                 if (!(head_commit = lookup_commit_reference(r, &head)))
1763                         return error(_("could not read HEAD"));
1764                 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1765                         return error(_("could not read HEAD's commit message"));
1766
1767                 find_commit_subject(head_message, &body);
1768                 if (write_message(body, strlen(body),
1769                                   rebase_path_fixup_msg(), 0)) {
1770                         unuse_commit_buffer(head_commit, head_message);
1771                         return error(_("cannot write '%s'"),
1772                                      rebase_path_fixup_msg());
1773                 }
1774
1775                 strbuf_addf(&buf, "%c ", comment_line_char);
1776                 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
1777                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1778                 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1779                 strbuf_addstr(&buf, "\n\n");
1780                 strbuf_addstr(&buf, body);
1781
1782                 unuse_commit_buffer(head_commit, head_message);
1783         }
1784
1785         if (!(message = logmsg_reencode(commit, NULL, encoding)))
1786                 return error(_("could not read commit message of %s"),
1787                              oid_to_hex(&commit->object.oid));
1788         find_commit_subject(message, &body);
1789
1790         if (command == TODO_SQUASH) {
1791                 unlink(rebase_path_fixup_msg());
1792                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1793                 strbuf_addf(&buf, _("This is the commit message #%d:"),
1794                             ++opts->current_fixup_count + 1);
1795                 strbuf_addstr(&buf, "\n\n");
1796                 strbuf_addstr(&buf, body);
1797         } else if (command == TODO_FIXUP) {
1798                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1799                 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1800                             ++opts->current_fixup_count + 1);
1801                 strbuf_addstr(&buf, "\n\n");
1802                 strbuf_add_commented_lines(&buf, body, strlen(body));
1803         } else
1804                 return error(_("unknown command: %d"), command);
1805         unuse_commit_buffer(commit, message);
1806
1807         res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1808         strbuf_release(&buf);
1809
1810         if (!res) {
1811                 strbuf_addf(&opts->current_fixups, "%s%s %s",
1812                             opts->current_fixups.len ? "\n" : "",
1813                             command_to_string(command),
1814                             oid_to_hex(&commit->object.oid));
1815                 res = write_message(opts->current_fixups.buf,
1816                                     opts->current_fixups.len,
1817                                     rebase_path_current_fixups(), 0);
1818         }
1819
1820         return res;
1821 }
1822
1823 static void flush_rewritten_pending(void)
1824 {
1825         struct strbuf buf = STRBUF_INIT;
1826         struct object_id newoid;
1827         FILE *out;
1828
1829         if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1830             !get_oid("HEAD", &newoid) &&
1831             (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1832                 char *bol = buf.buf, *eol;
1833
1834                 while (*bol) {
1835                         eol = strchrnul(bol, '\n');
1836                         fprintf(out, "%.*s %s\n", (int)(eol - bol),
1837                                         bol, oid_to_hex(&newoid));
1838                         if (!*eol)
1839                                 break;
1840                         bol = eol + 1;
1841                 }
1842                 fclose(out);
1843                 unlink(rebase_path_rewritten_pending());
1844         }
1845         strbuf_release(&buf);
1846 }
1847
1848 static void record_in_rewritten(struct object_id *oid,
1849                 enum todo_command next_command)
1850 {
1851         FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1852
1853         if (!out)
1854                 return;
1855
1856         fprintf(out, "%s\n", oid_to_hex(oid));
1857         fclose(out);
1858
1859         if (!is_fixup(next_command))
1860                 flush_rewritten_pending();
1861 }
1862
1863 static int do_pick_commit(struct repository *r,
1864                           enum todo_command command,
1865                           struct commit *commit,
1866                           struct replay_opts *opts,
1867                           int final_fixup, int *check_todo)
1868 {
1869         unsigned int flags = opts->edit ? EDIT_MSG : 0;
1870         const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
1871         struct object_id head;
1872         struct commit *base, *next, *parent;
1873         const char *base_label, *next_label;
1874         char *author = NULL;
1875         struct commit_message msg = { NULL, NULL, NULL, NULL };
1876         struct strbuf msgbuf = STRBUF_INIT;
1877         int res, unborn = 0, reword = 0, allow, drop_commit;
1878
1879         if (opts->no_commit) {
1880                 /*
1881                  * We do not intend to commit immediately.  We just want to
1882                  * merge the differences in, so let's compute the tree
1883                  * that represents the "current" state for merge-recursive
1884                  * to work on.
1885                  */
1886                 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
1887                         return error(_("your index file is unmerged."));
1888         } else {
1889                 unborn = get_oid("HEAD", &head);
1890                 /* Do we want to generate a root commit? */
1891                 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1892                     oideq(&head, &opts->squash_onto)) {
1893                         if (is_fixup(command))
1894                                 return error(_("cannot fixup root commit"));
1895                         flags |= CREATE_ROOT_COMMIT;
1896                         unborn = 1;
1897                 } else if (unborn)
1898                         oidcpy(&head, the_hash_algo->empty_tree);
1899                 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
1900                                        NULL, 0))
1901                         return error_dirty_index(r, opts);
1902         }
1903         discard_index(r->index);
1904
1905         if (!commit->parents)
1906                 parent = NULL;
1907         else if (commit->parents->next) {
1908                 /* Reverting or cherry-picking a merge commit */
1909                 int cnt;
1910                 struct commit_list *p;
1911
1912                 if (!opts->mainline)
1913                         return error(_("commit %s is a merge but no -m option was given."),
1914                                 oid_to_hex(&commit->object.oid));
1915
1916                 for (cnt = 1, p = commit->parents;
1917                      cnt != opts->mainline && p;
1918                      cnt++)
1919                         p = p->next;
1920                 if (cnt != opts->mainline || !p)
1921                         return error(_("commit %s does not have parent %d"),
1922                                 oid_to_hex(&commit->object.oid), opts->mainline);
1923                 parent = p->item;
1924         } else if (1 < opts->mainline)
1925                 /*
1926                  *  Non-first parent explicitly specified as mainline for
1927                  *  non-merge commit
1928                  */
1929                 return error(_("commit %s does not have parent %d"),
1930                              oid_to_hex(&commit->object.oid), opts->mainline);
1931         else
1932                 parent = commit->parents->item;
1933
1934         if (get_message(commit, &msg) != 0)
1935                 return error(_("cannot get commit message for %s"),
1936                         oid_to_hex(&commit->object.oid));
1937
1938         if (opts->allow_ff && !is_fixup(command) &&
1939             ((parent && oideq(&parent->object.oid, &head)) ||
1940              (!parent && unborn))) {
1941                 if (is_rebase_i(opts))
1942                         write_author_script(msg.message);
1943                 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
1944                         opts);
1945                 if (res || command != TODO_REWORD)
1946                         goto leave;
1947                 reword = 1;
1948                 msg_file = NULL;
1949                 goto fast_forward_edit;
1950         }
1951         if (parent && parse_commit(parent) < 0)
1952                 /* TRANSLATORS: The first %s will be a "todo" command like
1953                    "revert" or "pick", the second %s a SHA1. */
1954                 return error(_("%s: cannot parse parent commit %s"),
1955                         command_to_string(command),
1956                         oid_to_hex(&parent->object.oid));
1957
1958         /*
1959          * "commit" is an existing commit.  We would want to apply
1960          * the difference it introduces since its first parent "prev"
1961          * on top of the current HEAD if we are cherry-pick.  Or the
1962          * reverse of it if we are revert.
1963          */
1964
1965         if (command == TODO_REVERT) {
1966                 base = commit;
1967                 base_label = msg.label;
1968                 next = parent;
1969                 next_label = msg.parent_label;
1970                 strbuf_addstr(&msgbuf, "Revert \"");
1971                 strbuf_addstr(&msgbuf, msg.subject);
1972                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1973                 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1974
1975                 if (commit->parents && commit->parents->next) {
1976                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1977                         strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1978                 }
1979                 strbuf_addstr(&msgbuf, ".\n");
1980         } else {
1981                 const char *p;
1982
1983                 base = parent;
1984                 base_label = msg.parent_label;
1985                 next = commit;
1986                 next_label = msg.label;
1987
1988                 /* Append the commit log message to msgbuf. */
1989                 if (find_commit_subject(msg.message, &p))
1990                         strbuf_addstr(&msgbuf, p);
1991
1992                 if (opts->record_origin) {
1993                         strbuf_complete_line(&msgbuf);
1994                         if (!has_conforming_footer(&msgbuf, NULL, 0))
1995                                 strbuf_addch(&msgbuf, '\n');
1996                         strbuf_addstr(&msgbuf, cherry_picked_prefix);
1997                         strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1998                         strbuf_addstr(&msgbuf, ")\n");
1999                 }
2000                 if (!is_fixup(command))
2001                         author = get_author(msg.message);
2002         }
2003
2004         if (command == TODO_REWORD)
2005                 reword = 1;
2006         else if (is_fixup(command)) {
2007                 if (update_squash_messages(r, command, commit, opts))
2008                         return -1;
2009                 flags |= AMEND_MSG;
2010                 if (!final_fixup)
2011                         msg_file = rebase_path_squash_msg();
2012                 else if (file_exists(rebase_path_fixup_msg())) {
2013                         flags |= VERBATIM_MSG;
2014                         msg_file = rebase_path_fixup_msg();
2015                 } else {
2016                         const char *dest = git_path_squash_msg(r);
2017                         unlink(dest);
2018                         if (copy_file(dest, rebase_path_squash_msg(), 0666))
2019                                 return error(_("could not rename '%s' to '%s'"),
2020                                              rebase_path_squash_msg(), dest);
2021                         unlink(git_path_merge_msg(r));
2022                         msg_file = dest;
2023                         flags |= EDIT_MSG;
2024                 }
2025         }
2026
2027         if (opts->signoff && !is_fixup(command))
2028                 append_signoff(&msgbuf, 0, 0);
2029
2030         if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2031                 res = -1;
2032         else if (!opts->strategy ||
2033                  !strcmp(opts->strategy, "recursive") ||
2034                  !strcmp(opts->strategy, "ort") ||
2035                  command == TODO_REVERT) {
2036                 res = do_recursive_merge(r, base, next, base_label, next_label,
2037                                          &head, &msgbuf, opts);
2038                 if (res < 0)
2039                         goto leave;
2040
2041                 res |= write_message(msgbuf.buf, msgbuf.len,
2042                                      git_path_merge_msg(r), 0);
2043         } else {
2044                 struct commit_list *common = NULL;
2045                 struct commit_list *remotes = NULL;
2046
2047                 res = write_message(msgbuf.buf, msgbuf.len,
2048                                     git_path_merge_msg(r), 0);
2049
2050                 commit_list_insert(base, &common);
2051                 commit_list_insert(next, &remotes);
2052                 res |= try_merge_command(r, opts->strategy,
2053                                          opts->xopts_nr, (const char **)opts->xopts,
2054                                         common, oid_to_hex(&head), remotes);
2055                 free_commit_list(common);
2056                 free_commit_list(remotes);
2057         }
2058         strbuf_release(&msgbuf);
2059
2060         /*
2061          * If the merge was clean or if it failed due to conflict, we write
2062          * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2063          * However, if the merge did not even start, then we don't want to
2064          * write it at all.
2065          */
2066         if ((command == TODO_PICK || command == TODO_REWORD ||
2067              command == TODO_EDIT) && !opts->no_commit &&
2068             (res == 0 || res == 1) &&
2069             update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2070                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2071                 res = -1;
2072         if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2073             update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2074                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2075                 res = -1;
2076
2077         if (res) {
2078                 error(command == TODO_REVERT
2079                       ? _("could not revert %s... %s")
2080                       : _("could not apply %s... %s"),
2081                       short_commit_name(commit), msg.subject);
2082                 print_advice(r, res == 1, opts);
2083                 repo_rerere(r, opts->allow_rerere_auto);
2084                 goto leave;
2085         }
2086
2087         drop_commit = 0;
2088         allow = allow_empty(r, opts, commit);
2089         if (allow < 0) {
2090                 res = allow;
2091                 goto leave;
2092         } else if (allow == 1) {
2093                 flags |= ALLOW_EMPTY;
2094         } else if (allow == 2) {
2095                 drop_commit = 1;
2096                 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2097                                 NULL, 0);
2098                 unlink(git_path_merge_msg(r));
2099                 unlink(git_path_auto_merge(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         unlink(git_path_auto_merge(r));
2456
2457         if (!need_cleanup)
2458                 return;
2459
2460         if (!have_finished_the_last_pick())
2461                 return;
2462
2463         sequencer_remove_state(&opts);
2464 }
2465
2466 static void todo_list_write_total_nr(struct todo_list *todo_list)
2467 {
2468         FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2469
2470         if (f) {
2471                 fprintf(f, "%d\n", todo_list->total_nr);
2472                 fclose(f);
2473         }
2474 }
2475
2476 static int read_populate_todo(struct repository *r,
2477                               struct todo_list *todo_list,
2478                               struct replay_opts *opts)
2479 {
2480         struct stat st;
2481         const char *todo_file = get_todo_path(opts);
2482         int res;
2483
2484         strbuf_reset(&todo_list->buf);
2485         if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2486                 return -1;
2487
2488         res = stat(todo_file, &st);
2489         if (res)
2490                 return error(_("could not stat '%s'"), todo_file);
2491         fill_stat_data(&todo_list->stat, &st);
2492
2493         res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2494         if (res) {
2495                 if (is_rebase_i(opts))
2496                         return error(_("please fix this using "
2497                                        "'git rebase --edit-todo'."));
2498                 return error(_("unusable instruction sheet: '%s'"), todo_file);
2499         }
2500
2501         if (!todo_list->nr &&
2502             (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2503                 return error(_("no commits parsed."));
2504
2505         if (!is_rebase_i(opts)) {
2506                 enum todo_command valid =
2507                         opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2508                 int i;
2509
2510                 for (i = 0; i < todo_list->nr; i++)
2511                         if (valid == todo_list->items[i].command)
2512                                 continue;
2513                         else if (valid == TODO_PICK)
2514                                 return error(_("cannot cherry-pick during a revert."));
2515                         else
2516                                 return error(_("cannot revert during a cherry-pick."));
2517         }
2518
2519         if (is_rebase_i(opts)) {
2520                 struct todo_list done = TODO_LIST_INIT;
2521
2522                 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2523                     !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2524                         todo_list->done_nr = count_commands(&done);
2525                 else
2526                         todo_list->done_nr = 0;
2527
2528                 todo_list->total_nr = todo_list->done_nr
2529                         + count_commands(todo_list);
2530                 todo_list_release(&done);
2531
2532                 todo_list_write_total_nr(todo_list);
2533         }
2534
2535         return 0;
2536 }
2537
2538 static int git_config_string_dup(char **dest,
2539                                  const char *var, const char *value)
2540 {
2541         if (!value)
2542                 return config_error_nonbool(var);
2543         free(*dest);
2544         *dest = xstrdup(value);
2545         return 0;
2546 }
2547
2548 static int populate_opts_cb(const char *key, const char *value, void *data)
2549 {
2550         struct replay_opts *opts = data;
2551         int error_flag = 1;
2552
2553         if (!value)
2554                 error_flag = 0;
2555         else if (!strcmp(key, "options.no-commit"))
2556                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2557         else if (!strcmp(key, "options.edit"))
2558                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2559         else if (!strcmp(key, "options.allow-empty"))
2560                 opts->allow_empty =
2561                         git_config_bool_or_int(key, value, &error_flag);
2562         else if (!strcmp(key, "options.allow-empty-message"))
2563                 opts->allow_empty_message =
2564                         git_config_bool_or_int(key, value, &error_flag);
2565         else if (!strcmp(key, "options.keep-redundant-commits"))
2566                 opts->keep_redundant_commits =
2567                         git_config_bool_or_int(key, value, &error_flag);
2568         else if (!strcmp(key, "options.signoff"))
2569                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2570         else if (!strcmp(key, "options.record-origin"))
2571                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2572         else if (!strcmp(key, "options.allow-ff"))
2573                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2574         else if (!strcmp(key, "options.mainline"))
2575                 opts->mainline = git_config_int(key, value);
2576         else if (!strcmp(key, "options.strategy"))
2577                 git_config_string_dup(&opts->strategy, key, value);
2578         else if (!strcmp(key, "options.gpg-sign"))
2579                 git_config_string_dup(&opts->gpg_sign, key, value);
2580         else if (!strcmp(key, "options.strategy-option")) {
2581                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2582                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2583         } else if (!strcmp(key, "options.allow-rerere-auto"))
2584                 opts->allow_rerere_auto =
2585                         git_config_bool_or_int(key, value, &error_flag) ?
2586                                 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2587         else if (!strcmp(key, "options.default-msg-cleanup")) {
2588                 opts->explicit_cleanup = 1;
2589                 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2590         } else
2591                 return error(_("invalid key: %s"), key);
2592
2593         if (!error_flag)
2594                 return error(_("invalid value for %s: %s"), key, value);
2595
2596         return 0;
2597 }
2598
2599 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2600 {
2601         int i;
2602         char *strategy_opts_string = raw_opts;
2603
2604         if (*strategy_opts_string == ' ')
2605                 strategy_opts_string++;
2606
2607         opts->xopts_nr = split_cmdline(strategy_opts_string,
2608                                        (const char ***)&opts->xopts);
2609         for (i = 0; i < opts->xopts_nr; i++) {
2610                 const char *arg = opts->xopts[i];
2611
2612                 skip_prefix(arg, "--", &arg);
2613                 opts->xopts[i] = xstrdup(arg);
2614         }
2615 }
2616
2617 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2618 {
2619         strbuf_reset(buf);
2620         if (!read_oneliner(buf, rebase_path_strategy(), 0))
2621                 return;
2622         opts->strategy = strbuf_detach(buf, NULL);
2623         if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2624                 return;
2625
2626         parse_strategy_opts(opts, buf->buf);
2627 }
2628
2629 static int read_populate_opts(struct replay_opts *opts)
2630 {
2631         if (is_rebase_i(opts)) {
2632                 struct strbuf buf = STRBUF_INIT;
2633                 int ret = 0;
2634
2635                 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2636                                   READ_ONELINER_SKIP_IF_EMPTY)) {
2637                         if (!starts_with(buf.buf, "-S"))
2638                                 strbuf_reset(&buf);
2639                         else {
2640                                 free(opts->gpg_sign);
2641                                 opts->gpg_sign = xstrdup(buf.buf + 2);
2642                         }
2643                         strbuf_reset(&buf);
2644                 }
2645
2646                 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2647                                   READ_ONELINER_SKIP_IF_EMPTY)) {
2648                         if (!strcmp(buf.buf, "--rerere-autoupdate"))
2649                                 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2650                         else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2651                                 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2652                         strbuf_reset(&buf);
2653                 }
2654
2655                 if (file_exists(rebase_path_verbose()))
2656                         opts->verbose = 1;
2657
2658                 if (file_exists(rebase_path_quiet()))
2659                         opts->quiet = 1;
2660
2661                 if (file_exists(rebase_path_signoff())) {
2662                         opts->allow_ff = 0;
2663                         opts->signoff = 1;
2664                 }
2665
2666                 if (file_exists(rebase_path_cdate_is_adate())) {
2667                         opts->allow_ff = 0;
2668                         opts->committer_date_is_author_date = 1;
2669                 }
2670
2671                 if (file_exists(rebase_path_ignore_date())) {
2672                         opts->allow_ff = 0;
2673                         opts->ignore_date = 1;
2674                 }
2675
2676                 if (file_exists(rebase_path_reschedule_failed_exec()))
2677                         opts->reschedule_failed_exec = 1;
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
2779         return 0;
2780 }
2781
2782 static int walk_revs_populate_todo(struct todo_list *todo_list,
2783                                 struct replay_opts *opts)
2784 {
2785         enum todo_command command = opts->action == REPLAY_PICK ?
2786                 TODO_PICK : TODO_REVERT;
2787         const char *command_string = todo_command_info[command].str;
2788         const char *encoding;
2789         struct commit *commit;
2790
2791         if (prepare_revs(opts))
2792                 return -1;
2793
2794         encoding = get_log_output_encoding();
2795
2796         while ((commit = get_revision(opts->revs))) {
2797                 struct todo_item *item = append_new_todo(todo_list);
2798                 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2799                 const char *subject;
2800                 int subject_len;
2801
2802                 item->command = command;
2803                 item->commit = commit;
2804                 item->arg_offset = 0;
2805                 item->arg_len = 0;
2806                 item->offset_in_buf = todo_list->buf.len;
2807                 subject_len = find_commit_subject(commit_buffer, &subject);
2808                 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2809                         short_commit_name(commit), subject_len, subject);
2810                 unuse_commit_buffer(commit, commit_buffer);
2811         }
2812
2813         if (!todo_list->nr)
2814                 return error(_("empty commit set passed"));
2815
2816         return 0;
2817 }
2818
2819 static int create_seq_dir(struct repository *r)
2820 {
2821         enum replay_action action;
2822         const char *in_progress_error = NULL;
2823         const char *in_progress_advice = NULL;
2824         unsigned int advise_skip =
2825                 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
2826                 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
2827
2828         if (!sequencer_get_last_command(r, &action)) {
2829                 switch (action) {
2830                 case REPLAY_REVERT:
2831                         in_progress_error = _("revert is already in progress");
2832                         in_progress_advice =
2833                         _("try \"git revert (--continue | %s--abort | --quit)\"");
2834                         break;
2835                 case REPLAY_PICK:
2836                         in_progress_error = _("cherry-pick is already in progress");
2837                         in_progress_advice =
2838                         _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
2839                         break;
2840                 default:
2841                         BUG("unexpected action in create_seq_dir");
2842                 }
2843         }
2844         if (in_progress_error) {
2845                 error("%s", in_progress_error);
2846                 if (advice_sequencer_in_use)
2847                         advise(in_progress_advice,
2848                                 advise_skip ? "--skip | " : "");
2849                 return -1;
2850         }
2851         if (mkdir(git_path_seq_dir(), 0777) < 0)
2852                 return error_errno(_("could not create sequencer directory '%s'"),
2853                                    git_path_seq_dir());
2854
2855         return 0;
2856 }
2857
2858 static int save_head(const char *head)
2859 {
2860         struct lock_file head_lock = LOCK_INIT;
2861         struct strbuf buf = STRBUF_INIT;
2862         int fd;
2863         ssize_t written;
2864
2865         fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2866         if (fd < 0)
2867                 return error_errno(_("could not lock HEAD"));
2868         strbuf_addf(&buf, "%s\n", head);
2869         written = write_in_full(fd, buf.buf, buf.len);
2870         strbuf_release(&buf);
2871         if (written < 0) {
2872                 error_errno(_("could not write to '%s'"), git_path_head_file());
2873                 rollback_lock_file(&head_lock);
2874                 return -1;
2875         }
2876         if (commit_lock_file(&head_lock) < 0)
2877                 return error(_("failed to finalize '%s'"), git_path_head_file());
2878         return 0;
2879 }
2880
2881 static int rollback_is_safe(void)
2882 {
2883         struct strbuf sb = STRBUF_INIT;
2884         struct object_id expected_head, actual_head;
2885
2886         if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2887                 strbuf_trim(&sb);
2888                 if (get_oid_hex(sb.buf, &expected_head)) {
2889                         strbuf_release(&sb);
2890                         die(_("could not parse %s"), git_path_abort_safety_file());
2891                 }
2892                 strbuf_release(&sb);
2893         }
2894         else if (errno == ENOENT)
2895                 oidclr(&expected_head);
2896         else
2897                 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2898
2899         if (get_oid("HEAD", &actual_head))
2900                 oidclr(&actual_head);
2901
2902         return oideq(&actual_head, &expected_head);
2903 }
2904
2905 static int reset_merge(const struct object_id *oid)
2906 {
2907         int ret;
2908         struct strvec argv = STRVEC_INIT;
2909
2910         strvec_pushl(&argv, "reset", "--merge", NULL);
2911
2912         if (!is_null_oid(oid))
2913                 strvec_push(&argv, oid_to_hex(oid));
2914
2915         ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
2916         strvec_clear(&argv);
2917
2918         return ret;
2919 }
2920
2921 static int rollback_single_pick(struct repository *r)
2922 {
2923         struct object_id head_oid;
2924
2925         if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
2926             !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
2927                 return error(_("no cherry-pick or revert in progress"));
2928         if (read_ref_full("HEAD", 0, &head_oid, NULL))
2929                 return error(_("cannot resolve HEAD"));
2930         if (is_null_oid(&head_oid))
2931                 return error(_("cannot abort from a branch yet to be born"));
2932         return reset_merge(&head_oid);
2933 }
2934
2935 static int skip_single_pick(void)
2936 {
2937         struct object_id head;
2938
2939         if (read_ref_full("HEAD", 0, &head, NULL))
2940                 return error(_("cannot resolve HEAD"));
2941         return reset_merge(&head);
2942 }
2943
2944 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2945 {
2946         FILE *f;
2947         struct object_id oid;
2948         struct strbuf buf = STRBUF_INIT;
2949         const char *p;
2950
2951         f = fopen(git_path_head_file(), "r");
2952         if (!f && errno == ENOENT) {
2953                 /*
2954                  * There is no multiple-cherry-pick in progress.
2955                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2956                  * a single-cherry-pick in progress, abort that.
2957                  */
2958                 return rollback_single_pick(r);
2959         }
2960         if (!f)
2961                 return error_errno(_("cannot open '%s'"), git_path_head_file());
2962         if (strbuf_getline_lf(&buf, f)) {
2963                 error(_("cannot read '%s': %s"), git_path_head_file(),
2964                       ferror(f) ?  strerror(errno) : _("unexpected end of file"));
2965                 fclose(f);
2966                 goto fail;
2967         }
2968         fclose(f);
2969         if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2970                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2971                         git_path_head_file());
2972                 goto fail;
2973         }
2974         if (is_null_oid(&oid)) {
2975                 error(_("cannot abort from a branch yet to be born"));
2976                 goto fail;
2977         }
2978
2979         if (!rollback_is_safe()) {
2980                 /* Do not error, just do not rollback */
2981                 warning(_("You seem to have moved HEAD. "
2982                           "Not rewinding, check your HEAD!"));
2983         } else
2984         if (reset_merge(&oid))
2985                 goto fail;
2986         strbuf_release(&buf);
2987         return sequencer_remove_state(opts);
2988 fail:
2989         strbuf_release(&buf);
2990         return -1;
2991 }
2992
2993 int sequencer_skip(struct repository *r, struct replay_opts *opts)
2994 {
2995         enum replay_action action = -1;
2996         sequencer_get_last_command(r, &action);
2997
2998         /*
2999          * Check whether the subcommand requested to skip the commit is actually
3000          * in progress and that it's safe to skip the commit.
3001          *
3002          * opts->action tells us which subcommand requested to skip the commit.
3003          * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3004          * action is in progress and we can skip the commit.
3005          *
3006          * Otherwise we check that the last instruction was related to the
3007          * particular subcommand we're trying to execute and barf if that's not
3008          * the case.
3009          *
3010          * Finally we check that the rollback is "safe", i.e., has the HEAD
3011          * moved? In this case, it doesn't make sense to "reset the merge" and
3012          * "skip the commit" as the user already handled this by committing. But
3013          * we'd not want to barf here, instead give advice on how to proceed. We
3014          * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3015          * it gets removed when the user commits, so if it still exists we're
3016          * sure the user can't have committed before.
3017          */
3018         switch (opts->action) {
3019         case REPLAY_REVERT:
3020                 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3021                         if (action != REPLAY_REVERT)
3022                                 return error(_("no revert in progress"));
3023                         if (!rollback_is_safe())
3024                                 goto give_advice;
3025                 }
3026                 break;
3027         case REPLAY_PICK:
3028                 if (!refs_ref_exists(get_main_ref_store(r),
3029                                      "CHERRY_PICK_HEAD")) {
3030                         if (action != REPLAY_PICK)
3031                                 return error(_("no cherry-pick in progress"));
3032                         if (!rollback_is_safe())
3033                                 goto give_advice;
3034                 }
3035                 break;
3036         default:
3037                 BUG("unexpected action in sequencer_skip");
3038         }
3039
3040         if (skip_single_pick())
3041                 return error(_("failed to skip the commit"));
3042         if (!is_directory(git_path_seq_dir()))
3043                 return 0;
3044
3045         return sequencer_continue(r, opts);
3046
3047 give_advice:
3048         error(_("there is nothing to skip"));
3049
3050         if (advice_resolve_conflict) {
3051                 advise(_("have you committed already?\n"
3052                          "try \"git %s --continue\""),
3053                          action == REPLAY_REVERT ? "revert" : "cherry-pick");
3054         }
3055         return -1;
3056 }
3057
3058 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3059 {
3060         struct lock_file todo_lock = LOCK_INIT;
3061         const char *todo_path = get_todo_path(opts);
3062         int next = todo_list->current, offset, fd;
3063
3064         /*
3065          * rebase -i writes "git-rebase-todo" without the currently executing
3066          * command, appending it to "done" instead.
3067          */
3068         if (is_rebase_i(opts))
3069                 next++;
3070
3071         fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3072         if (fd < 0)
3073                 return error_errno(_("could not lock '%s'"), todo_path);
3074         offset = get_item_line_offset(todo_list, next);
3075         if (write_in_full(fd, todo_list->buf.buf + offset,
3076                         todo_list->buf.len - offset) < 0)
3077                 return error_errno(_("could not write to '%s'"), todo_path);
3078         if (commit_lock_file(&todo_lock) < 0)
3079                 return error(_("failed to finalize '%s'"), todo_path);
3080
3081         if (is_rebase_i(opts) && next > 0) {
3082                 const char *done = rebase_path_done();
3083                 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3084                 int ret = 0;
3085
3086                 if (fd < 0)
3087                         return 0;
3088                 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3089                                   get_item_line_length(todo_list, next - 1))
3090                     < 0)
3091                         ret = error_errno(_("could not write to '%s'"), done);
3092                 if (close(fd) < 0)
3093                         ret = error_errno(_("failed to finalize '%s'"), done);
3094                 return ret;
3095         }
3096         return 0;
3097 }
3098
3099 static int save_opts(struct replay_opts *opts)
3100 {
3101         const char *opts_file = git_path_opts_file();
3102         int res = 0;
3103
3104         if (opts->no_commit)
3105                 res |= git_config_set_in_file_gently(opts_file,
3106                                         "options.no-commit", "true");
3107         if (opts->edit)
3108                 res |= git_config_set_in_file_gently(opts_file,
3109                                         "options.edit", "true");
3110         if (opts->allow_empty)
3111                 res |= git_config_set_in_file_gently(opts_file,
3112                                         "options.allow-empty", "true");
3113         if (opts->allow_empty_message)
3114                 res |= git_config_set_in_file_gently(opts_file,
3115                                 "options.allow-empty-message", "true");
3116         if (opts->keep_redundant_commits)
3117                 res |= git_config_set_in_file_gently(opts_file,
3118                                 "options.keep-redundant-commits", "true");
3119         if (opts->signoff)
3120                 res |= git_config_set_in_file_gently(opts_file,
3121                                         "options.signoff", "true");
3122         if (opts->record_origin)
3123                 res |= git_config_set_in_file_gently(opts_file,
3124                                         "options.record-origin", "true");
3125         if (opts->allow_ff)
3126                 res |= git_config_set_in_file_gently(opts_file,
3127                                         "options.allow-ff", "true");
3128         if (opts->mainline) {
3129                 struct strbuf buf = STRBUF_INIT;
3130                 strbuf_addf(&buf, "%d", opts->mainline);
3131                 res |= git_config_set_in_file_gently(opts_file,
3132                                         "options.mainline", buf.buf);
3133                 strbuf_release(&buf);
3134         }
3135         if (opts->strategy)
3136                 res |= git_config_set_in_file_gently(opts_file,
3137                                         "options.strategy", opts->strategy);
3138         if (opts->gpg_sign)
3139                 res |= git_config_set_in_file_gently(opts_file,
3140                                         "options.gpg-sign", opts->gpg_sign);
3141         if (opts->xopts) {
3142                 int i;
3143                 for (i = 0; i < opts->xopts_nr; i++)
3144                         res |= git_config_set_multivar_in_file_gently(opts_file,
3145                                         "options.strategy-option",
3146                                         opts->xopts[i], "^$", 0);
3147         }
3148         if (opts->allow_rerere_auto)
3149                 res |= git_config_set_in_file_gently(opts_file,
3150                                 "options.allow-rerere-auto",
3151                                 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3152                                 "true" : "false");
3153
3154         if (opts->explicit_cleanup)
3155                 res |= git_config_set_in_file_gently(opts_file,
3156                                 "options.default-msg-cleanup",
3157                                 describe_cleanup_mode(opts->default_msg_cleanup));
3158         return res;
3159 }
3160
3161 static int make_patch(struct repository *r,
3162                       struct commit *commit,
3163                       struct replay_opts *opts)
3164 {
3165         struct strbuf buf = STRBUF_INIT;
3166         struct rev_info log_tree_opt;
3167         const char *subject;
3168         char hex[GIT_MAX_HEXSZ + 1];
3169         int res = 0;
3170
3171         oid_to_hex_r(hex, &commit->object.oid);
3172         if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3173                 return -1;
3174         res |= write_rebase_head(&commit->object.oid);
3175
3176         strbuf_addf(&buf, "%s/patch", get_dir(opts));
3177         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3178         repo_init_revisions(r, &log_tree_opt, NULL);
3179         log_tree_opt.abbrev = 0;
3180         log_tree_opt.diff = 1;
3181         log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3182         log_tree_opt.disable_stdin = 1;
3183         log_tree_opt.no_commit_id = 1;
3184         log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3185         log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3186         if (!log_tree_opt.diffopt.file)
3187                 res |= error_errno(_("could not open '%s'"), buf.buf);
3188         else {
3189                 res |= log_tree_commit(&log_tree_opt, commit);
3190                 fclose(log_tree_opt.diffopt.file);
3191         }
3192         strbuf_reset(&buf);
3193
3194         strbuf_addf(&buf, "%s/message", get_dir(opts));
3195         if (!file_exists(buf.buf)) {
3196                 const char *encoding = get_commit_output_encoding();
3197                 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3198                 find_commit_subject(commit_buffer, &subject);
3199                 res |= write_message(subject, strlen(subject), buf.buf, 1);
3200                 unuse_commit_buffer(commit, commit_buffer);
3201         }
3202         strbuf_release(&buf);
3203
3204         return res;
3205 }
3206
3207 static int intend_to_amend(void)
3208 {
3209         struct object_id head;
3210         char *p;
3211
3212         if (get_oid("HEAD", &head))
3213                 return error(_("cannot read HEAD"));
3214
3215         p = oid_to_hex(&head);
3216         return write_message(p, strlen(p), rebase_path_amend(), 1);
3217 }
3218
3219 static int error_with_patch(struct repository *r,
3220                             struct commit *commit,
3221                             const char *subject, int subject_len,
3222                             struct replay_opts *opts,
3223                             int exit_code, int to_amend)
3224 {
3225         if (commit) {
3226                 if (make_patch(r, commit, opts))
3227                         return -1;
3228         } else if (copy_file(rebase_path_message(),
3229                              git_path_merge_msg(r), 0666))
3230                 return error(_("unable to copy '%s' to '%s'"),
3231                              git_path_merge_msg(r), rebase_path_message());
3232
3233         if (to_amend) {
3234                 if (intend_to_amend())
3235                         return -1;
3236
3237                 fprintf(stderr,
3238                         _("You can amend the commit now, with\n"
3239                           "\n"
3240                           "  git commit --amend %s\n"
3241                           "\n"
3242                           "Once you are satisfied with your changes, run\n"
3243                           "\n"
3244                           "  git rebase --continue\n"),
3245                         gpg_sign_opt_quoted(opts));
3246         } else if (exit_code) {
3247                 if (commit)
3248                         fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3249                                    short_commit_name(commit), subject_len, subject);
3250                 else
3251                         /*
3252                          * We don't have the hash of the parent so
3253                          * just print the line from the todo file.
3254                          */
3255                         fprintf_ln(stderr, _("Could not merge %.*s"),
3256                                    subject_len, subject);
3257         }
3258
3259         return exit_code;
3260 }
3261
3262 static int error_failed_squash(struct repository *r,
3263                                struct commit *commit,
3264                                struct replay_opts *opts,
3265                                int subject_len,
3266                                const char *subject)
3267 {
3268         if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3269                 return error(_("could not copy '%s' to '%s'"),
3270                         rebase_path_squash_msg(), rebase_path_message());
3271         unlink(git_path_merge_msg(r));
3272         if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3273                 return error(_("could not copy '%s' to '%s'"),
3274                              rebase_path_message(),
3275                              git_path_merge_msg(r));
3276         return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3277 }
3278
3279 static int do_exec(struct repository *r, const char *command_line)
3280 {
3281         struct strvec child_env = STRVEC_INIT;
3282         const char *child_argv[] = { NULL, NULL };
3283         int dirty, status;
3284
3285         fprintf(stderr, _("Executing: %s\n"), command_line);
3286         child_argv[0] = command_line;
3287         strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3288         strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3289                      absolute_path(get_git_work_tree()));
3290         status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3291                                           child_env.v);
3292
3293         /* force re-reading of the cache */
3294         if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3295                 return error(_("could not read index"));
3296
3297         dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3298
3299         if (status) {
3300                 warning(_("execution failed: %s\n%s"
3301                           "You can fix the problem, and then run\n"
3302                           "\n"
3303                           "  git rebase --continue\n"
3304                           "\n"),
3305                         command_line,
3306                         dirty ? N_("and made changes to the index and/or the "
3307                                 "working tree\n") : "");
3308                 if (status == 127)
3309                         /* command not found */
3310                         status = 1;
3311         } else if (dirty) {
3312                 warning(_("execution succeeded: %s\nbut "
3313                           "left changes to the index and/or the working tree\n"
3314                           "Commit or stash your changes, and then run\n"
3315                           "\n"
3316                           "  git rebase --continue\n"
3317                           "\n"), command_line);
3318                 status = 1;
3319         }
3320
3321         strvec_clear(&child_env);
3322
3323         return status;
3324 }
3325
3326 static int safe_append(const char *filename, const char *fmt, ...)
3327 {
3328         va_list ap;
3329         struct lock_file lock = LOCK_INIT;
3330         int fd = hold_lock_file_for_update(&lock, filename,
3331                                            LOCK_REPORT_ON_ERROR);
3332         struct strbuf buf = STRBUF_INIT;
3333
3334         if (fd < 0)
3335                 return -1;
3336
3337         if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3338                 error_errno(_("could not read '%s'"), filename);
3339                 rollback_lock_file(&lock);
3340                 return -1;
3341         }
3342         strbuf_complete(&buf, '\n');
3343         va_start(ap, fmt);
3344         strbuf_vaddf(&buf, fmt, ap);
3345         va_end(ap);
3346
3347         if (write_in_full(fd, buf.buf, buf.len) < 0) {
3348                 error_errno(_("could not write to '%s'"), filename);
3349                 strbuf_release(&buf);
3350                 rollback_lock_file(&lock);
3351                 return -1;
3352         }
3353         if (commit_lock_file(&lock) < 0) {
3354                 strbuf_release(&buf);
3355                 rollback_lock_file(&lock);
3356                 return error(_("failed to finalize '%s'"), filename);
3357         }
3358
3359         strbuf_release(&buf);
3360         return 0;
3361 }
3362
3363 static int do_label(struct repository *r, const char *name, int len)
3364 {
3365         struct ref_store *refs = get_main_ref_store(r);
3366         struct ref_transaction *transaction;
3367         struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3368         struct strbuf msg = STRBUF_INIT;
3369         int ret = 0;
3370         struct object_id head_oid;
3371
3372         if (len == 1 && *name == '#')
3373                 return error(_("illegal label name: '%.*s'"), len, name);
3374
3375         strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3376         strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3377
3378         transaction = ref_store_transaction_begin(refs, &err);
3379         if (!transaction) {
3380                 error("%s", err.buf);
3381                 ret = -1;
3382         } else if (get_oid("HEAD", &head_oid)) {
3383                 error(_("could not read HEAD"));
3384                 ret = -1;
3385         } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3386                                           NULL, 0, msg.buf, &err) < 0 ||
3387                    ref_transaction_commit(transaction, &err)) {
3388                 error("%s", err.buf);
3389                 ret = -1;
3390         }
3391         ref_transaction_free(transaction);
3392         strbuf_release(&err);
3393         strbuf_release(&msg);
3394
3395         if (!ret)
3396                 ret = safe_append(rebase_path_refs_to_delete(),
3397                                   "%s\n", ref_name.buf);
3398         strbuf_release(&ref_name);
3399
3400         return ret;
3401 }
3402
3403 static const char *reflog_message(struct replay_opts *opts,
3404         const char *sub_action, const char *fmt, ...);
3405
3406 static int do_reset(struct repository *r,
3407                     const char *name, int len,
3408                     struct replay_opts *opts)
3409 {
3410         struct strbuf ref_name = STRBUF_INIT;
3411         struct object_id oid;
3412         struct lock_file lock = LOCK_INIT;
3413         struct tree_desc desc;
3414         struct tree *tree;
3415         struct unpack_trees_options unpack_tree_opts;
3416         int ret = 0;
3417
3418         if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3419                 return -1;
3420
3421         if (len == 10 && !strncmp("[new root]", name, len)) {
3422                 if (!opts->have_squash_onto) {
3423                         const char *hex;
3424                         if (commit_tree("", 0, the_hash_algo->empty_tree,
3425                                         NULL, &opts->squash_onto,
3426                                         NULL, NULL))
3427                                 return error(_("writing fake root commit"));
3428                         opts->have_squash_onto = 1;
3429                         hex = oid_to_hex(&opts->squash_onto);
3430                         if (write_message(hex, strlen(hex),
3431                                           rebase_path_squash_onto(), 0))
3432                                 return error(_("writing squash-onto"));
3433                 }
3434                 oidcpy(&oid, &opts->squash_onto);
3435         } else {
3436                 int i;
3437
3438                 /* Determine the length of the label */
3439                 for (i = 0; i < len; i++)
3440                         if (isspace(name[i]))
3441                                 break;
3442                 len = i;
3443
3444                 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3445                 if (get_oid(ref_name.buf, &oid) &&
3446                     get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3447                         error(_("could not read '%s'"), ref_name.buf);
3448                         rollback_lock_file(&lock);
3449                         strbuf_release(&ref_name);
3450                         return -1;
3451                 }
3452         }
3453
3454         memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3455         setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3456         unpack_tree_opts.head_idx = 1;
3457         unpack_tree_opts.src_index = r->index;
3458         unpack_tree_opts.dst_index = r->index;
3459         unpack_tree_opts.fn = oneway_merge;
3460         unpack_tree_opts.merge = 1;
3461         unpack_tree_opts.update = 1;
3462         init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3463
3464         if (repo_read_index_unmerged(r)) {
3465                 rollback_lock_file(&lock);
3466                 strbuf_release(&ref_name);
3467                 return error_resolve_conflict(_(action_name(opts)));
3468         }
3469
3470         if (!fill_tree_descriptor(r, &desc, &oid)) {
3471                 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3472                 rollback_lock_file(&lock);
3473                 free((void *)desc.buffer);
3474                 strbuf_release(&ref_name);
3475                 return -1;
3476         }
3477
3478         if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3479                 rollback_lock_file(&lock);
3480                 free((void *)desc.buffer);
3481                 strbuf_release(&ref_name);
3482                 return -1;
3483         }
3484
3485         tree = parse_tree_indirect(&oid);
3486         prime_cache_tree(r, r->index, tree);
3487
3488         if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3489                 ret = error(_("could not write index"));
3490         free((void *)desc.buffer);
3491
3492         if (!ret)
3493                 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3494                                                 len, name), "HEAD", &oid,
3495                                  NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3496
3497         strbuf_release(&ref_name);
3498         return ret;
3499 }
3500
3501 static struct commit *lookup_label(const char *label, int len,
3502                                    struct strbuf *buf)
3503 {
3504         struct commit *commit;
3505
3506         strbuf_reset(buf);
3507         strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3508         commit = lookup_commit_reference_by_name(buf->buf);
3509         if (!commit) {
3510                 /* fall back to non-rewritten ref or commit */
3511                 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3512                 commit = lookup_commit_reference_by_name(buf->buf);
3513         }
3514
3515         if (!commit)
3516                 error(_("could not resolve '%s'"), buf->buf);
3517
3518         return commit;
3519 }
3520
3521 static int do_merge(struct repository *r,
3522                     struct commit *commit,
3523                     const char *arg, int arg_len,
3524                     int flags, struct replay_opts *opts)
3525 {
3526         int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3527                 EDIT_MSG | VERIFY_MSG : 0;
3528         struct strbuf ref_name = STRBUF_INIT;
3529         struct commit *head_commit, *merge_commit, *i;
3530         struct commit_list *bases, *j, *reversed = NULL;
3531         struct commit_list *to_merge = NULL, **tail = &to_merge;
3532         const char *strategy = !opts->xopts_nr &&
3533                 (!opts->strategy ||
3534                  !strcmp(opts->strategy, "recursive") ||
3535                  !strcmp(opts->strategy, "ort")) ?
3536                 NULL : opts->strategy;
3537         struct merge_options o;
3538         int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3539         static struct lock_file lock;
3540         const char *p;
3541
3542         if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3543                 ret = -1;
3544                 goto leave_merge;
3545         }
3546
3547         head_commit = lookup_commit_reference_by_name("HEAD");
3548         if (!head_commit) {
3549                 ret = error(_("cannot merge without a current revision"));
3550                 goto leave_merge;
3551         }
3552
3553         /*
3554          * For octopus merges, the arg starts with the list of revisions to be
3555          * merged. The list is optionally followed by '#' and the oneline.
3556          */
3557         merge_arg_len = oneline_offset = arg_len;
3558         for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3559                 if (!*p)
3560                         break;
3561                 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3562                         p += 1 + strspn(p + 1, " \t\n");
3563                         oneline_offset = p - arg;
3564                         break;
3565                 }
3566                 k = strcspn(p, " \t\n");
3567                 if (!k)
3568                         continue;
3569                 merge_commit = lookup_label(p, k, &ref_name);
3570                 if (!merge_commit) {
3571                         ret = error(_("unable to parse '%.*s'"), k, p);
3572                         goto leave_merge;
3573                 }
3574                 tail = &commit_list_insert(merge_commit, tail)->next;
3575                 p += k;
3576                 merge_arg_len = p - arg;
3577         }
3578
3579         if (!to_merge) {
3580                 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3581                 goto leave_merge;
3582         }
3583
3584         if (opts->have_squash_onto &&
3585             oideq(&head_commit->object.oid, &opts->squash_onto)) {
3586                 /*
3587                  * When the user tells us to "merge" something into a
3588                  * "[new root]", let's simply fast-forward to the merge head.
3589                  */
3590                 rollback_lock_file(&lock);
3591                 if (to_merge->next)
3592                         ret = error(_("octopus merge cannot be executed on "
3593                                       "top of a [new root]"));
3594                 else
3595                         ret = fast_forward_to(r, &to_merge->item->object.oid,
3596                                               &head_commit->object.oid, 0,
3597                                               opts);
3598                 goto leave_merge;
3599         }
3600
3601         if (commit) {
3602                 const char *encoding = get_commit_output_encoding();
3603                 const char *message = logmsg_reencode(commit, NULL, encoding);
3604                 const char *body;
3605                 int len;
3606
3607                 if (!message) {
3608                         ret = error(_("could not get commit message of '%s'"),
3609                                     oid_to_hex(&commit->object.oid));
3610                         goto leave_merge;
3611                 }
3612                 write_author_script(message);
3613                 find_commit_subject(message, &body);
3614                 len = strlen(body);
3615                 ret = write_message(body, len, git_path_merge_msg(r), 0);
3616                 unuse_commit_buffer(commit, message);
3617                 if (ret) {
3618                         error_errno(_("could not write '%s'"),
3619                                     git_path_merge_msg(r));
3620                         goto leave_merge;
3621                 }
3622         } else {
3623                 struct strbuf buf = STRBUF_INIT;
3624                 int len;
3625
3626                 strbuf_addf(&buf, "author %s", git_author_info(0));
3627                 write_author_script(buf.buf);
3628                 strbuf_reset(&buf);
3629
3630                 if (oneline_offset < arg_len) {
3631                         p = arg + oneline_offset;
3632                         len = arg_len - oneline_offset;
3633                 } else {
3634                         strbuf_addf(&buf, "Merge %s '%.*s'",
3635                                     to_merge->next ? "branches" : "branch",
3636                                     merge_arg_len, arg);
3637                         p = buf.buf;
3638                         len = buf.len;
3639                 }
3640
3641                 ret = write_message(p, len, git_path_merge_msg(r), 0);
3642                 strbuf_release(&buf);
3643                 if (ret) {
3644                         error_errno(_("could not write '%s'"),
3645                                     git_path_merge_msg(r));
3646                         goto leave_merge;
3647                 }
3648         }
3649
3650         /*
3651          * If HEAD is not identical to the first parent of the original merge
3652          * commit, we cannot fast-forward.
3653          */
3654         can_fast_forward = opts->allow_ff && commit && commit->parents &&
3655                 oideq(&commit->parents->item->object.oid,
3656                       &head_commit->object.oid);
3657
3658         /*
3659          * If any merge head is different from the original one, we cannot
3660          * fast-forward.
3661          */
3662         if (can_fast_forward) {
3663                 struct commit_list *p = commit->parents->next;
3664
3665                 for (j = to_merge; j && p; j = j->next, p = p->next)
3666                         if (!oideq(&j->item->object.oid,
3667                                    &p->item->object.oid)) {
3668                                 can_fast_forward = 0;
3669                                 break;
3670                         }
3671                 /*
3672                  * If the number of merge heads differs from the original merge
3673                  * commit, we cannot fast-forward.
3674                  */
3675                 if (j || p)
3676                         can_fast_forward = 0;
3677         }
3678
3679         if (can_fast_forward) {
3680                 rollback_lock_file(&lock);
3681                 ret = fast_forward_to(r, &commit->object.oid,
3682                                       &head_commit->object.oid, 0, opts);
3683                 if (flags & TODO_EDIT_MERGE_MSG) {
3684                         run_commit_flags |= AMEND_MSG;
3685                         goto fast_forward_edit;
3686                 }
3687                 goto leave_merge;
3688         }
3689
3690         if (strategy || to_merge->next) {
3691                 /* Octopus merge */
3692                 struct child_process cmd = CHILD_PROCESS_INIT;
3693
3694                 if (read_env_script(&cmd.env_array)) {
3695                         const char *gpg_opt = gpg_sign_opt_quoted(opts);
3696
3697                         ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3698                         goto leave_merge;
3699                 }
3700
3701                 if (opts->committer_date_is_author_date)
3702                         strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3703                                      opts->ignore_date ?
3704                                      "" :
3705                                      author_date_from_env_array(&cmd.env_array));
3706                 if (opts->ignore_date)
3707                         strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3708
3709                 cmd.git_cmd = 1;
3710                 strvec_push(&cmd.args, "merge");
3711                 strvec_push(&cmd.args, "-s");
3712                 if (!strategy)
3713                         strvec_push(&cmd.args, "octopus");
3714                 else {
3715                         strvec_push(&cmd.args, strategy);
3716                         for (k = 0; k < opts->xopts_nr; k++)
3717                                 strvec_pushf(&cmd.args,
3718                                              "-X%s", opts->xopts[k]);
3719                 }
3720                 strvec_push(&cmd.args, "--no-edit");
3721                 strvec_push(&cmd.args, "--no-ff");
3722                 strvec_push(&cmd.args, "--no-log");
3723                 strvec_push(&cmd.args, "--no-stat");
3724                 strvec_push(&cmd.args, "-F");
3725                 strvec_push(&cmd.args, git_path_merge_msg(r));
3726                 if (opts->gpg_sign)
3727                         strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3728                 else
3729                         strvec_push(&cmd.args, "--no-gpg-sign");
3730
3731                 /* Add the tips to be merged */
3732                 for (j = to_merge; j; j = j->next)
3733                         strvec_push(&cmd.args,
3734                                     oid_to_hex(&j->item->object.oid));
3735
3736                 strbuf_release(&ref_name);
3737                 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3738                                 NULL, 0);
3739                 rollback_lock_file(&lock);
3740
3741                 ret = run_command(&cmd);
3742
3743                 /* force re-reading of the cache */
3744                 if (!ret && (discard_index(r->index) < 0 ||
3745                              repo_read_index(r) < 0))
3746                         ret = error(_("could not read index"));
3747                 goto leave_merge;
3748         }
3749
3750         merge_commit = to_merge->item;
3751         bases = get_merge_bases(head_commit, merge_commit);
3752         if (bases && oideq(&merge_commit->object.oid,
3753                            &bases->item->object.oid)) {
3754                 ret = 0;
3755                 /* skip merging an ancestor of HEAD */
3756                 goto leave_merge;
3757         }
3758
3759         write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3760                       git_path_merge_head(r), 0);
3761         write_message("no-ff", 5, git_path_merge_mode(r), 0);
3762
3763         for (j = bases; j; j = j->next)
3764                 commit_list_insert(j->item, &reversed);
3765         free_commit_list(bases);
3766
3767         repo_read_index(r);
3768         init_merge_options(&o, r);
3769         o.branch1 = "HEAD";
3770         o.branch2 = ref_name.buf;
3771         o.buffer_output = 2;
3772
3773         if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3774                 /*
3775                  * TODO: Should use merge_incore_recursive() and
3776                  * merge_switch_to_result(), skipping the call to
3777                  * merge_switch_to_result() when we don't actually need to
3778                  * update the index and working copy immediately.
3779                  */
3780                 ret = merge_ort_recursive(&o,
3781                                           head_commit, merge_commit, reversed,
3782                                           &i);
3783         } else {
3784                 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
3785                                       &i);
3786         }
3787         if (ret <= 0)
3788                 fputs(o.obuf.buf, stdout);
3789         strbuf_release(&o.obuf);
3790         if (ret < 0) {
3791                 error(_("could not even attempt to merge '%.*s'"),
3792                       merge_arg_len, arg);
3793                 goto leave_merge;
3794         }
3795         /*
3796          * The return value of merge_recursive() is 1 on clean, and 0 on
3797          * unclean merge.
3798          *
3799          * Let's reverse that, so that do_merge() returns 0 upon success and
3800          * 1 upon failed merge (keeping the return value -1 for the cases where
3801          * we will want to reschedule the `merge` command).
3802          */
3803         ret = !ret;
3804
3805         if (r->index->cache_changed &&
3806             write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3807                 ret = error(_("merge: Unable to write new index file"));
3808                 goto leave_merge;
3809         }
3810
3811         rollback_lock_file(&lock);
3812         if (ret)
3813                 repo_rerere(r, opts->allow_rerere_auto);
3814         else
3815                 /*
3816                  * In case of problems, we now want to return a positive
3817                  * value (a negative one would indicate that the `merge`
3818                  * command needs to be rescheduled).
3819                  */
3820         fast_forward_edit:
3821                 ret = !!run_git_commit(git_path_merge_msg(r), opts,
3822                                        run_commit_flags);
3823
3824 leave_merge:
3825         strbuf_release(&ref_name);
3826         rollback_lock_file(&lock);
3827         free_commit_list(to_merge);
3828         return ret;
3829 }
3830
3831 static int is_final_fixup(struct todo_list *todo_list)
3832 {
3833         int i = todo_list->current;
3834
3835         if (!is_fixup(todo_list->items[i].command))
3836                 return 0;
3837
3838         while (++i < todo_list->nr)
3839                 if (is_fixup(todo_list->items[i].command))
3840                         return 0;
3841                 else if (!is_noop(todo_list->items[i].command))
3842                         break;
3843         return 1;
3844 }
3845
3846 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3847 {
3848         int i;
3849
3850         for (i = todo_list->current + offset; i < todo_list->nr; i++)
3851                 if (!is_noop(todo_list->items[i].command))
3852                         return todo_list->items[i].command;
3853
3854         return -1;
3855 }
3856
3857 void create_autostash(struct repository *r, const char *path,
3858                       const char *default_reflog_action)
3859 {
3860         struct strbuf buf = STRBUF_INIT;
3861         struct lock_file lock_file = LOCK_INIT;
3862         int fd;
3863
3864         fd = repo_hold_locked_index(r, &lock_file, 0);
3865         refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
3866         if (0 <= fd)
3867                 repo_update_index_if_able(r, &lock_file);
3868         rollback_lock_file(&lock_file);
3869
3870         if (has_unstaged_changes(r, 1) ||
3871             has_uncommitted_changes(r, 1)) {
3872                 struct child_process stash = CHILD_PROCESS_INIT;
3873                 struct object_id oid;
3874
3875                 strvec_pushl(&stash.args,
3876                              "stash", "create", "autostash", NULL);
3877                 stash.git_cmd = 1;
3878                 stash.no_stdin = 1;
3879                 strbuf_reset(&buf);
3880                 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
3881                         die(_("Cannot autostash"));
3882                 strbuf_trim_trailing_newline(&buf);
3883                 if (get_oid(buf.buf, &oid))
3884                         die(_("Unexpected stash response: '%s'"),
3885                             buf.buf);
3886                 strbuf_reset(&buf);
3887                 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
3888
3889                 if (safe_create_leading_directories_const(path))
3890                         die(_("Could not create directory for '%s'"),
3891                             path);
3892                 write_file(path, "%s", oid_to_hex(&oid));
3893                 printf(_("Created autostash: %s\n"), buf.buf);
3894                 if (reset_head(r, NULL, "reset --hard",
3895                                NULL, RESET_HEAD_HARD, NULL, NULL,
3896                                default_reflog_action) < 0)
3897                         die(_("could not reset --hard"));
3898
3899                 if (discard_index(r->index) < 0 ||
3900                         repo_read_index(r) < 0)
3901                         die(_("could not read index"));
3902         }
3903         strbuf_release(&buf);
3904 }
3905
3906 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
3907 {
3908         struct child_process child = CHILD_PROCESS_INIT;
3909         int ret = 0;
3910
3911         if (attempt_apply) {
3912                 child.git_cmd = 1;
3913                 child.no_stdout = 1;
3914                 child.no_stderr = 1;
3915                 strvec_push(&child.args, "stash");
3916                 strvec_push(&child.args, "apply");
3917                 strvec_push(&child.args, stash_oid);
3918                 ret = run_command(&child);
3919         }
3920
3921         if (attempt_apply && !ret)
3922                 fprintf(stderr, _("Applied autostash.\n"));
3923         else {
3924                 struct child_process store = CHILD_PROCESS_INIT;
3925
3926                 store.git_cmd = 1;
3927                 strvec_push(&store.args, "stash");
3928                 strvec_push(&store.args, "store");
3929                 strvec_push(&store.args, "-m");
3930                 strvec_push(&store.args, "autostash");
3931                 strvec_push(&store.args, "-q");
3932                 strvec_push(&store.args, stash_oid);
3933                 if (run_command(&store))
3934                         ret = error(_("cannot store %s"), stash_oid);
3935                 else
3936                         fprintf(stderr,
3937                                 _("%s\n"
3938                                   "Your changes are safe in the stash.\n"
3939                                   "You can run \"git stash pop\" or"
3940                                   " \"git stash drop\" at any time.\n"),
3941                                 attempt_apply ?
3942                                 _("Applying autostash resulted in conflicts.") :
3943                                 _("Autostash exists; creating a new stash entry."));
3944         }
3945
3946         return ret;
3947 }
3948
3949 static int apply_save_autostash(const char *path, int attempt_apply)
3950 {
3951         struct strbuf stash_oid = STRBUF_INIT;
3952         int ret = 0;
3953
3954         if (!read_oneliner(&stash_oid, path,
3955                            READ_ONELINER_SKIP_IF_EMPTY)) {
3956                 strbuf_release(&stash_oid);
3957                 return 0;
3958         }
3959         strbuf_trim(&stash_oid);
3960
3961         ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
3962
3963         unlink(path);
3964         strbuf_release(&stash_oid);
3965         return ret;
3966 }
3967
3968 int save_autostash(const char *path)
3969 {
3970         return apply_save_autostash(path, 0);
3971 }
3972
3973 int apply_autostash(const char *path)
3974 {
3975         return apply_save_autostash(path, 1);
3976 }
3977
3978 int apply_autostash_oid(const char *stash_oid)
3979 {
3980         return apply_save_autostash_oid(stash_oid, 1);
3981 }
3982
3983 static const char *reflog_message(struct replay_opts *opts,
3984         const char *sub_action, const char *fmt, ...)
3985 {
3986         va_list ap;
3987         static struct strbuf buf = STRBUF_INIT;
3988         char *reflog_action = getenv(GIT_REFLOG_ACTION);
3989
3990         va_start(ap, fmt);
3991         strbuf_reset(&buf);
3992         strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3993         if (sub_action)
3994                 strbuf_addf(&buf, " (%s)", sub_action);
3995         if (fmt) {
3996                 strbuf_addstr(&buf, ": ");
3997                 strbuf_vaddf(&buf, fmt, ap);
3998         }
3999         va_end(ap);
4000
4001         return buf.buf;
4002 }
4003
4004 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4005                             const char *commit, const char *action)
4006 {
4007         struct child_process cmd = CHILD_PROCESS_INIT;
4008         int ret;
4009
4010         cmd.git_cmd = 1;
4011
4012         strvec_push(&cmd.args, "checkout");
4013         strvec_push(&cmd.args, commit);
4014         strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4015
4016         if (opts->verbose)
4017                 ret = run_command(&cmd);
4018         else
4019                 ret = run_command_silent_on_success(&cmd);
4020
4021         if (!ret)
4022                 discard_index(r->index);
4023
4024         return ret;
4025 }
4026
4027 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4028                          const char *onto_name, const struct object_id *onto,
4029                          const struct object_id *orig_head)
4030 {
4031         const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4032
4033         if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4034                 apply_autostash(rebase_path_autostash());
4035                 sequencer_remove_state(opts);
4036                 return error(_("could not detach HEAD"));
4037         }
4038
4039         return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4040 }
4041
4042 static int stopped_at_head(struct repository *r)
4043 {
4044         struct object_id head;
4045         struct commit *commit;
4046         struct commit_message message;
4047
4048         if (get_oid("HEAD", &head) ||
4049             !(commit = lookup_commit(r, &head)) ||
4050             parse_commit(commit) || get_message(commit, &message))
4051                 fprintf(stderr, _("Stopped at HEAD\n"));
4052         else {
4053                 fprintf(stderr, _("Stopped at %s\n"), message.label);
4054                 free_message(commit, &message);
4055         }
4056         return 0;
4057
4058 }
4059
4060 static const char rescheduled_advice[] =
4061 N_("Could not execute the todo command\n"
4062 "\n"
4063 "    %.*s"
4064 "\n"
4065 "It has been rescheduled; To edit the command before continuing, please\n"
4066 "edit the todo list first:\n"
4067 "\n"
4068 "    git rebase --edit-todo\n"
4069 "    git rebase --continue\n");
4070
4071 static int pick_commits(struct repository *r,
4072                         struct todo_list *todo_list,
4073                         struct replay_opts *opts)
4074 {
4075         int res = 0, reschedule = 0;
4076         char *prev_reflog_action;
4077
4078         /* Note that 0 for 3rd parameter of setenv means set only if not set */
4079         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4080         prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4081         if (opts->allow_ff)
4082                 assert(!(opts->signoff || opts->no_commit ||
4083                          opts->record_origin || opts->edit ||
4084                          opts->committer_date_is_author_date ||
4085                          opts->ignore_date));
4086         if (read_and_refresh_cache(r, opts))
4087                 return -1;
4088
4089         while (todo_list->current < todo_list->nr) {
4090                 struct todo_item *item = todo_list->items + todo_list->current;
4091                 const char *arg = todo_item_get_arg(todo_list, item);
4092                 int check_todo = 0;
4093
4094                 if (save_todo(todo_list, opts))
4095                         return -1;
4096                 if (is_rebase_i(opts)) {
4097                         if (item->command != TODO_COMMENT) {
4098                                 FILE *f = fopen(rebase_path_msgnum(), "w");
4099
4100                                 todo_list->done_nr++;
4101
4102                                 if (f) {
4103                                         fprintf(f, "%d\n", todo_list->done_nr);
4104                                         fclose(f);
4105                                 }
4106                                 if (!opts->quiet)
4107                                         fprintf(stderr, _("Rebasing (%d/%d)%s"),
4108                                                 todo_list->done_nr,
4109                                                 todo_list->total_nr,
4110                                                 opts->verbose ? "\n" : "\r");
4111                         }
4112                         unlink(rebase_path_message());
4113                         unlink(rebase_path_author_script());
4114                         unlink(rebase_path_stopped_sha());
4115                         unlink(rebase_path_amend());
4116                         unlink(git_path_merge_head(r));
4117                         unlink(git_path_auto_merge(r));
4118                         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4119
4120                         if (item->command == TODO_BREAK) {
4121                                 if (!opts->verbose)
4122                                         term_clear_line();
4123                                 return stopped_at_head(r);
4124                         }
4125                 }
4126                 if (item->command <= TODO_SQUASH) {
4127                         if (is_rebase_i(opts))
4128                                 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4129                                         command_to_string(item->command), NULL),
4130                                         1);
4131                         res = do_pick_commit(r, item->command, item->commit,
4132                                              opts, is_final_fixup(todo_list),
4133                                              &check_todo);
4134                         if (is_rebase_i(opts))
4135                                 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4136                         if (is_rebase_i(opts) && res < 0) {
4137                                 /* Reschedule */
4138                                 advise(_(rescheduled_advice),
4139                                        get_item_line_length(todo_list,
4140                                                             todo_list->current),
4141                                        get_item_line(todo_list,
4142                                                      todo_list->current));
4143                                 todo_list->current--;
4144                                 if (save_todo(todo_list, opts))
4145                                         return -1;
4146                         }
4147                         if (item->command == TODO_EDIT) {
4148                                 struct commit *commit = item->commit;
4149                                 if (!res) {
4150                                         if (!opts->verbose)
4151                                                 term_clear_line();
4152                                         fprintf(stderr,
4153                                                 _("Stopped at %s...  %.*s\n"),
4154                                                 short_commit_name(commit),
4155                                                 item->arg_len, arg);
4156                                 }
4157                                 return error_with_patch(r, commit,
4158                                         arg, item->arg_len, opts, res, !res);
4159                         }
4160                         if (is_rebase_i(opts) && !res)
4161                                 record_in_rewritten(&item->commit->object.oid,
4162                                         peek_command(todo_list, 1));
4163                         if (res && is_fixup(item->command)) {
4164                                 if (res == 1)
4165                                         intend_to_amend();
4166                                 return error_failed_squash(r, item->commit, opts,
4167                                         item->arg_len, arg);
4168                         } else if (res && is_rebase_i(opts) && item->commit) {
4169                                 int to_amend = 0;
4170                                 struct object_id oid;
4171
4172                                 /*
4173                                  * If we are rewording and have either
4174                                  * fast-forwarded already, or are about to
4175                                  * create a new root commit, we want to amend,
4176                                  * otherwise we do not.
4177                                  */
4178                                 if (item->command == TODO_REWORD &&
4179                                     !get_oid("HEAD", &oid) &&
4180                                     (oideq(&item->commit->object.oid, &oid) ||
4181                                      (opts->have_squash_onto &&
4182                                       oideq(&opts->squash_onto, &oid))))
4183                                         to_amend = 1;
4184
4185                                 return res | error_with_patch(r, item->commit,
4186                                                 arg, item->arg_len, opts,
4187                                                 res, to_amend);
4188                         }
4189                 } else if (item->command == TODO_EXEC) {
4190                         char *end_of_arg = (char *)(arg + item->arg_len);
4191                         int saved = *end_of_arg;
4192
4193                         if (!opts->verbose)
4194                                 term_clear_line();
4195                         *end_of_arg = '\0';
4196                         res = do_exec(r, arg);
4197                         *end_of_arg = saved;
4198
4199                         if (res) {
4200                                 if (opts->reschedule_failed_exec)
4201                                         reschedule = 1;
4202                         }
4203                         check_todo = 1;
4204                 } else if (item->command == TODO_LABEL) {
4205                         if ((res = do_label(r, arg, item->arg_len)))
4206                                 reschedule = 1;
4207                 } else if (item->command == TODO_RESET) {
4208                         if ((res = do_reset(r, arg, item->arg_len, opts)))
4209                                 reschedule = 1;
4210                 } else if (item->command == TODO_MERGE) {
4211                         if ((res = do_merge(r, item->commit,
4212                                             arg, item->arg_len,
4213                                             item->flags, opts)) < 0)
4214                                 reschedule = 1;
4215                         else if (item->commit)
4216                                 record_in_rewritten(&item->commit->object.oid,
4217                                                     peek_command(todo_list, 1));
4218                         if (res > 0)
4219                                 /* failed with merge conflicts */
4220                                 return error_with_patch(r, item->commit,
4221                                                         arg, item->arg_len,
4222                                                         opts, res, 0);
4223                 } else if (!is_noop(item->command))
4224                         return error(_("unknown command %d"), item->command);
4225
4226                 if (reschedule) {
4227                         advise(_(rescheduled_advice),
4228                                get_item_line_length(todo_list,
4229                                                     todo_list->current),
4230                                get_item_line(todo_list, todo_list->current));
4231                         todo_list->current--;
4232                         if (save_todo(todo_list, opts))
4233                                 return -1;
4234                         if (item->commit)
4235                                 return error_with_patch(r,
4236                                                         item->commit,
4237                                                         arg, item->arg_len,
4238                                                         opts, res, 0);
4239                 } else if (is_rebase_i(opts) && check_todo && !res) {
4240                         struct stat st;
4241
4242                         if (stat(get_todo_path(opts), &st)) {
4243                                 res = error_errno(_("could not stat '%s'"),
4244                                                   get_todo_path(opts));
4245                         } else if (match_stat_data(&todo_list->stat, &st)) {
4246                                 /* Reread the todo file if it has changed. */
4247                                 todo_list_release(todo_list);
4248                                 if (read_populate_todo(r, todo_list, opts))
4249                                         res = -1; /* message was printed */
4250                                 /* `current` will be incremented below */
4251                                 todo_list->current = -1;
4252                         }
4253                 }
4254
4255                 todo_list->current++;
4256                 if (res)
4257                         return res;
4258         }
4259
4260         if (is_rebase_i(opts)) {
4261                 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4262                 struct stat st;
4263
4264                 /* Stopped in the middle, as planned? */
4265                 if (todo_list->current < todo_list->nr)
4266                         return 0;
4267
4268                 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4269                                 starts_with(head_ref.buf, "refs/")) {
4270                         const char *msg;
4271                         struct object_id head, orig;
4272                         int res;
4273
4274                         if (get_oid("HEAD", &head)) {
4275                                 res = error(_("cannot read HEAD"));
4276 cleanup_head_ref:
4277                                 strbuf_release(&head_ref);
4278                                 strbuf_release(&buf);
4279                                 return res;
4280                         }
4281                         if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4282                                         get_oid_hex(buf.buf, &orig)) {
4283                                 res = error(_("could not read orig-head"));
4284                                 goto cleanup_head_ref;
4285                         }
4286                         strbuf_reset(&buf);
4287                         if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4288                                 res = error(_("could not read 'onto'"));
4289                                 goto cleanup_head_ref;
4290                         }
4291                         msg = reflog_message(opts, "finish", "%s onto %s",
4292                                 head_ref.buf, buf.buf);
4293                         if (update_ref(msg, head_ref.buf, &head, &orig,
4294                                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4295                                 res = error(_("could not update %s"),
4296                                         head_ref.buf);
4297                                 goto cleanup_head_ref;
4298                         }
4299                         msg = reflog_message(opts, "finish", "returning to %s",
4300                                 head_ref.buf);
4301                         if (create_symref("HEAD", head_ref.buf, msg)) {
4302                                 res = error(_("could not update HEAD to %s"),
4303                                         head_ref.buf);
4304                                 goto cleanup_head_ref;
4305                         }
4306                         strbuf_reset(&buf);
4307                 }
4308
4309                 if (opts->verbose) {
4310                         struct rev_info log_tree_opt;
4311                         struct object_id orig, head;
4312
4313                         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4314                         repo_init_revisions(r, &log_tree_opt, NULL);
4315                         log_tree_opt.diff = 1;
4316                         log_tree_opt.diffopt.output_format =
4317                                 DIFF_FORMAT_DIFFSTAT;
4318                         log_tree_opt.disable_stdin = 1;
4319
4320                         if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4321                             !get_oid(buf.buf, &orig) &&
4322                             !get_oid("HEAD", &head)) {
4323                                 diff_tree_oid(&orig, &head, "",
4324                                               &log_tree_opt.diffopt);
4325                                 log_tree_diff_flush(&log_tree_opt);
4326                         }
4327                 }
4328                 flush_rewritten_pending();
4329                 if (!stat(rebase_path_rewritten_list(), &st) &&
4330                                 st.st_size > 0) {
4331                         struct child_process child = CHILD_PROCESS_INIT;
4332                         const char *post_rewrite_hook =
4333                                 find_hook("post-rewrite");
4334
4335                         child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4336                         child.git_cmd = 1;
4337                         strvec_push(&child.args, "notes");
4338                         strvec_push(&child.args, "copy");
4339                         strvec_push(&child.args, "--for-rewrite=rebase");
4340                         /* we don't care if this copying failed */
4341                         run_command(&child);
4342
4343                         if (post_rewrite_hook) {
4344                                 struct child_process hook = CHILD_PROCESS_INIT;
4345
4346                                 hook.in = open(rebase_path_rewritten_list(),
4347                                         O_RDONLY);
4348                                 hook.stdout_to_stderr = 1;
4349                                 hook.trace2_hook_name = "post-rewrite";
4350                                 strvec_push(&hook.args, post_rewrite_hook);
4351                                 strvec_push(&hook.args, "rebase");
4352                                 /* we don't care if this hook failed */
4353                                 run_command(&hook);
4354                         }
4355                 }
4356                 apply_autostash(rebase_path_autostash());
4357
4358                 if (!opts->quiet) {
4359                         if (!opts->verbose)
4360                                 term_clear_line();
4361                         fprintf(stderr,
4362                                 _("Successfully rebased and updated %s.\n"),
4363                                 head_ref.buf);
4364                 }
4365
4366                 strbuf_release(&buf);
4367                 strbuf_release(&head_ref);
4368         }
4369
4370         /*
4371          * Sequence of picks finished successfully; cleanup by
4372          * removing the .git/sequencer directory
4373          */
4374         return sequencer_remove_state(opts);
4375 }
4376
4377 static int continue_single_pick(struct repository *r)
4378 {
4379         const char *argv[] = { "commit", NULL };
4380
4381         if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4382             !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4383                 return error(_("no cherry-pick or revert in progress"));
4384         return run_command_v_opt(argv, RUN_GIT_CMD);
4385 }
4386
4387 static int commit_staged_changes(struct repository *r,
4388                                  struct replay_opts *opts,
4389                                  struct todo_list *todo_list)
4390 {
4391         unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4392         unsigned int final_fixup = 0, is_clean;
4393
4394         if (has_unstaged_changes(r, 1))
4395                 return error(_("cannot rebase: You have unstaged changes."));
4396
4397         is_clean = !has_uncommitted_changes(r, 0);
4398
4399         if (file_exists(rebase_path_amend())) {
4400                 struct strbuf rev = STRBUF_INIT;
4401                 struct object_id head, to_amend;
4402
4403                 if (get_oid("HEAD", &head))
4404                         return error(_("cannot amend non-existing commit"));
4405                 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4406                         return error(_("invalid file: '%s'"), rebase_path_amend());
4407                 if (get_oid_hex(rev.buf, &to_amend))
4408                         return error(_("invalid contents: '%s'"),
4409                                 rebase_path_amend());
4410                 if (!is_clean && !oideq(&head, &to_amend))
4411                         return error(_("\nYou have uncommitted changes in your "
4412                                        "working tree. Please, commit them\n"
4413                                        "first and then run 'git rebase "
4414                                        "--continue' again."));
4415                 /*
4416                  * When skipping a failed fixup/squash, we need to edit the
4417                  * commit message, the current fixup list and count, and if it
4418                  * was the last fixup/squash in the chain, we need to clean up
4419                  * the commit message and if there was a squash, let the user
4420                  * edit it.
4421                  */
4422                 if (!is_clean || !opts->current_fixup_count)
4423                         ; /* this is not the final fixup */
4424                 else if (!oideq(&head, &to_amend) ||
4425                          !file_exists(rebase_path_stopped_sha())) {
4426                         /* was a final fixup or squash done manually? */
4427                         if (!is_fixup(peek_command(todo_list, 0))) {
4428                                 unlink(rebase_path_fixup_msg());
4429                                 unlink(rebase_path_squash_msg());
4430                                 unlink(rebase_path_current_fixups());
4431                                 strbuf_reset(&opts->current_fixups);
4432                                 opts->current_fixup_count = 0;
4433                         }
4434                 } else {
4435                         /* we are in a fixup/squash chain */
4436                         const char *p = opts->current_fixups.buf;
4437                         int len = opts->current_fixups.len;
4438
4439                         opts->current_fixup_count--;
4440                         if (!len)
4441                                 BUG("Incorrect current_fixups:\n%s", p);
4442                         while (len && p[len - 1] != '\n')
4443                                 len--;
4444                         strbuf_setlen(&opts->current_fixups, len);
4445                         if (write_message(p, len, rebase_path_current_fixups(),
4446                                           0) < 0)
4447                                 return error(_("could not write file: '%s'"),
4448                                              rebase_path_current_fixups());
4449
4450                         /*
4451                          * If a fixup/squash in a fixup/squash chain failed, the
4452                          * commit message is already correct, no need to commit
4453                          * it again.
4454                          *
4455                          * Only if it is the final command in the fixup/squash
4456                          * chain, and only if the chain is longer than a single
4457                          * fixup/squash command (which was just skipped), do we
4458                          * actually need to re-commit with a cleaned up commit
4459                          * message.
4460                          */
4461                         if (opts->current_fixup_count > 0 &&
4462                             !is_fixup(peek_command(todo_list, 0))) {
4463                                 final_fixup = 1;
4464                                 /*
4465                                  * If there was not a single "squash" in the
4466                                  * chain, we only need to clean up the commit
4467                                  * message, no need to bother the user with
4468                                  * opening the commit message in the editor.
4469                                  */
4470                                 if (!starts_with(p, "squash ") &&
4471                                     !strstr(p, "\nsquash "))
4472                                         flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4473                         } else if (is_fixup(peek_command(todo_list, 0))) {
4474                                 /*
4475                                  * We need to update the squash message to skip
4476                                  * the latest commit message.
4477                                  */
4478                                 struct commit *commit;
4479                                 const char *path = rebase_path_squash_msg();
4480                                 const char *encoding = get_commit_output_encoding();
4481
4482                                 if (parse_head(r, &commit) ||
4483                                     !(p = logmsg_reencode(commit, NULL, encoding)) ||
4484                                     write_message(p, strlen(p), path, 0)) {
4485                                         unuse_commit_buffer(commit, p);
4486                                         return error(_("could not write file: "
4487                                                        "'%s'"), path);
4488                                 }
4489                                 unuse_commit_buffer(commit, p);
4490                         }
4491                 }
4492
4493                 strbuf_release(&rev);
4494                 flags |= AMEND_MSG;
4495         }
4496
4497         if (is_clean) {
4498                 if (refs_ref_exists(get_main_ref_store(r),
4499                                     "CHERRY_PICK_HEAD") &&
4500                     refs_delete_ref(get_main_ref_store(r), "",
4501                                     "CHERRY_PICK_HEAD", NULL, 0))
4502                         return error(_("could not remove CHERRY_PICK_HEAD"));
4503                 if (!final_fixup)
4504                         return 0;
4505         }
4506
4507         if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4508                            opts, flags))
4509                 return error(_("could not commit staged changes."));
4510         unlink(rebase_path_amend());
4511         unlink(git_path_merge_head(r));
4512         unlink(git_path_auto_merge(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         base_items = xcalloc(commands->nr, sizeof(struct todo_item));
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 }