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