sequencer: try to commit without forking 'git commit'
[git] / sequencer.c
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object.h"
6 #include "commit.h"
7 #include "sequencer.h"
8 #include "tag.h"
9 #include "run-command.h"
10 #include "exec_cmd.h"
11 #include "utf8.h"
12 #include "cache-tree.h"
13 #include "diff.h"
14 #include "revision.h"
15 #include "rerere.h"
16 #include "merge-recursive.h"
17 #include "refs.h"
18 #include "argv-array.h"
19 #include "quote.h"
20 #include "trailer.h"
21 #include "log-tree.h"
22 #include "wt-status.h"
23 #include "hashmap.h"
24 #include "notes-utils.h"
25 #include "sigchain.h"
26
27 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
28
29 const char sign_off_header[] = "Signed-off-by: ";
30 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
31
32 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
33
34 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
35 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
36 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
37 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
38
39 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
40 /*
41  * The file containing rebase commands, comments, and empty lines.
42  * This file is created by "git rebase -i" then edited by the user. As
43  * the lines are processed, they are removed from the front of this
44  * file and written to the tail of 'done'.
45  */
46 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
47 /*
48  * The rebase command lines that have already been processed. A line
49  * is moved here when it is first handled, before any associated user
50  * actions.
51  */
52 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
53 /*
54  * The file to keep track of how many commands were already processed (e.g.
55  * for the prompt).
56  */
57 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
58 /*
59  * The file to keep track of how many commands are to be processed in total
60  * (e.g. for the prompt).
61  */
62 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
63 /*
64  * The commit message that is planned to be used for any changes that
65  * need to be committed following a user interaction.
66  */
67 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
68 /*
69  * The file into which is accumulated the suggested commit message for
70  * squash/fixup commands. When the first of a series of squash/fixups
71  * is seen, the file is created and the commit message from the
72  * previous commit and from the first squash/fixup commit are written
73  * to it. The commit message for each subsequent squash/fixup commit
74  * is appended to the file as it is processed.
75  *
76  * The first line of the file is of the form
77  *     # This is a combination of $count commits.
78  * where $count is the number of commits whose messages have been
79  * written to the file so far (including the initial "pick" commit).
80  * Each time that a commit message is processed, this line is read and
81  * updated. It is deleted just before the combined commit is made.
82  */
83 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
84 /*
85  * If the current series of squash/fixups has not yet included a squash
86  * command, then this file exists and holds the commit message of the
87  * original "pick" commit.  (If the series ends without a "squash"
88  * command, then this can be used as the commit message of the combined
89  * commit without opening the editor.)
90  */
91 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
92 /*
93  * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
94  * GIT_AUTHOR_DATE that will be used for the commit that is currently
95  * being rebased.
96  */
97 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
98 /*
99  * When an "edit" rebase command is being processed, the SHA1 of the
100  * commit to be edited is recorded in this file.  When "git rebase
101  * --continue" is executed, if there are any staged changes then they
102  * will be amended to the HEAD commit, but only provided the HEAD
103  * commit is still the commit to be edited.  When any other rebase
104  * command is processed, this file is deleted.
105  */
106 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
107 /*
108  * When we stop at a given patch via the "edit" command, this file contains
109  * the abbreviated commit name of the corresponding patch.
110  */
111 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
112 /*
113  * For the post-rewrite hook, we make a list of rewritten commits and
114  * their new sha1s.  The rewritten-pending list keeps the sha1s of
115  * commits that have been processed, but not committed yet,
116  * e.g. because they are waiting for a 'squash' command.
117  */
118 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
119 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
120         "rebase-merge/rewritten-pending")
121 /*
122  * The following files are written by git-rebase just after parsing the
123  * command-line (and are only consumed, not modified, by the sequencer).
124  */
125 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
126 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
127 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
128 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
129 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
130 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
131 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
132 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
133 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
134
135 static inline int is_rebase_i(const struct replay_opts *opts)
136 {
137         return opts->action == REPLAY_INTERACTIVE_REBASE;
138 }
139
140 static const char *get_dir(const struct replay_opts *opts)
141 {
142         if (is_rebase_i(opts))
143                 return rebase_path();
144         return git_path_seq_dir();
145 }
146
147 static const char *get_todo_path(const struct replay_opts *opts)
148 {
149         if (is_rebase_i(opts))
150                 return rebase_path_todo();
151         return git_path_todo_file();
152 }
153
154 /*
155  * Returns 0 for non-conforming footer
156  * Returns 1 for conforming footer
157  * Returns 2 when sob exists within conforming footer
158  * Returns 3 when sob exists within conforming footer as last entry
159  */
160 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
161         int ignore_footer)
162 {
163         struct trailer_info info;
164         int i;
165         int found_sob = 0, found_sob_last = 0;
166
167         trailer_info_get(&info, sb->buf);
168
169         if (info.trailer_start == info.trailer_end)
170                 return 0;
171
172         for (i = 0; i < info.trailer_nr; i++)
173                 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
174                         found_sob = 1;
175                         if (i == info.trailer_nr - 1)
176                                 found_sob_last = 1;
177                 }
178
179         trailer_info_release(&info);
180
181         if (found_sob_last)
182                 return 3;
183         if (found_sob)
184                 return 2;
185         return 1;
186 }
187
188 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
189 {
190         static struct strbuf buf = STRBUF_INIT;
191
192         strbuf_reset(&buf);
193         if (opts->gpg_sign)
194                 sq_quotef(&buf, "-S%s", opts->gpg_sign);
195         return buf.buf;
196 }
197
198 int sequencer_remove_state(struct replay_opts *opts)
199 {
200         struct strbuf dir = STRBUF_INIT;
201         int i;
202
203         free(opts->gpg_sign);
204         free(opts->strategy);
205         for (i = 0; i < opts->xopts_nr; i++)
206                 free(opts->xopts[i]);
207         free(opts->xopts);
208
209         strbuf_addstr(&dir, get_dir(opts));
210         remove_dir_recursively(&dir, 0);
211         strbuf_release(&dir);
212
213         return 0;
214 }
215
216 static const char *action_name(const struct replay_opts *opts)
217 {
218         switch (opts->action) {
219         case REPLAY_REVERT:
220                 return N_("revert");
221         case REPLAY_PICK:
222                 return N_("cherry-pick");
223         case REPLAY_INTERACTIVE_REBASE:
224                 return N_("rebase -i");
225         }
226         die(_("Unknown action: %d"), opts->action);
227 }
228
229 struct commit_message {
230         char *parent_label;
231         char *label;
232         char *subject;
233         const char *message;
234 };
235
236 static const char *short_commit_name(struct commit *commit)
237 {
238         return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
239 }
240
241 static int get_message(struct commit *commit, struct commit_message *out)
242 {
243         const char *abbrev, *subject;
244         int subject_len;
245
246         out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
247         abbrev = short_commit_name(commit);
248
249         subject_len = find_commit_subject(out->message, &subject);
250
251         out->subject = xmemdupz(subject, subject_len);
252         out->label = xstrfmt("%s... %s", abbrev, out->subject);
253         out->parent_label = xstrfmt("parent of %s", out->label);
254
255         return 0;
256 }
257
258 static void free_message(struct commit *commit, struct commit_message *msg)
259 {
260         free(msg->parent_label);
261         free(msg->label);
262         free(msg->subject);
263         unuse_commit_buffer(commit, msg->message);
264 }
265
266 static void print_advice(int show_hint, struct replay_opts *opts)
267 {
268         char *msg = getenv("GIT_CHERRY_PICK_HELP");
269
270         if (msg) {
271                 fprintf(stderr, "%s\n", msg);
272                 /*
273                  * A conflict has occurred but the porcelain
274                  * (typically rebase --interactive) wants to take care
275                  * of the commit itself so remove CHERRY_PICK_HEAD
276                  */
277                 unlink(git_path_cherry_pick_head());
278                 return;
279         }
280
281         if (show_hint) {
282                 if (opts->no_commit)
283                         advise(_("after resolving the conflicts, mark the corrected paths\n"
284                                  "with 'git add <paths>' or 'git rm <paths>'"));
285                 else
286                         advise(_("after resolving the conflicts, mark the corrected paths\n"
287                                  "with 'git add <paths>' or 'git rm <paths>'\n"
288                                  "and commit the result with 'git commit'"));
289         }
290 }
291
292 static int write_message(const void *buf, size_t len, const char *filename,
293                          int append_eol)
294 {
295         static struct lock_file msg_file;
296
297         int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
298         if (msg_fd < 0)
299                 return error_errno(_("could not lock '%s'"), filename);
300         if (write_in_full(msg_fd, buf, len) < 0) {
301                 rollback_lock_file(&msg_file);
302                 return error_errno(_("could not write to '%s'"), filename);
303         }
304         if (append_eol && write(msg_fd, "\n", 1) < 0) {
305                 rollback_lock_file(&msg_file);
306                 return error_errno(_("could not write eol to '%s'"), filename);
307         }
308         if (commit_lock_file(&msg_file) < 0) {
309                 rollback_lock_file(&msg_file);
310                 return error(_("failed to finalize '%s'."), filename);
311         }
312
313         return 0;
314 }
315
316 /*
317  * Reads a file that was presumably written by a shell script, i.e. with an
318  * end-of-line marker that needs to be stripped.
319  *
320  * Note that only the last end-of-line marker is stripped, consistent with the
321  * behavior of "$(cat path)" in a shell script.
322  *
323  * Returns 1 if the file was read, 0 if it could not be read or does not exist.
324  */
325 static int read_oneliner(struct strbuf *buf,
326         const char *path, int skip_if_empty)
327 {
328         int orig_len = buf->len;
329
330         if (!file_exists(path))
331                 return 0;
332
333         if (strbuf_read_file(buf, path, 0) < 0) {
334                 warning_errno(_("could not read '%s'"), path);
335                 return 0;
336         }
337
338         if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
339                 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
340                         --buf->len;
341                 buf->buf[buf->len] = '\0';
342         }
343
344         if (skip_if_empty && buf->len == orig_len)
345                 return 0;
346
347         return 1;
348 }
349
350 static struct tree *empty_tree(void)
351 {
352         return lookup_tree(&empty_tree_oid);
353 }
354
355 static int error_dirty_index(struct replay_opts *opts)
356 {
357         if (read_cache_unmerged())
358                 return error_resolve_conflict(_(action_name(opts)));
359
360         error(_("your local changes would be overwritten by %s."),
361                 _(action_name(opts)));
362
363         if (advice_commit_before_merge)
364                 advise(_("commit your changes or stash them to proceed."));
365         return -1;
366 }
367
368 static void update_abort_safety_file(void)
369 {
370         struct object_id head;
371
372         /* Do nothing on a single-pick */
373         if (!file_exists(git_path_seq_dir()))
374                 return;
375
376         if (!get_oid("HEAD", &head))
377                 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
378         else
379                 write_file(git_path_abort_safety_file(), "%s", "");
380 }
381
382 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
383                         int unborn, struct replay_opts *opts)
384 {
385         struct ref_transaction *transaction;
386         struct strbuf sb = STRBUF_INIT;
387         struct strbuf err = STRBUF_INIT;
388
389         read_cache();
390         if (checkout_fast_forward(from, to, 1))
391                 return -1; /* the callee should have complained already */
392
393         strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
394
395         transaction = ref_transaction_begin(&err);
396         if (!transaction ||
397             ref_transaction_update(transaction, "HEAD",
398                                    to, unborn ? &null_oid : from,
399                                    0, sb.buf, &err) ||
400             ref_transaction_commit(transaction, &err)) {
401                 ref_transaction_free(transaction);
402                 error("%s", err.buf);
403                 strbuf_release(&sb);
404                 strbuf_release(&err);
405                 return -1;
406         }
407
408         strbuf_release(&sb);
409         strbuf_release(&err);
410         ref_transaction_free(transaction);
411         update_abort_safety_file();
412         return 0;
413 }
414
415 void append_conflicts_hint(struct strbuf *msgbuf)
416 {
417         int i;
418
419         strbuf_addch(msgbuf, '\n');
420         strbuf_commented_addf(msgbuf, "Conflicts:\n");
421         for (i = 0; i < active_nr;) {
422                 const struct cache_entry *ce = active_cache[i++];
423                 if (ce_stage(ce)) {
424                         strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
425                         while (i < active_nr && !strcmp(ce->name,
426                                                         active_cache[i]->name))
427                                 i++;
428                 }
429         }
430 }
431
432 static int do_recursive_merge(struct commit *base, struct commit *next,
433                               const char *base_label, const char *next_label,
434                               struct object_id *head, struct strbuf *msgbuf,
435                               struct replay_opts *opts)
436 {
437         struct merge_options o;
438         struct tree *result, *next_tree, *base_tree, *head_tree;
439         int clean;
440         char **xopt;
441         static struct lock_file index_lock;
442
443         hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
444
445         read_cache();
446
447         init_merge_options(&o);
448         o.ancestor = base ? base_label : "(empty tree)";
449         o.branch1 = "HEAD";
450         o.branch2 = next ? next_label : "(empty tree)";
451         if (is_rebase_i(opts))
452                 o.buffer_output = 2;
453
454         head_tree = parse_tree_indirect(head);
455         next_tree = next ? next->tree : empty_tree();
456         base_tree = base ? base->tree : empty_tree();
457
458         for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
459                 parse_merge_opt(&o, *xopt);
460
461         clean = merge_trees(&o,
462                             head_tree,
463                             next_tree, base_tree, &result);
464         if (is_rebase_i(opts) && clean <= 0)
465                 fputs(o.obuf.buf, stdout);
466         strbuf_release(&o.obuf);
467         if (clean < 0)
468                 return clean;
469
470         if (active_cache_changed &&
471             write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
472                 /*
473                  * TRANSLATORS: %s will be "revert", "cherry-pick" or
474                  * "rebase -i".
475                  */
476                 return error(_("%s: Unable to write new index file"),
477                         _(action_name(opts)));
478         rollback_lock_file(&index_lock);
479
480         if (!clean)
481                 append_conflicts_hint(msgbuf);
482
483         return !clean;
484 }
485
486 static int is_index_unchanged(void)
487 {
488         struct object_id head_oid;
489         struct commit *head_commit;
490
491         if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
492                 return error(_("could not resolve HEAD commit\n"));
493
494         head_commit = lookup_commit(&head_oid);
495
496         /*
497          * If head_commit is NULL, check_commit, called from
498          * lookup_commit, would have indicated that head_commit is not
499          * a commit object already.  parse_commit() will return failure
500          * without further complaints in such a case.  Otherwise, if
501          * the commit is invalid, parse_commit() will complain.  So
502          * there is nothing for us to say here.  Just return failure.
503          */
504         if (parse_commit(head_commit))
505                 return -1;
506
507         if (!active_cache_tree)
508                 active_cache_tree = cache_tree();
509
510         if (!cache_tree_fully_valid(active_cache_tree))
511                 if (cache_tree_update(&the_index, 0))
512                         return error(_("unable to update cache tree\n"));
513
514         return !oidcmp(&active_cache_tree->oid,
515                        &head_commit->tree->object.oid);
516 }
517
518 static int write_author_script(const char *message)
519 {
520         struct strbuf buf = STRBUF_INIT;
521         const char *eol;
522         int res;
523
524         for (;;)
525                 if (!*message || starts_with(message, "\n")) {
526 missing_author:
527                         /* Missing 'author' line? */
528                         unlink(rebase_path_author_script());
529                         return 0;
530                 } else if (skip_prefix(message, "author ", &message))
531                         break;
532                 else if ((eol = strchr(message, '\n')))
533                         message = eol + 1;
534                 else
535                         goto missing_author;
536
537         strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
538         while (*message && *message != '\n' && *message != '\r')
539                 if (skip_prefix(message, " <", &message))
540                         break;
541                 else if (*message != '\'')
542                         strbuf_addch(&buf, *(message++));
543                 else
544                         strbuf_addf(&buf, "'\\\\%c'", *(message++));
545         strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
546         while (*message && *message != '\n' && *message != '\r')
547                 if (skip_prefix(message, "> ", &message))
548                         break;
549                 else if (*message != '\'')
550                         strbuf_addch(&buf, *(message++));
551                 else
552                         strbuf_addf(&buf, "'\\\\%c'", *(message++));
553         strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
554         while (*message && *message != '\n' && *message != '\r')
555                 if (*message != '\'')
556                         strbuf_addch(&buf, *(message++));
557                 else
558                         strbuf_addf(&buf, "'\\\\%c'", *(message++));
559         res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
560         strbuf_release(&buf);
561         return res;
562 }
563
564 /*
565  * Read a list of environment variable assignments (such as the author-script
566  * file) into an environment block. Returns -1 on error, 0 otherwise.
567  */
568 static int read_env_script(struct argv_array *env)
569 {
570         struct strbuf script = STRBUF_INIT;
571         int i, count = 0;
572         char *p, *p2;
573
574         if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
575                 return -1;
576
577         for (p = script.buf; *p; p++)
578                 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
579                         strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
580                 else if (*p == '\'')
581                         strbuf_splice(&script, p-- - script.buf, 1, "", 0);
582                 else if (*p == '\n') {
583                         *p = '\0';
584                         count++;
585                 }
586
587         for (i = 0, p = script.buf; i < count; i++) {
588                 argv_array_push(env, p);
589                 p += strlen(p) + 1;
590         }
591
592         return 0;
593 }
594
595 static char *get_author(const char *message)
596 {
597         size_t len;
598         const char *a;
599
600         a = find_commit_header(message, "author", &len);
601         if (a)
602                 return xmemdupz(a, len);
603
604         return NULL;
605 }
606
607 static const char staged_changes_advice[] =
608 N_("you have staged changes in your working tree\n"
609 "If these changes are meant to be squashed into the previous commit, run:\n"
610 "\n"
611 "  git commit --amend %s\n"
612 "\n"
613 "If they are meant to go into a new commit, run:\n"
614 "\n"
615 "  git commit %s\n"
616 "\n"
617 "In both cases, once you're done, continue with:\n"
618 "\n"
619 "  git rebase --continue\n");
620
621 #define ALLOW_EMPTY (1<<0)
622 #define EDIT_MSG    (1<<1)
623 #define AMEND_MSG   (1<<2)
624 #define CLEANUP_MSG (1<<3)
625 #define VERIFY_MSG  (1<<4)
626
627 /*
628  * If we are cherry-pick, and if the merge did not result in
629  * hand-editing, we will hit this commit and inherit the original
630  * author date and name.
631  *
632  * If we are revert, or if our cherry-pick results in a hand merge,
633  * we had better say that the current user is responsible for that.
634  *
635  * An exception is when run_git_commit() is called during an
636  * interactive rebase: in that case, we will want to retain the
637  * author metadata.
638  */
639 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
640                           unsigned int flags)
641 {
642         struct child_process cmd = CHILD_PROCESS_INIT;
643         const char *value;
644
645         cmd.git_cmd = 1;
646
647         if (is_rebase_i(opts)) {
648                 if (!(flags & EDIT_MSG)) {
649                         cmd.stdout_to_stderr = 1;
650                         cmd.err = -1;
651                 }
652
653                 if (read_env_script(&cmd.env_array)) {
654                         const char *gpg_opt = gpg_sign_opt_quoted(opts);
655
656                         return error(_(staged_changes_advice),
657                                      gpg_opt, gpg_opt);
658                 }
659         }
660
661         argv_array_push(&cmd.args, "commit");
662
663         if (!(flags & VERIFY_MSG))
664                 argv_array_push(&cmd.args, "-n");
665         if ((flags & AMEND_MSG))
666                 argv_array_push(&cmd.args, "--amend");
667         if (opts->gpg_sign)
668                 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
669         if (defmsg)
670                 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
671         if ((flags & CLEANUP_MSG))
672                 argv_array_push(&cmd.args, "--cleanup=strip");
673         if ((flags & EDIT_MSG))
674                 argv_array_push(&cmd.args, "-e");
675         else if (!(flags & CLEANUP_MSG) &&
676                  !opts->signoff && !opts->record_origin &&
677                  git_config_get_value("commit.cleanup", &value))
678                 argv_array_push(&cmd.args, "--cleanup=verbatim");
679
680         if ((flags & ALLOW_EMPTY))
681                 argv_array_push(&cmd.args, "--allow-empty");
682
683         if (opts->allow_empty_message)
684                 argv_array_push(&cmd.args, "--allow-empty-message");
685
686         if (cmd.err == -1) {
687                 /* hide stderr on success */
688                 struct strbuf buf = STRBUF_INIT;
689                 int rc = pipe_command(&cmd,
690                                       NULL, 0,
691                                       /* stdout is already redirected */
692                                       NULL, 0,
693                                       &buf, 0);
694                 if (rc)
695                         fputs(buf.buf, stderr);
696                 strbuf_release(&buf);
697                 return rc;
698         }
699
700         return run_command(&cmd);
701 }
702
703 static enum commit_msg_cleanup_mode default_msg_cleanup =
704                                                 COMMIT_MSG_CLEANUP_NONE;
705 static char *default_gpg_sign;
706
707 int git_sequencer_config(const char *k, const char *v, void *cb)
708 {
709         if (!strcmp(k, "commit.cleanup")) {
710                 int status;
711                 const char *s;
712
713                 status = git_config_string(&s, k, v);
714                 if (status)
715                         return status;
716
717                 if (!strcmp(s, "verbatim"))
718                         default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
719                 else if (!strcmp(s, "whitespace"))
720                         default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
721                 else if (!strcmp(s, "strip"))
722                         default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
723                 else if (!strcmp(s, "scissors"))
724                         default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
725
726                 return status;
727         }
728
729         if (!strcmp(k, "commit.gpgsign")) {
730                 default_gpg_sign = git_config_bool(k, v) ? "" : NULL;
731                 return 0;
732         }
733
734         return git_gpg_config(k, v, NULL);
735 }
736
737 static int rest_is_empty(const struct strbuf *sb, int start)
738 {
739         int i, eol;
740         const char *nl;
741
742         /* Check if the rest is just whitespace and Signed-off-by's. */
743         for (i = start; i < sb->len; i++) {
744                 nl = memchr(sb->buf + i, '\n', sb->len - i);
745                 if (nl)
746                         eol = nl - sb->buf;
747                 else
748                         eol = sb->len;
749
750                 if (strlen(sign_off_header) <= eol - i &&
751                     starts_with(sb->buf + i, sign_off_header)) {
752                         i = eol;
753                         continue;
754                 }
755                 while (i < eol)
756                         if (!isspace(sb->buf[i++]))
757                                 return 0;
758         }
759
760         return 1;
761 }
762
763 /*
764  * Find out if the message in the strbuf contains only whitespace and
765  * Signed-off-by lines.
766  */
767 int message_is_empty(const struct strbuf *sb,
768                      enum commit_msg_cleanup_mode cleanup_mode)
769 {
770         if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
771                 return 0;
772         return rest_is_empty(sb, 0);
773 }
774
775 /*
776  * See if the user edited the message in the editor or left what
777  * was in the template intact
778  */
779 int template_untouched(const struct strbuf *sb, const char *template_file,
780                        enum commit_msg_cleanup_mode cleanup_mode)
781 {
782         struct strbuf tmpl = STRBUF_INIT;
783         const char *start;
784
785         if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
786                 return 0;
787
788         if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
789                 return 0;
790
791         strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
792         if (!skip_prefix(sb->buf, tmpl.buf, &start))
793                 start = sb->buf;
794         strbuf_release(&tmpl);
795         return rest_is_empty(sb, start - sb->buf);
796 }
797
798 int update_head_with_reflog(const struct commit *old_head,
799                             const struct object_id *new_head,
800                             const char *action, const struct strbuf *msg,
801                             struct strbuf *err)
802 {
803         struct ref_transaction *transaction;
804         struct strbuf sb = STRBUF_INIT;
805         const char *nl;
806         int ret = 0;
807
808         if (action) {
809                 strbuf_addstr(&sb, action);
810                 strbuf_addstr(&sb, ": ");
811         }
812
813         nl = strchr(msg->buf, '\n');
814         if (nl) {
815                 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
816         } else {
817                 strbuf_addbuf(&sb, msg);
818                 strbuf_addch(&sb, '\n');
819         }
820
821         transaction = ref_transaction_begin(err);
822         if (!transaction ||
823             ref_transaction_update(transaction, "HEAD", new_head,
824                                    old_head ? &old_head->object.oid : &null_oid,
825                                    0, sb.buf, err) ||
826             ref_transaction_commit(transaction, err)) {
827                 ret = -1;
828         }
829         ref_transaction_free(transaction);
830         strbuf_release(&sb);
831
832         return ret;
833 }
834
835 static int run_rewrite_hook(const struct object_id *oldoid,
836                             const struct object_id *newoid)
837 {
838         struct child_process proc = CHILD_PROCESS_INIT;
839         const char *argv[3];
840         int code;
841         struct strbuf sb = STRBUF_INIT;
842
843         argv[0] = find_hook("post-rewrite");
844         if (!argv[0])
845                 return 0;
846
847         argv[1] = "amend";
848         argv[2] = NULL;
849
850         proc.argv = argv;
851         proc.in = -1;
852         proc.stdout_to_stderr = 1;
853
854         code = start_command(&proc);
855         if (code)
856                 return code;
857         strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
858         sigchain_push(SIGPIPE, SIG_IGN);
859         write_in_full(proc.in, sb.buf, sb.len);
860         close(proc.in);
861         strbuf_release(&sb);
862         sigchain_pop(SIGPIPE);
863         return finish_command(&proc);
864 }
865
866 void commit_post_rewrite(const struct commit *old_head,
867                          const struct object_id *new_head)
868 {
869         struct notes_rewrite_cfg *cfg;
870
871         cfg = init_copy_notes_for_rewrite("amend");
872         if (cfg) {
873                 /* we are amending, so old_head is not NULL */
874                 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
875                 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
876         }
877         run_rewrite_hook(&old_head->object.oid, new_head);
878 }
879
880 static const char implicit_ident_advice_noconfig[] =
881 N_("Your name and email address were configured automatically based\n"
882 "on your username and hostname. Please check that they are accurate.\n"
883 "You can suppress this message by setting them explicitly. Run the\n"
884 "following command and follow the instructions in your editor to edit\n"
885 "your configuration file:\n"
886 "\n"
887 "    git config --global --edit\n"
888 "\n"
889 "After doing this, you may fix the identity used for this commit with:\n"
890 "\n"
891 "    git commit --amend --reset-author\n");
892
893 static const char implicit_ident_advice_config[] =
894 N_("Your name and email address were configured automatically based\n"
895 "on your username and hostname. Please check that they are accurate.\n"
896 "You can suppress this message by setting them explicitly:\n"
897 "\n"
898 "    git config --global user.name \"Your Name\"\n"
899 "    git config --global user.email you@example.com\n"
900 "\n"
901 "After doing this, you may fix the identity used for this commit with:\n"
902 "\n"
903 "    git commit --amend --reset-author\n");
904
905 static const char *implicit_ident_advice(void)
906 {
907         char *user_config = expand_user_path("~/.gitconfig", 0);
908         char *xdg_config = xdg_config_home("config");
909         int config_exists = file_exists(user_config) || file_exists(xdg_config);
910
911         free(user_config);
912         free(xdg_config);
913
914         if (config_exists)
915                 return _(implicit_ident_advice_config);
916         else
917                 return _(implicit_ident_advice_noconfig);
918
919 }
920
921 void print_commit_summary(const char *prefix, const struct object_id *oid,
922                           unsigned int flags)
923 {
924         struct rev_info rev;
925         struct commit *commit;
926         struct strbuf format = STRBUF_INIT;
927         const char *head;
928         struct pretty_print_context pctx = {0};
929         struct strbuf author_ident = STRBUF_INIT;
930         struct strbuf committer_ident = STRBUF_INIT;
931
932         commit = lookup_commit(oid);
933         if (!commit)
934                 die(_("couldn't look up newly created commit"));
935         if (parse_commit(commit))
936                 die(_("could not parse newly created commit"));
937
938         strbuf_addstr(&format, "format:%h] %s");
939
940         format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
941         format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
942         if (strbuf_cmp(&author_ident, &committer_ident)) {
943                 strbuf_addstr(&format, "\n Author: ");
944                 strbuf_addbuf_percentquote(&format, &author_ident);
945         }
946         if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
947                 struct strbuf date = STRBUF_INIT;
948
949                 format_commit_message(commit, "%ad", &date, &pctx);
950                 strbuf_addstr(&format, "\n Date: ");
951                 strbuf_addbuf_percentquote(&format, &date);
952                 strbuf_release(&date);
953         }
954         if (!committer_ident_sufficiently_given()) {
955                 strbuf_addstr(&format, "\n Committer: ");
956                 strbuf_addbuf_percentquote(&format, &committer_ident);
957                 if (advice_implicit_identity) {
958                         strbuf_addch(&format, '\n');
959                         strbuf_addstr(&format, implicit_ident_advice());
960                 }
961         }
962         strbuf_release(&author_ident);
963         strbuf_release(&committer_ident);
964
965         init_revisions(&rev, prefix);
966         setup_revisions(0, NULL, &rev, NULL);
967
968         rev.diff = 1;
969         rev.diffopt.output_format =
970                 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
971
972         rev.verbose_header = 1;
973         rev.show_root_diff = 1;
974         get_commit_format(format.buf, &rev);
975         rev.always_show_header = 0;
976         rev.diffopt.detect_rename = 1;
977         rev.diffopt.break_opt = 0;
978         diff_setup_done(&rev.diffopt);
979
980         head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
981         if (!head)
982                 die_errno(_("unable to resolve HEAD after creating commit"));
983         if (!strcmp(head, "HEAD"))
984                 head = _("detached HEAD");
985         else
986                 skip_prefix(head, "refs/heads/", &head);
987         printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
988                                                 _(" (root-commit)") : "");
989
990         if (!log_tree_commit(&rev, commit)) {
991                 rev.always_show_header = 1;
992                 rev.use_terminator = 1;
993                 log_tree_commit(&rev, commit);
994         }
995
996         strbuf_release(&format);
997 }
998
999 static int parse_head(struct commit **head)
1000 {
1001         struct commit *current_head;
1002         struct object_id oid;
1003
1004         if (get_oid("HEAD", &oid)) {
1005                 current_head = NULL;
1006         } else {
1007                 current_head = lookup_commit_reference(&oid);
1008                 if (!current_head)
1009                         return error(_("could not parse HEAD"));
1010                 if (oidcmp(&oid, &current_head->object.oid)) {
1011                         warning(_("HEAD %s is not a commit!"),
1012                                 oid_to_hex(&oid));
1013                 }
1014                 if (parse_commit(current_head))
1015                         return error(_("could not parse HEAD commit"));
1016         }
1017         *head = current_head;
1018
1019         return 0;
1020 }
1021
1022 /*
1023  * Try to commit without forking 'git commit'. In some cases we need
1024  * to run 'git commit' to display an error message
1025  *
1026  * Returns:
1027  *  -1 - error unable to commit
1028  *   0 - success
1029  *   1 - run 'git commit'
1030  */
1031 static int try_to_commit(struct strbuf *msg, const char *author,
1032                          struct replay_opts *opts, unsigned int flags,
1033                          struct object_id *oid)
1034 {
1035         struct object_id tree;
1036         struct commit *current_head;
1037         struct commit_list *parents = NULL;
1038         struct commit_extra_header *extra = NULL;
1039         struct strbuf err = STRBUF_INIT;
1040         struct strbuf amend_msg = STRBUF_INIT;
1041         char *amend_author = NULL;
1042         const char *gpg_sign;
1043         enum commit_msg_cleanup_mode cleanup;
1044         int res = 0;
1045
1046         if (parse_head(&current_head))
1047                 return -1;
1048
1049         if (flags & AMEND_MSG) {
1050                 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1051                 const char *out_enc = get_commit_output_encoding();
1052                 const char *message = logmsg_reencode(current_head, NULL,
1053                                                       out_enc);
1054
1055                 if (!msg) {
1056                         const char *orig_message = NULL;
1057
1058                         find_commit_subject(message, &orig_message);
1059                         msg = &amend_msg;
1060                         strbuf_addstr(msg, orig_message);
1061                 }
1062                 author = amend_author = get_author(message);
1063                 unuse_commit_buffer(current_head, message);
1064                 if (!author) {
1065                         res = error(_("unable to parse commit author"));
1066                         goto out;
1067                 }
1068                 parents = copy_commit_list(current_head->parents);
1069                 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1070         } else if (current_head) {
1071                 commit_list_insert(current_head, &parents);
1072         }
1073
1074         cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1075                                           default_msg_cleanup;
1076         if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1077                 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1078         if (!opts->allow_empty_message && message_is_empty(msg, cleanup)) {
1079                 res = 1; /* run 'git commit' to display error message */
1080                 goto out;
1081         }
1082
1083         gpg_sign = opts->gpg_sign ? opts->gpg_sign : default_gpg_sign;
1084
1085         if (write_cache_as_tree(tree.hash, 0, NULL)) {
1086                 res = error(_("git write-tree failed to write a tree"));
1087                 goto out;
1088         }
1089
1090         if (!(flags & ALLOW_EMPTY) && !oidcmp(current_head ?
1091                                               &current_head->tree->object.oid :
1092                                               &empty_tree_oid, &tree)) {
1093                 res = 1; /* run 'git commit' to display error message */
1094                 goto out;
1095         }
1096
1097         if (commit_tree_extended(msg->buf, msg->len, tree.hash, parents,
1098                                  oid->hash, author, gpg_sign, extra)) {
1099                 res = error(_("failed to write commit object"));
1100                 goto out;
1101         }
1102
1103         if (update_head_with_reflog(current_head, oid,
1104                                     getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1105                 res = error("%s", err.buf);
1106                 goto out;
1107         }
1108
1109         if (flags & AMEND_MSG)
1110                 commit_post_rewrite(current_head, oid);
1111
1112 out:
1113         free_commit_extra_headers(extra);
1114         strbuf_release(&err);
1115         strbuf_release(&amend_msg);
1116         free(amend_author);
1117
1118         return res;
1119 }
1120
1121 static int do_commit(const char *msg_file, const char *author,
1122                      struct replay_opts *opts, unsigned int flags)
1123 {
1124         int res = 1;
1125
1126         if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1127                 struct object_id oid;
1128                 struct strbuf sb = STRBUF_INIT;
1129
1130                 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1131                         return error_errno(_("unable to read commit message "
1132                                              "from '%s'"),
1133                                            msg_file);
1134
1135                 res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1136                                     &oid);
1137                 strbuf_release(&sb);
1138                 if (!res) {
1139                         unlink(git_path_cherry_pick_head());
1140                         unlink(git_path_merge_msg());
1141                         if (!is_rebase_i(opts))
1142                                 print_commit_summary(NULL, &oid,
1143                                                 SUMMARY_SHOW_AUTHOR_DATE);
1144                         return res;
1145                 }
1146         }
1147         if (res == 1)
1148                 return run_git_commit(msg_file, opts, flags);
1149
1150         return res;
1151 }
1152
1153 static int is_original_commit_empty(struct commit *commit)
1154 {
1155         const struct object_id *ptree_oid;
1156
1157         if (parse_commit(commit))
1158                 return error(_("could not parse commit %s\n"),
1159                              oid_to_hex(&commit->object.oid));
1160         if (commit->parents) {
1161                 struct commit *parent = commit->parents->item;
1162                 if (parse_commit(parent))
1163                         return error(_("could not parse parent commit %s\n"),
1164                                 oid_to_hex(&parent->object.oid));
1165                 ptree_oid = &parent->tree->object.oid;
1166         } else {
1167                 ptree_oid = &empty_tree_oid; /* commit is root */
1168         }
1169
1170         return !oidcmp(ptree_oid, &commit->tree->object.oid);
1171 }
1172
1173 /*
1174  * Do we run "git commit" with "--allow-empty"?
1175  */
1176 static int allow_empty(struct replay_opts *opts, struct commit *commit)
1177 {
1178         int index_unchanged, empty_commit;
1179
1180         /*
1181          * Three cases:
1182          *
1183          * (1) we do not allow empty at all and error out.
1184          *
1185          * (2) we allow ones that were initially empty, but
1186          * forbid the ones that become empty;
1187          *
1188          * (3) we allow both.
1189          */
1190         if (!opts->allow_empty)
1191                 return 0; /* let "git commit" barf as necessary */
1192
1193         index_unchanged = is_index_unchanged();
1194         if (index_unchanged < 0)
1195                 return index_unchanged;
1196         if (!index_unchanged)
1197                 return 0; /* we do not have to say --allow-empty */
1198
1199         if (opts->keep_redundant_commits)
1200                 return 1;
1201
1202         empty_commit = is_original_commit_empty(commit);
1203         if (empty_commit < 0)
1204                 return empty_commit;
1205         if (!empty_commit)
1206                 return 0;
1207         else
1208                 return 1;
1209 }
1210
1211 /*
1212  * Note that ordering matters in this enum. Not only must it match the mapping
1213  * below, it is also divided into several sections that matter.  When adding
1214  * new commands, make sure you add it in the right section.
1215  */
1216 enum todo_command {
1217         /* commands that handle commits */
1218         TODO_PICK = 0,
1219         TODO_REVERT,
1220         TODO_EDIT,
1221         TODO_REWORD,
1222         TODO_FIXUP,
1223         TODO_SQUASH,
1224         /* commands that do something else than handling a single commit */
1225         TODO_EXEC,
1226         /* commands that do nothing but are counted for reporting progress */
1227         TODO_NOOP,
1228         TODO_DROP,
1229         /* comments (not counted for reporting progress) */
1230         TODO_COMMENT
1231 };
1232
1233 static struct {
1234         char c;
1235         const char *str;
1236 } todo_command_info[] = {
1237         { 'p', "pick" },
1238         { 0,   "revert" },
1239         { 'e', "edit" },
1240         { 'r', "reword" },
1241         { 'f', "fixup" },
1242         { 's', "squash" },
1243         { 'x', "exec" },
1244         { 0,   "noop" },
1245         { 'd', "drop" },
1246         { 0,   NULL }
1247 };
1248
1249 static const char *command_to_string(const enum todo_command command)
1250 {
1251         if (command < TODO_COMMENT)
1252                 return todo_command_info[command].str;
1253         die("Unknown command: %d", command);
1254 }
1255
1256 static int is_noop(const enum todo_command command)
1257 {
1258         return TODO_NOOP <= command;
1259 }
1260
1261 static int is_fixup(enum todo_command command)
1262 {
1263         return command == TODO_FIXUP || command == TODO_SQUASH;
1264 }
1265
1266 static int update_squash_messages(enum todo_command command,
1267                 struct commit *commit, struct replay_opts *opts)
1268 {
1269         struct strbuf buf = STRBUF_INIT;
1270         int count, res;
1271         const char *message, *body;
1272
1273         if (file_exists(rebase_path_squash_msg())) {
1274                 struct strbuf header = STRBUF_INIT;
1275                 char *eol, *p;
1276
1277                 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
1278                         return error(_("could not read '%s'"),
1279                                 rebase_path_squash_msg());
1280
1281                 p = buf.buf + 1;
1282                 eol = strchrnul(buf.buf, '\n');
1283                 if (buf.buf[0] != comment_line_char ||
1284                     (p += strcspn(p, "0123456789\n")) == eol)
1285                         return error(_("unexpected 1st line of squash message:"
1286                                        "\n\n\t%.*s"),
1287                                      (int)(eol - buf.buf), buf.buf);
1288                 count = strtol(p, NULL, 10);
1289
1290                 if (count < 1)
1291                         return error(_("invalid 1st line of squash message:\n"
1292                                        "\n\t%.*s"),
1293                                      (int)(eol - buf.buf), buf.buf);
1294
1295                 strbuf_addf(&header, "%c ", comment_line_char);
1296                 strbuf_addf(&header,
1297                             _("This is a combination of %d commits."), ++count);
1298                 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1299                 strbuf_release(&header);
1300         } else {
1301                 struct object_id head;
1302                 struct commit *head_commit;
1303                 const char *head_message, *body;
1304
1305                 if (get_oid("HEAD", &head))
1306                         return error(_("need a HEAD to fixup"));
1307                 if (!(head_commit = lookup_commit_reference(&head)))
1308                         return error(_("could not read HEAD"));
1309                 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1310                         return error(_("could not read HEAD's commit message"));
1311
1312                 find_commit_subject(head_message, &body);
1313                 if (write_message(body, strlen(body),
1314                                   rebase_path_fixup_msg(), 0)) {
1315                         unuse_commit_buffer(head_commit, head_message);
1316                         return error(_("cannot write '%s'"),
1317                                      rebase_path_fixup_msg());
1318                 }
1319
1320                 count = 2;
1321                 strbuf_addf(&buf, "%c ", comment_line_char);
1322                 strbuf_addf(&buf, _("This is a combination of %d commits."),
1323                             count);
1324                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1325                 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1326                 strbuf_addstr(&buf, "\n\n");
1327                 strbuf_addstr(&buf, body);
1328
1329                 unuse_commit_buffer(head_commit, head_message);
1330         }
1331
1332         if (!(message = get_commit_buffer(commit, NULL)))
1333                 return error(_("could not read commit message of %s"),
1334                              oid_to_hex(&commit->object.oid));
1335         find_commit_subject(message, &body);
1336
1337         if (command == TODO_SQUASH) {
1338                 unlink(rebase_path_fixup_msg());
1339                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1340                 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
1341                 strbuf_addstr(&buf, "\n\n");
1342                 strbuf_addstr(&buf, body);
1343         } else if (command == TODO_FIXUP) {
1344                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1345                 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1346                             count);
1347                 strbuf_addstr(&buf, "\n\n");
1348                 strbuf_add_commented_lines(&buf, body, strlen(body));
1349         } else
1350                 return error(_("unknown command: %d"), command);
1351         unuse_commit_buffer(commit, message);
1352
1353         res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1354         strbuf_release(&buf);
1355         return res;
1356 }
1357
1358 static void flush_rewritten_pending(void) {
1359         struct strbuf buf = STRBUF_INIT;
1360         struct object_id newoid;
1361         FILE *out;
1362
1363         if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1364             !get_oid("HEAD", &newoid) &&
1365             (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1366                 char *bol = buf.buf, *eol;
1367
1368                 while (*bol) {
1369                         eol = strchrnul(bol, '\n');
1370                         fprintf(out, "%.*s %s\n", (int)(eol - bol),
1371                                         bol, oid_to_hex(&newoid));
1372                         if (!*eol)
1373                                 break;
1374                         bol = eol + 1;
1375                 }
1376                 fclose(out);
1377                 unlink(rebase_path_rewritten_pending());
1378         }
1379         strbuf_release(&buf);
1380 }
1381
1382 static void record_in_rewritten(struct object_id *oid,
1383                 enum todo_command next_command) {
1384         FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1385
1386         if (!out)
1387                 return;
1388
1389         fprintf(out, "%s\n", oid_to_hex(oid));
1390         fclose(out);
1391
1392         if (!is_fixup(next_command))
1393                 flush_rewritten_pending();
1394 }
1395
1396 static int do_pick_commit(enum todo_command command, struct commit *commit,
1397                 struct replay_opts *opts, int final_fixup)
1398 {
1399         unsigned int flags = opts->edit ? EDIT_MSG : 0;
1400         const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1401         struct object_id head;
1402         struct commit *base, *next, *parent;
1403         const char *base_label, *next_label;
1404         char *author = NULL;
1405         struct commit_message msg = { NULL, NULL, NULL, NULL };
1406         struct strbuf msgbuf = STRBUF_INIT;
1407         int res, unborn = 0, allow;
1408
1409         if (opts->no_commit) {
1410                 /*
1411                  * We do not intend to commit immediately.  We just want to
1412                  * merge the differences in, so let's compute the tree
1413                  * that represents the "current" state for merge-recursive
1414                  * to work on.
1415                  */
1416                 if (write_cache_as_tree(head.hash, 0, NULL))
1417                         return error(_("your index file is unmerged."));
1418         } else {
1419                 unborn = get_oid("HEAD", &head);
1420                 if (unborn)
1421                         oidcpy(&head, &empty_tree_oid);
1422                 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1423                                        NULL, 0))
1424                         return error_dirty_index(opts);
1425         }
1426         discard_cache();
1427
1428         if (!commit->parents)
1429                 parent = NULL;
1430         else if (commit->parents->next) {
1431                 /* Reverting or cherry-picking a merge commit */
1432                 int cnt;
1433                 struct commit_list *p;
1434
1435                 if (!opts->mainline)
1436                         return error(_("commit %s is a merge but no -m option was given."),
1437                                 oid_to_hex(&commit->object.oid));
1438
1439                 for (cnt = 1, p = commit->parents;
1440                      cnt != opts->mainline && p;
1441                      cnt++)
1442                         p = p->next;
1443                 if (cnt != opts->mainline || !p)
1444                         return error(_("commit %s does not have parent %d"),
1445                                 oid_to_hex(&commit->object.oid), opts->mainline);
1446                 parent = p->item;
1447         } else if (0 < opts->mainline)
1448                 return error(_("mainline was specified but commit %s is not a merge."),
1449                         oid_to_hex(&commit->object.oid));
1450         else
1451                 parent = commit->parents->item;
1452
1453         if (get_message(commit, &msg) != 0)
1454                 return error(_("cannot get commit message for %s"),
1455                         oid_to_hex(&commit->object.oid));
1456
1457         if (opts->allow_ff && !is_fixup(command) &&
1458             ((parent && !oidcmp(&parent->object.oid, &head)) ||
1459              (!parent && unborn))) {
1460                 if (is_rebase_i(opts))
1461                         write_author_script(msg.message);
1462                 res = fast_forward_to(&commit->object.oid, &head, unborn,
1463                         opts);
1464                 if (res || command != TODO_REWORD)
1465                         goto leave;
1466                 flags |= EDIT_MSG | AMEND_MSG;
1467                 if (command == TODO_REWORD)
1468                         flags |= VERIFY_MSG;
1469                 msg_file = NULL;
1470                 goto fast_forward_edit;
1471         }
1472         if (parent && parse_commit(parent) < 0)
1473                 /* TRANSLATORS: The first %s will be a "todo" command like
1474                    "revert" or "pick", the second %s a SHA1. */
1475                 return error(_("%s: cannot parse parent commit %s"),
1476                         command_to_string(command),
1477                         oid_to_hex(&parent->object.oid));
1478
1479         /*
1480          * "commit" is an existing commit.  We would want to apply
1481          * the difference it introduces since its first parent "prev"
1482          * on top of the current HEAD if we are cherry-pick.  Or the
1483          * reverse of it if we are revert.
1484          */
1485
1486         if (command == TODO_REVERT) {
1487                 base = commit;
1488                 base_label = msg.label;
1489                 next = parent;
1490                 next_label = msg.parent_label;
1491                 strbuf_addstr(&msgbuf, "Revert \"");
1492                 strbuf_addstr(&msgbuf, msg.subject);
1493                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1494                 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1495
1496                 if (commit->parents && commit->parents->next) {
1497                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1498                         strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1499                 }
1500                 strbuf_addstr(&msgbuf, ".\n");
1501         } else {
1502                 const char *p;
1503
1504                 base = parent;
1505                 base_label = msg.parent_label;
1506                 next = commit;
1507                 next_label = msg.label;
1508
1509                 /* Append the commit log message to msgbuf. */
1510                 if (find_commit_subject(msg.message, &p))
1511                         strbuf_addstr(&msgbuf, p);
1512
1513                 if (opts->record_origin) {
1514                         strbuf_complete_line(&msgbuf);
1515                         if (!has_conforming_footer(&msgbuf, NULL, 0))
1516                                 strbuf_addch(&msgbuf, '\n');
1517                         strbuf_addstr(&msgbuf, cherry_picked_prefix);
1518                         strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1519                         strbuf_addstr(&msgbuf, ")\n");
1520                 }
1521                 if (!is_fixup(command))
1522                         author = get_author(msg.message);
1523         }
1524
1525         if (command == TODO_REWORD)
1526                 flags |= EDIT_MSG | VERIFY_MSG;
1527         else if (is_fixup(command)) {
1528                 if (update_squash_messages(command, commit, opts))
1529                         return -1;
1530                 flags |= AMEND_MSG;
1531                 if (!final_fixup)
1532                         msg_file = rebase_path_squash_msg();
1533                 else if (file_exists(rebase_path_fixup_msg())) {
1534                         flags |= CLEANUP_MSG;
1535                         msg_file = rebase_path_fixup_msg();
1536                 } else {
1537                         const char *dest = git_path_squash_msg();
1538                         unlink(dest);
1539                         if (copy_file(dest, rebase_path_squash_msg(), 0666))
1540                                 return error(_("could not rename '%s' to '%s'"),
1541                                              rebase_path_squash_msg(), dest);
1542                         unlink(git_path_merge_msg());
1543                         msg_file = dest;
1544                         flags |= EDIT_MSG;
1545                 }
1546         }
1547
1548         if (opts->signoff)
1549                 append_signoff(&msgbuf, 0, 0);
1550
1551         if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1552                 res = -1;
1553         else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1554                 res = do_recursive_merge(base, next, base_label, next_label,
1555                                          &head, &msgbuf, opts);
1556                 if (res < 0)
1557                         return res;
1558                 res |= write_message(msgbuf.buf, msgbuf.len,
1559                                      git_path_merge_msg(), 0);
1560         } else {
1561                 struct commit_list *common = NULL;
1562                 struct commit_list *remotes = NULL;
1563
1564                 res = write_message(msgbuf.buf, msgbuf.len,
1565                                     git_path_merge_msg(), 0);
1566
1567                 commit_list_insert(base, &common);
1568                 commit_list_insert(next, &remotes);
1569                 res |= try_merge_command(opts->strategy,
1570                                          opts->xopts_nr, (const char **)opts->xopts,
1571                                         common, oid_to_hex(&head), remotes);
1572                 free_commit_list(common);
1573                 free_commit_list(remotes);
1574         }
1575         strbuf_release(&msgbuf);
1576
1577         /*
1578          * If the merge was clean or if it failed due to conflict, we write
1579          * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1580          * However, if the merge did not even start, then we don't want to
1581          * write it at all.
1582          */
1583         if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1584             update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1585                        REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1586                 res = -1;
1587         if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1588             update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1589                        REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1590                 res = -1;
1591
1592         if (res) {
1593                 error(command == TODO_REVERT
1594                       ? _("could not revert %s... %s")
1595                       : _("could not apply %s... %s"),
1596                       short_commit_name(commit), msg.subject);
1597                 print_advice(res == 1, opts);
1598                 rerere(opts->allow_rerere_auto);
1599                 goto leave;
1600         }
1601
1602         allow = allow_empty(opts, commit);
1603         if (allow < 0) {
1604                 res = allow;
1605                 goto leave;
1606         } else if (allow)
1607                 flags |= ALLOW_EMPTY;
1608         if (!opts->no_commit) {
1609 fast_forward_edit:
1610                 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1611                         res = do_commit(msg_file, author, opts, flags);
1612                 else
1613                         res = error(_("unable to parse commit author"));
1614         }
1615
1616         if (!res && final_fixup) {
1617                 unlink(rebase_path_fixup_msg());
1618                 unlink(rebase_path_squash_msg());
1619         }
1620
1621 leave:
1622         free_message(commit, &msg);
1623         free(author);
1624         update_abort_safety_file();
1625
1626         return res;
1627 }
1628
1629 static int prepare_revs(struct replay_opts *opts)
1630 {
1631         /*
1632          * picking (but not reverting) ranges (but not individual revisions)
1633          * should be done in reverse
1634          */
1635         if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1636                 opts->revs->reverse ^= 1;
1637
1638         if (prepare_revision_walk(opts->revs))
1639                 return error(_("revision walk setup failed"));
1640
1641         if (!opts->revs->commits)
1642                 return error(_("empty commit set passed"));
1643         return 0;
1644 }
1645
1646 static int read_and_refresh_cache(struct replay_opts *opts)
1647 {
1648         static struct lock_file index_lock;
1649         int index_fd = hold_locked_index(&index_lock, 0);
1650         if (read_index_preload(&the_index, NULL) < 0) {
1651                 rollback_lock_file(&index_lock);
1652                 return error(_("git %s: failed to read the index"),
1653                         _(action_name(opts)));
1654         }
1655         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1656         if (the_index.cache_changed && index_fd >= 0) {
1657                 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1658                         return error(_("git %s: failed to refresh the index"),
1659                                 _(action_name(opts)));
1660                 }
1661         }
1662         rollback_lock_file(&index_lock);
1663         return 0;
1664 }
1665
1666 struct todo_item {
1667         enum todo_command command;
1668         struct commit *commit;
1669         const char *arg;
1670         int arg_len;
1671         size_t offset_in_buf;
1672 };
1673
1674 struct todo_list {
1675         struct strbuf buf;
1676         struct todo_item *items;
1677         int nr, alloc, current;
1678         int done_nr, total_nr;
1679         struct stat_data stat;
1680 };
1681
1682 #define TODO_LIST_INIT { STRBUF_INIT }
1683
1684 static void todo_list_release(struct todo_list *todo_list)
1685 {
1686         strbuf_release(&todo_list->buf);
1687         FREE_AND_NULL(todo_list->items);
1688         todo_list->nr = todo_list->alloc = 0;
1689 }
1690
1691 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1692 {
1693         ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1694         return todo_list->items + todo_list->nr++;
1695 }
1696
1697 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1698 {
1699         struct object_id commit_oid;
1700         char *end_of_object_name;
1701         int i, saved, status, padding;
1702
1703         /* left-trim */
1704         bol += strspn(bol, " \t");
1705
1706         if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1707                 item->command = TODO_COMMENT;
1708                 item->commit = NULL;
1709                 item->arg = bol;
1710                 item->arg_len = eol - bol;
1711                 return 0;
1712         }
1713
1714         for (i = 0; i < TODO_COMMENT; i++)
1715                 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1716                         item->command = i;
1717                         break;
1718                 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1719                         bol++;
1720                         item->command = i;
1721                         break;
1722                 }
1723         if (i >= TODO_COMMENT)
1724                 return -1;
1725
1726         if (item->command == TODO_NOOP) {
1727                 item->commit = NULL;
1728                 item->arg = bol;
1729                 item->arg_len = eol - bol;
1730                 return 0;
1731         }
1732
1733         /* Eat up extra spaces/ tabs before object name */
1734         padding = strspn(bol, " \t");
1735         if (!padding)
1736                 return -1;
1737         bol += padding;
1738
1739         if (item->command == TODO_EXEC) {
1740                 item->arg = bol;
1741                 item->arg_len = (int)(eol - bol);
1742                 return 0;
1743         }
1744
1745         end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1746         saved = *end_of_object_name;
1747         *end_of_object_name = '\0';
1748         status = get_oid(bol, &commit_oid);
1749         *end_of_object_name = saved;
1750
1751         item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1752         item->arg_len = (int)(eol - item->arg);
1753
1754         if (status < 0)
1755                 return -1;
1756
1757         item->commit = lookup_commit_reference(&commit_oid);
1758         return !item->commit;
1759 }
1760
1761 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1762 {
1763         struct todo_item *item;
1764         char *p = buf, *next_p;
1765         int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1766
1767         for (i = 1; *p; i++, p = next_p) {
1768                 char *eol = strchrnul(p, '\n');
1769
1770                 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1771
1772                 if (p != eol && eol[-1] == '\r')
1773                         eol--; /* strip Carriage Return */
1774
1775                 item = append_new_todo(todo_list);
1776                 item->offset_in_buf = p - todo_list->buf.buf;
1777                 if (parse_insn_line(item, p, eol)) {
1778                         res = error(_("invalid line %d: %.*s"),
1779                                 i, (int)(eol - p), p);
1780                         item->command = TODO_NOOP;
1781                 }
1782
1783                 if (fixup_okay)
1784                         ; /* do nothing */
1785                 else if (is_fixup(item->command))
1786                         return error(_("cannot '%s' without a previous commit"),
1787                                 command_to_string(item->command));
1788                 else if (!is_noop(item->command))
1789                         fixup_okay = 1;
1790         }
1791
1792         return res;
1793 }
1794
1795 static int count_commands(struct todo_list *todo_list)
1796 {
1797         int count = 0, i;
1798
1799         for (i = 0; i < todo_list->nr; i++)
1800                 if (todo_list->items[i].command != TODO_COMMENT)
1801                         count++;
1802
1803         return count;
1804 }
1805
1806 static int read_populate_todo(struct todo_list *todo_list,
1807                         struct replay_opts *opts)
1808 {
1809         struct stat st;
1810         const char *todo_file = get_todo_path(opts);
1811         int fd, res;
1812
1813         strbuf_reset(&todo_list->buf);
1814         fd = open(todo_file, O_RDONLY);
1815         if (fd < 0)
1816                 return error_errno(_("could not open '%s'"), todo_file);
1817         if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1818                 close(fd);
1819                 return error(_("could not read '%s'."), todo_file);
1820         }
1821         close(fd);
1822
1823         res = stat(todo_file, &st);
1824         if (res)
1825                 return error(_("could not stat '%s'"), todo_file);
1826         fill_stat_data(&todo_list->stat, &st);
1827
1828         res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1829         if (res) {
1830                 if (is_rebase_i(opts))
1831                         return error(_("please fix this using "
1832                                        "'git rebase --edit-todo'."));
1833                 return error(_("unusable instruction sheet: '%s'"), todo_file);
1834         }
1835
1836         if (!todo_list->nr &&
1837             (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1838                 return error(_("no commits parsed."));
1839
1840         if (!is_rebase_i(opts)) {
1841                 enum todo_command valid =
1842                         opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1843                 int i;
1844
1845                 for (i = 0; i < todo_list->nr; i++)
1846                         if (valid == todo_list->items[i].command)
1847                                 continue;
1848                         else if (valid == TODO_PICK)
1849                                 return error(_("cannot cherry-pick during a revert."));
1850                         else
1851                                 return error(_("cannot revert during a cherry-pick."));
1852         }
1853
1854         if (is_rebase_i(opts)) {
1855                 struct todo_list done = TODO_LIST_INIT;
1856                 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
1857
1858                 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1859                                 !parse_insn_buffer(done.buf.buf, &done))
1860                         todo_list->done_nr = count_commands(&done);
1861                 else
1862                         todo_list->done_nr = 0;
1863
1864                 todo_list->total_nr = todo_list->done_nr
1865                         + count_commands(todo_list);
1866                 todo_list_release(&done);
1867
1868                 if (f) {
1869                         fprintf(f, "%d\n", todo_list->total_nr);
1870                         fclose(f);
1871                 }
1872         }
1873
1874         return 0;
1875 }
1876
1877 static int git_config_string_dup(char **dest,
1878                                  const char *var, const char *value)
1879 {
1880         if (!value)
1881                 return config_error_nonbool(var);
1882         free(*dest);
1883         *dest = xstrdup(value);
1884         return 0;
1885 }
1886
1887 static int populate_opts_cb(const char *key, const char *value, void *data)
1888 {
1889         struct replay_opts *opts = data;
1890         int error_flag = 1;
1891
1892         if (!value)
1893                 error_flag = 0;
1894         else if (!strcmp(key, "options.no-commit"))
1895                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1896         else if (!strcmp(key, "options.edit"))
1897                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1898         else if (!strcmp(key, "options.signoff"))
1899                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1900         else if (!strcmp(key, "options.record-origin"))
1901                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1902         else if (!strcmp(key, "options.allow-ff"))
1903                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1904         else if (!strcmp(key, "options.mainline"))
1905                 opts->mainline = git_config_int(key, value);
1906         else if (!strcmp(key, "options.strategy"))
1907                 git_config_string_dup(&opts->strategy, key, value);
1908         else if (!strcmp(key, "options.gpg-sign"))
1909                 git_config_string_dup(&opts->gpg_sign, key, value);
1910         else if (!strcmp(key, "options.strategy-option")) {
1911                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1912                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1913         } else if (!strcmp(key, "options.allow-rerere-auto"))
1914                 opts->allow_rerere_auto =
1915                         git_config_bool_or_int(key, value, &error_flag) ?
1916                                 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
1917         else
1918                 return error(_("invalid key: %s"), key);
1919
1920         if (!error_flag)
1921                 return error(_("invalid value for %s: %s"), key, value);
1922
1923         return 0;
1924 }
1925
1926 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1927 {
1928         int i;
1929
1930         strbuf_reset(buf);
1931         if (!read_oneliner(buf, rebase_path_strategy(), 0))
1932                 return;
1933         opts->strategy = strbuf_detach(buf, NULL);
1934         if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
1935                 return;
1936
1937         opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
1938         for (i = 0; i < opts->xopts_nr; i++) {
1939                 const char *arg = opts->xopts[i];
1940
1941                 skip_prefix(arg, "--", &arg);
1942                 opts->xopts[i] = xstrdup(arg);
1943         }
1944 }
1945
1946 static int read_populate_opts(struct replay_opts *opts)
1947 {
1948         if (is_rebase_i(opts)) {
1949                 struct strbuf buf = STRBUF_INIT;
1950
1951                 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1952                         if (!starts_with(buf.buf, "-S"))
1953                                 strbuf_reset(&buf);
1954                         else {
1955                                 free(opts->gpg_sign);
1956                                 opts->gpg_sign = xstrdup(buf.buf + 2);
1957                         }
1958                         strbuf_reset(&buf);
1959                 }
1960
1961                 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
1962                         if (!strcmp(buf.buf, "--rerere-autoupdate"))
1963                                 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
1964                         else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
1965                                 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
1966                         strbuf_reset(&buf);
1967                 }
1968
1969                 if (file_exists(rebase_path_verbose()))
1970                         opts->verbose = 1;
1971
1972                 read_strategy_opts(opts, &buf);
1973                 strbuf_release(&buf);
1974
1975                 return 0;
1976         }
1977
1978         if (!file_exists(git_path_opts_file()))
1979                 return 0;
1980         /*
1981          * The function git_parse_source(), called from git_config_from_file(),
1982          * may die() in case of a syntactically incorrect file. We do not care
1983          * about this case, though, because we wrote that file ourselves, so we
1984          * are pretty certain that it is syntactically correct.
1985          */
1986         if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1987                 return error(_("malformed options sheet: '%s'"),
1988                         git_path_opts_file());
1989         return 0;
1990 }
1991
1992 static int walk_revs_populate_todo(struct todo_list *todo_list,
1993                                 struct replay_opts *opts)
1994 {
1995         enum todo_command command = opts->action == REPLAY_PICK ?
1996                 TODO_PICK : TODO_REVERT;
1997         const char *command_string = todo_command_info[command].str;
1998         struct commit *commit;
1999
2000         if (prepare_revs(opts))
2001                 return -1;
2002
2003         while ((commit = get_revision(opts->revs))) {
2004                 struct todo_item *item = append_new_todo(todo_list);
2005                 const char *commit_buffer = get_commit_buffer(commit, NULL);
2006                 const char *subject;
2007                 int subject_len;
2008
2009                 item->command = command;
2010                 item->commit = commit;
2011                 item->arg = NULL;
2012                 item->arg_len = 0;
2013                 item->offset_in_buf = todo_list->buf.len;
2014                 subject_len = find_commit_subject(commit_buffer, &subject);
2015                 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2016                         short_commit_name(commit), subject_len, subject);
2017                 unuse_commit_buffer(commit, commit_buffer);
2018         }
2019         return 0;
2020 }
2021
2022 static int create_seq_dir(void)
2023 {
2024         if (file_exists(git_path_seq_dir())) {
2025                 error(_("a cherry-pick or revert is already in progress"));
2026                 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2027                 return -1;
2028         } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2029                 return error_errno(_("could not create sequencer directory '%s'"),
2030                                    git_path_seq_dir());
2031         return 0;
2032 }
2033
2034 static int save_head(const char *head)
2035 {
2036         static struct lock_file head_lock;
2037         struct strbuf buf = STRBUF_INIT;
2038         int fd;
2039         ssize_t written;
2040
2041         fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2042         if (fd < 0) {
2043                 rollback_lock_file(&head_lock);
2044                 return error_errno(_("could not lock HEAD"));
2045         }
2046         strbuf_addf(&buf, "%s\n", head);
2047         written = write_in_full(fd, buf.buf, buf.len);
2048         strbuf_release(&buf);
2049         if (written < 0) {
2050                 rollback_lock_file(&head_lock);
2051                 return error_errno(_("could not write to '%s'"),
2052                                    git_path_head_file());
2053         }
2054         if (commit_lock_file(&head_lock) < 0) {
2055                 rollback_lock_file(&head_lock);
2056                 return error(_("failed to finalize '%s'."), git_path_head_file());
2057         }
2058         return 0;
2059 }
2060
2061 static int rollback_is_safe(void)
2062 {
2063         struct strbuf sb = STRBUF_INIT;
2064         struct object_id expected_head, actual_head;
2065
2066         if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2067                 strbuf_trim(&sb);
2068                 if (get_oid_hex(sb.buf, &expected_head)) {
2069                         strbuf_release(&sb);
2070                         die(_("could not parse %s"), git_path_abort_safety_file());
2071                 }
2072                 strbuf_release(&sb);
2073         }
2074         else if (errno == ENOENT)
2075                 oidclr(&expected_head);
2076         else
2077                 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2078
2079         if (get_oid("HEAD", &actual_head))
2080                 oidclr(&actual_head);
2081
2082         return !oidcmp(&actual_head, &expected_head);
2083 }
2084
2085 static int reset_for_rollback(const struct object_id *oid)
2086 {
2087         const char *argv[4];    /* reset --merge <arg> + NULL */
2088
2089         argv[0] = "reset";
2090         argv[1] = "--merge";
2091         argv[2] = oid_to_hex(oid);
2092         argv[3] = NULL;
2093         return run_command_v_opt(argv, RUN_GIT_CMD);
2094 }
2095
2096 static int rollback_single_pick(void)
2097 {
2098         struct object_id head_oid;
2099
2100         if (!file_exists(git_path_cherry_pick_head()) &&
2101             !file_exists(git_path_revert_head()))
2102                 return error(_("no cherry-pick or revert in progress"));
2103         if (read_ref_full("HEAD", 0, &head_oid, NULL))
2104                 return error(_("cannot resolve HEAD"));
2105         if (is_null_oid(&head_oid))
2106                 return error(_("cannot abort from a branch yet to be born"));
2107         return reset_for_rollback(&head_oid);
2108 }
2109
2110 int sequencer_rollback(struct replay_opts *opts)
2111 {
2112         FILE *f;
2113         struct object_id oid;
2114         struct strbuf buf = STRBUF_INIT;
2115         const char *p;
2116
2117         f = fopen(git_path_head_file(), "r");
2118         if (!f && errno == ENOENT) {
2119                 /*
2120                  * There is no multiple-cherry-pick in progress.
2121                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2122                  * a single-cherry-pick in progress, abort that.
2123                  */
2124                 return rollback_single_pick();
2125         }
2126         if (!f)
2127                 return error_errno(_("cannot open '%s'"), git_path_head_file());
2128         if (strbuf_getline_lf(&buf, f)) {
2129                 error(_("cannot read '%s': %s"), git_path_head_file(),
2130                       ferror(f) ?  strerror(errno) : _("unexpected end of file"));
2131                 fclose(f);
2132                 goto fail;
2133         }
2134         fclose(f);
2135         if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2136                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2137                         git_path_head_file());
2138                 goto fail;
2139         }
2140         if (is_null_oid(&oid)) {
2141                 error(_("cannot abort from a branch yet to be born"));
2142                 goto fail;
2143         }
2144
2145         if (!rollback_is_safe()) {
2146                 /* Do not error, just do not rollback */
2147                 warning(_("You seem to have moved HEAD. "
2148                           "Not rewinding, check your HEAD!"));
2149         } else
2150         if (reset_for_rollback(&oid))
2151                 goto fail;
2152         strbuf_release(&buf);
2153         return sequencer_remove_state(opts);
2154 fail:
2155         strbuf_release(&buf);
2156         return -1;
2157 }
2158
2159 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2160 {
2161         static struct lock_file todo_lock;
2162         const char *todo_path = get_todo_path(opts);
2163         int next = todo_list->current, offset, fd;
2164
2165         /*
2166          * rebase -i writes "git-rebase-todo" without the currently executing
2167          * command, appending it to "done" instead.
2168          */
2169         if (is_rebase_i(opts))
2170                 next++;
2171
2172         fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2173         if (fd < 0)
2174                 return error_errno(_("could not lock '%s'"), todo_path);
2175         offset = next < todo_list->nr ?
2176                 todo_list->items[next].offset_in_buf : todo_list->buf.len;
2177         if (write_in_full(fd, todo_list->buf.buf + offset,
2178                         todo_list->buf.len - offset) < 0)
2179                 return error_errno(_("could not write to '%s'"), todo_path);
2180         if (commit_lock_file(&todo_lock) < 0)
2181                 return error(_("failed to finalize '%s'."), todo_path);
2182
2183         if (is_rebase_i(opts)) {
2184                 const char *done_path = rebase_path_done();
2185                 int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
2186                 int prev_offset = !next ? 0 :
2187                         todo_list->items[next - 1].offset_in_buf;
2188
2189                 if (fd >= 0 && offset > prev_offset &&
2190                     write_in_full(fd, todo_list->buf.buf + prev_offset,
2191                                   offset - prev_offset) < 0) {
2192                         close(fd);
2193                         return error_errno(_("could not write to '%s'"),
2194                                            done_path);
2195                 }
2196                 if (fd >= 0)
2197                         close(fd);
2198         }
2199         return 0;
2200 }
2201
2202 static int save_opts(struct replay_opts *opts)
2203 {
2204         const char *opts_file = git_path_opts_file();
2205         int res = 0;
2206
2207         if (opts->no_commit)
2208                 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2209         if (opts->edit)
2210                 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2211         if (opts->signoff)
2212                 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2213         if (opts->record_origin)
2214                 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2215         if (opts->allow_ff)
2216                 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2217         if (opts->mainline) {
2218                 struct strbuf buf = STRBUF_INIT;
2219                 strbuf_addf(&buf, "%d", opts->mainline);
2220                 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2221                 strbuf_release(&buf);
2222         }
2223         if (opts->strategy)
2224                 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2225         if (opts->gpg_sign)
2226                 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2227         if (opts->xopts) {
2228                 int i;
2229                 for (i = 0; i < opts->xopts_nr; i++)
2230                         res |= git_config_set_multivar_in_file_gently(opts_file,
2231                                                         "options.strategy-option",
2232                                                         opts->xopts[i], "^$", 0);
2233         }
2234         if (opts->allow_rerere_auto)
2235                 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2236                                                      opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2237                                                      "true" : "false");
2238         return res;
2239 }
2240
2241 static int make_patch(struct commit *commit, struct replay_opts *opts)
2242 {
2243         struct strbuf buf = STRBUF_INIT;
2244         struct rev_info log_tree_opt;
2245         const char *subject, *p;
2246         int res = 0;
2247
2248         p = short_commit_name(commit);
2249         if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2250                 return -1;
2251
2252         strbuf_addf(&buf, "%s/patch", get_dir(opts));
2253         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2254         init_revisions(&log_tree_opt, NULL);
2255         log_tree_opt.abbrev = 0;
2256         log_tree_opt.diff = 1;
2257         log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2258         log_tree_opt.disable_stdin = 1;
2259         log_tree_opt.no_commit_id = 1;
2260         log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2261         log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2262         if (!log_tree_opt.diffopt.file)
2263                 res |= error_errno(_("could not open '%s'"), buf.buf);
2264         else {
2265                 res |= log_tree_commit(&log_tree_opt, commit);
2266                 fclose(log_tree_opt.diffopt.file);
2267         }
2268         strbuf_reset(&buf);
2269
2270         strbuf_addf(&buf, "%s/message", get_dir(opts));
2271         if (!file_exists(buf.buf)) {
2272                 const char *commit_buffer = get_commit_buffer(commit, NULL);
2273                 find_commit_subject(commit_buffer, &subject);
2274                 res |= write_message(subject, strlen(subject), buf.buf, 1);
2275                 unuse_commit_buffer(commit, commit_buffer);
2276         }
2277         strbuf_release(&buf);
2278
2279         return res;
2280 }
2281
2282 static int intend_to_amend(void)
2283 {
2284         struct object_id head;
2285         char *p;
2286
2287         if (get_oid("HEAD", &head))
2288                 return error(_("cannot read HEAD"));
2289
2290         p = oid_to_hex(&head);
2291         return write_message(p, strlen(p), rebase_path_amend(), 1);
2292 }
2293
2294 static int error_with_patch(struct commit *commit,
2295         const char *subject, int subject_len,
2296         struct replay_opts *opts, int exit_code, int to_amend)
2297 {
2298         if (make_patch(commit, opts))
2299                 return -1;
2300
2301         if (to_amend) {
2302                 if (intend_to_amend())
2303                         return -1;
2304
2305                 fprintf(stderr, "You can amend the commit now, with\n"
2306                         "\n"
2307                         "  git commit --amend %s\n"
2308                         "\n"
2309                         "Once you are satisfied with your changes, run\n"
2310                         "\n"
2311                         "  git rebase --continue\n", gpg_sign_opt_quoted(opts));
2312         } else if (exit_code)
2313                 fprintf(stderr, "Could not apply %s... %.*s\n",
2314                         short_commit_name(commit), subject_len, subject);
2315
2316         return exit_code;
2317 }
2318
2319 static int error_failed_squash(struct commit *commit,
2320         struct replay_opts *opts, int subject_len, const char *subject)
2321 {
2322         if (rename(rebase_path_squash_msg(), rebase_path_message()))
2323                 return error(_("could not rename '%s' to '%s'"),
2324                         rebase_path_squash_msg(), rebase_path_message());
2325         unlink(rebase_path_fixup_msg());
2326         unlink(git_path_merge_msg());
2327         if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2328                 return error(_("could not copy '%s' to '%s'"),
2329                              rebase_path_message(), git_path_merge_msg());
2330         return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2331 }
2332
2333 static int do_exec(const char *command_line)
2334 {
2335         struct argv_array child_env = ARGV_ARRAY_INIT;
2336         const char *child_argv[] = { NULL, NULL };
2337         int dirty, status;
2338
2339         fprintf(stderr, "Executing: %s\n", command_line);
2340         child_argv[0] = command_line;
2341         argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2342         status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2343                                           child_env.argv);
2344
2345         /* force re-reading of the cache */
2346         if (discard_cache() < 0 || read_cache() < 0)
2347                 return error(_("could not read index"));
2348
2349         dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2350
2351         if (status) {
2352                 warning(_("execution failed: %s\n%s"
2353                           "You can fix the problem, and then run\n"
2354                           "\n"
2355                           "  git rebase --continue\n"
2356                           "\n"),
2357                         command_line,
2358                         dirty ? N_("and made changes to the index and/or the "
2359                                 "working tree\n") : "");
2360                 if (status == 127)
2361                         /* command not found */
2362                         status = 1;
2363         } else if (dirty) {
2364                 warning(_("execution succeeded: %s\nbut "
2365                           "left changes to the index and/or the working tree\n"
2366                           "Commit or stash your changes, and then run\n"
2367                           "\n"
2368                           "  git rebase --continue\n"
2369                           "\n"), command_line);
2370                 status = 1;
2371         }
2372
2373         argv_array_clear(&child_env);
2374
2375         return status;
2376 }
2377
2378 static int is_final_fixup(struct todo_list *todo_list)
2379 {
2380         int i = todo_list->current;
2381
2382         if (!is_fixup(todo_list->items[i].command))
2383                 return 0;
2384
2385         while (++i < todo_list->nr)
2386                 if (is_fixup(todo_list->items[i].command))
2387                         return 0;
2388                 else if (!is_noop(todo_list->items[i].command))
2389                         break;
2390         return 1;
2391 }
2392
2393 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2394 {
2395         int i;
2396
2397         for (i = todo_list->current + offset; i < todo_list->nr; i++)
2398                 if (!is_noop(todo_list->items[i].command))
2399                         return todo_list->items[i].command;
2400
2401         return -1;
2402 }
2403
2404 static int apply_autostash(struct replay_opts *opts)
2405 {
2406         struct strbuf stash_sha1 = STRBUF_INIT;
2407         struct child_process child = CHILD_PROCESS_INIT;
2408         int ret = 0;
2409
2410         if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2411                 strbuf_release(&stash_sha1);
2412                 return 0;
2413         }
2414         strbuf_trim(&stash_sha1);
2415
2416         child.git_cmd = 1;
2417         child.no_stdout = 1;
2418         child.no_stderr = 1;
2419         argv_array_push(&child.args, "stash");
2420         argv_array_push(&child.args, "apply");
2421         argv_array_push(&child.args, stash_sha1.buf);
2422         if (!run_command(&child))
2423                 fprintf(stderr, _("Applied autostash.\n"));
2424         else {
2425                 struct child_process store = CHILD_PROCESS_INIT;
2426
2427                 store.git_cmd = 1;
2428                 argv_array_push(&store.args, "stash");
2429                 argv_array_push(&store.args, "store");
2430                 argv_array_push(&store.args, "-m");
2431                 argv_array_push(&store.args, "autostash");
2432                 argv_array_push(&store.args, "-q");
2433                 argv_array_push(&store.args, stash_sha1.buf);
2434                 if (run_command(&store))
2435                         ret = error(_("cannot store %s"), stash_sha1.buf);
2436                 else
2437                         fprintf(stderr,
2438                                 _("Applying autostash resulted in conflicts.\n"
2439                                   "Your changes are safe in the stash.\n"
2440                                   "You can run \"git stash pop\" or"
2441                                   " \"git stash drop\" at any time.\n"));
2442         }
2443
2444         strbuf_release(&stash_sha1);
2445         return ret;
2446 }
2447
2448 static const char *reflog_message(struct replay_opts *opts,
2449         const char *sub_action, const char *fmt, ...)
2450 {
2451         va_list ap;
2452         static struct strbuf buf = STRBUF_INIT;
2453
2454         va_start(ap, fmt);
2455         strbuf_reset(&buf);
2456         strbuf_addstr(&buf, action_name(opts));
2457         if (sub_action)
2458                 strbuf_addf(&buf, " (%s)", sub_action);
2459         if (fmt) {
2460                 strbuf_addstr(&buf, ": ");
2461                 strbuf_vaddf(&buf, fmt, ap);
2462         }
2463         va_end(ap);
2464
2465         return buf.buf;
2466 }
2467
2468 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2469 {
2470         int res = 0;
2471
2472         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2473         if (opts->allow_ff)
2474                 assert(!(opts->signoff || opts->no_commit ||
2475                                 opts->record_origin || opts->edit));
2476         if (read_and_refresh_cache(opts))
2477                 return -1;
2478
2479         while (todo_list->current < todo_list->nr) {
2480                 struct todo_item *item = todo_list->items + todo_list->current;
2481                 if (save_todo(todo_list, opts))
2482                         return -1;
2483                 if (is_rebase_i(opts)) {
2484                         if (item->command != TODO_COMMENT) {
2485                                 FILE *f = fopen(rebase_path_msgnum(), "w");
2486
2487                                 todo_list->done_nr++;
2488
2489                                 if (f) {
2490                                         fprintf(f, "%d\n", todo_list->done_nr);
2491                                         fclose(f);
2492                                 }
2493                                 fprintf(stderr, "Rebasing (%d/%d)%s",
2494                                         todo_list->done_nr,
2495                                         todo_list->total_nr,
2496                                         opts->verbose ? "\n" : "\r");
2497                         }
2498                         unlink(rebase_path_message());
2499                         unlink(rebase_path_author_script());
2500                         unlink(rebase_path_stopped_sha());
2501                         unlink(rebase_path_amend());
2502                 }
2503                 if (item->command <= TODO_SQUASH) {
2504                         if (is_rebase_i(opts))
2505                                 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
2506                                         command_to_string(item->command), NULL),
2507                                         1);
2508                         res = do_pick_commit(item->command, item->commit,
2509                                         opts, is_final_fixup(todo_list));
2510                         if (is_rebase_i(opts) && res < 0) {
2511                                 /* Reschedule */
2512                                 todo_list->current--;
2513                                 if (save_todo(todo_list, opts))
2514                                         return -1;
2515                         }
2516                         if (item->command == TODO_EDIT) {
2517                                 struct commit *commit = item->commit;
2518                                 if (!res)
2519                                         fprintf(stderr,
2520                                                 _("Stopped at %s...  %.*s\n"),
2521                                                 short_commit_name(commit),
2522                                                 item->arg_len, item->arg);
2523                                 return error_with_patch(commit,
2524                                         item->arg, item->arg_len, opts, res,
2525                                         !res);
2526                         }
2527                         if (is_rebase_i(opts) && !res)
2528                                 record_in_rewritten(&item->commit->object.oid,
2529                                         peek_command(todo_list, 1));
2530                         if (res && is_fixup(item->command)) {
2531                                 if (res == 1)
2532                                         intend_to_amend();
2533                                 return error_failed_squash(item->commit, opts,
2534                                         item->arg_len, item->arg);
2535                         } else if (res && is_rebase_i(opts))
2536                                 return res | error_with_patch(item->commit,
2537                                         item->arg, item->arg_len, opts, res,
2538                                         item->command == TODO_REWORD);
2539                 } else if (item->command == TODO_EXEC) {
2540                         char *end_of_arg = (char *)(item->arg + item->arg_len);
2541                         int saved = *end_of_arg;
2542                         struct stat st;
2543
2544                         *end_of_arg = '\0';
2545                         res = do_exec(item->arg);
2546                         *end_of_arg = saved;
2547
2548                         /* Reread the todo file if it has changed. */
2549                         if (res)
2550                                 ; /* fall through */
2551                         else if (stat(get_todo_path(opts), &st))
2552                                 res = error_errno(_("could not stat '%s'"),
2553                                                   get_todo_path(opts));
2554                         else if (match_stat_data(&todo_list->stat, &st)) {
2555                                 todo_list_release(todo_list);
2556                                 if (read_populate_todo(todo_list, opts))
2557                                         res = -1; /* message was printed */
2558                                 /* `current` will be incremented below */
2559                                 todo_list->current = -1;
2560                         }
2561                 } else if (!is_noop(item->command))
2562                         return error(_("unknown command %d"), item->command);
2563
2564                 todo_list->current++;
2565                 if (res)
2566                         return res;
2567         }
2568
2569         if (is_rebase_i(opts)) {
2570                 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2571                 struct stat st;
2572
2573                 /* Stopped in the middle, as planned? */
2574                 if (todo_list->current < todo_list->nr)
2575                         return 0;
2576
2577                 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2578                                 starts_with(head_ref.buf, "refs/")) {
2579                         const char *msg;
2580                         struct object_id head, orig;
2581                         int res;
2582
2583                         if (get_oid("HEAD", &head)) {
2584                                 res = error(_("cannot read HEAD"));
2585 cleanup_head_ref:
2586                                 strbuf_release(&head_ref);
2587                                 strbuf_release(&buf);
2588                                 return res;
2589                         }
2590                         if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2591                                         get_oid_hex(buf.buf, &orig)) {
2592                                 res = error(_("could not read orig-head"));
2593                                 goto cleanup_head_ref;
2594                         }
2595                         strbuf_reset(&buf);
2596                         if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2597                                 res = error(_("could not read 'onto'"));
2598                                 goto cleanup_head_ref;
2599                         }
2600                         msg = reflog_message(opts, "finish", "%s onto %s",
2601                                 head_ref.buf, buf.buf);
2602                         if (update_ref(msg, head_ref.buf, &head, &orig,
2603                                        REF_NODEREF, UPDATE_REFS_MSG_ON_ERR)) {
2604                                 res = error(_("could not update %s"),
2605                                         head_ref.buf);
2606                                 goto cleanup_head_ref;
2607                         }
2608                         msg = reflog_message(opts, "finish", "returning to %s",
2609                                 head_ref.buf);
2610                         if (create_symref("HEAD", head_ref.buf, msg)) {
2611                                 res = error(_("could not update HEAD to %s"),
2612                                         head_ref.buf);
2613                                 goto cleanup_head_ref;
2614                         }
2615                         strbuf_reset(&buf);
2616                 }
2617
2618                 if (opts->verbose) {
2619                         struct rev_info log_tree_opt;
2620                         struct object_id orig, head;
2621
2622                         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2623                         init_revisions(&log_tree_opt, NULL);
2624                         log_tree_opt.diff = 1;
2625                         log_tree_opt.diffopt.output_format =
2626                                 DIFF_FORMAT_DIFFSTAT;
2627                         log_tree_opt.disable_stdin = 1;
2628
2629                         if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2630                             !get_oid(buf.buf, &orig) &&
2631                             !get_oid("HEAD", &head)) {
2632                                 diff_tree_oid(&orig, &head, "",
2633                                               &log_tree_opt.diffopt);
2634                                 log_tree_diff_flush(&log_tree_opt);
2635                         }
2636                 }
2637                 flush_rewritten_pending();
2638                 if (!stat(rebase_path_rewritten_list(), &st) &&
2639                                 st.st_size > 0) {
2640                         struct child_process child = CHILD_PROCESS_INIT;
2641                         const char *post_rewrite_hook =
2642                                 find_hook("post-rewrite");
2643
2644                         child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2645                         child.git_cmd = 1;
2646                         argv_array_push(&child.args, "notes");
2647                         argv_array_push(&child.args, "copy");
2648                         argv_array_push(&child.args, "--for-rewrite=rebase");
2649                         /* we don't care if this copying failed */
2650                         run_command(&child);
2651
2652                         if (post_rewrite_hook) {
2653                                 struct child_process hook = CHILD_PROCESS_INIT;
2654
2655                                 hook.in = open(rebase_path_rewritten_list(),
2656                                         O_RDONLY);
2657                                 hook.stdout_to_stderr = 1;
2658                                 argv_array_push(&hook.args, post_rewrite_hook);
2659                                 argv_array_push(&hook.args, "rebase");
2660                                 /* we don't care if this hook failed */
2661                                 run_command(&hook);
2662                         }
2663                 }
2664                 apply_autostash(opts);
2665
2666                 fprintf(stderr, "Successfully rebased and updated %s.\n",
2667                         head_ref.buf);
2668
2669                 strbuf_release(&buf);
2670                 strbuf_release(&head_ref);
2671         }
2672
2673         /*
2674          * Sequence of picks finished successfully; cleanup by
2675          * removing the .git/sequencer directory
2676          */
2677         return sequencer_remove_state(opts);
2678 }
2679
2680 static int continue_single_pick(void)
2681 {
2682         const char *argv[] = { "commit", NULL };
2683
2684         if (!file_exists(git_path_cherry_pick_head()) &&
2685             !file_exists(git_path_revert_head()))
2686                 return error(_("no cherry-pick or revert in progress"));
2687         return run_command_v_opt(argv, RUN_GIT_CMD);
2688 }
2689
2690 static int commit_staged_changes(struct replay_opts *opts)
2691 {
2692         unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
2693
2694         if (has_unstaged_changes(1))
2695                 return error(_("cannot rebase: You have unstaged changes."));
2696         if (!has_uncommitted_changes(0)) {
2697                 const char *cherry_pick_head = git_path_cherry_pick_head();
2698
2699                 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2700                         return error(_("could not remove CHERRY_PICK_HEAD"));
2701                 return 0;
2702         }
2703
2704         if (file_exists(rebase_path_amend())) {
2705                 struct strbuf rev = STRBUF_INIT;
2706                 struct object_id head, to_amend;
2707
2708                 if (get_oid("HEAD", &head))
2709                         return error(_("cannot amend non-existing commit"));
2710                 if (!read_oneliner(&rev, rebase_path_amend(), 0))
2711                         return error(_("invalid file: '%s'"), rebase_path_amend());
2712                 if (get_oid_hex(rev.buf, &to_amend))
2713                         return error(_("invalid contents: '%s'"),
2714                                 rebase_path_amend());
2715                 if (oidcmp(&head, &to_amend))
2716                         return error(_("\nYou have uncommitted changes in your "
2717                                        "working tree. Please, commit them\n"
2718                                        "first and then run 'git rebase "
2719                                        "--continue' again."));
2720
2721                 strbuf_release(&rev);
2722                 flags |= AMEND_MSG;
2723         }
2724
2725         if (run_git_commit(rebase_path_message(), opts, flags))
2726                 return error(_("could not commit staged changes."));
2727         unlink(rebase_path_amend());
2728         return 0;
2729 }
2730
2731 int sequencer_continue(struct replay_opts *opts)
2732 {
2733         struct todo_list todo_list = TODO_LIST_INIT;
2734         int res;
2735
2736         if (read_and_refresh_cache(opts))
2737                 return -1;
2738
2739         if (is_rebase_i(opts)) {
2740                 if (commit_staged_changes(opts))
2741                         return -1;
2742         } else if (!file_exists(get_todo_path(opts)))
2743                 return continue_single_pick();
2744         if (read_populate_opts(opts))
2745                 return -1;
2746         if ((res = read_populate_todo(&todo_list, opts)))
2747                 goto release_todo_list;
2748
2749         if (!is_rebase_i(opts)) {
2750                 /* Verify that the conflict has been resolved */
2751                 if (file_exists(git_path_cherry_pick_head()) ||
2752                     file_exists(git_path_revert_head())) {
2753                         res = continue_single_pick();
2754                         if (res)
2755                                 goto release_todo_list;
2756                 }
2757                 if (index_differs_from("HEAD", NULL, 0)) {
2758                         res = error_dirty_index(opts);
2759                         goto release_todo_list;
2760                 }
2761                 todo_list.current++;
2762         } else if (file_exists(rebase_path_stopped_sha())) {
2763                 struct strbuf buf = STRBUF_INIT;
2764                 struct object_id oid;
2765
2766                 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2767                     !get_oid_committish(buf.buf, &oid))
2768                         record_in_rewritten(&oid, peek_command(&todo_list, 0));
2769                 strbuf_release(&buf);
2770         }
2771
2772         res = pick_commits(&todo_list, opts);
2773 release_todo_list:
2774         todo_list_release(&todo_list);
2775         return res;
2776 }
2777
2778 static int single_pick(struct commit *cmit, struct replay_opts *opts)
2779 {
2780         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2781         return do_pick_commit(opts->action == REPLAY_PICK ?
2782                 TODO_PICK : TODO_REVERT, cmit, opts, 0);
2783 }
2784
2785 int sequencer_pick_revisions(struct replay_opts *opts)
2786 {
2787         struct todo_list todo_list = TODO_LIST_INIT;
2788         struct object_id oid;
2789         int i, res;
2790
2791         assert(opts->revs);
2792         if (read_and_refresh_cache(opts))
2793                 return -1;
2794
2795         for (i = 0; i < opts->revs->pending.nr; i++) {
2796                 struct object_id oid;
2797                 const char *name = opts->revs->pending.objects[i].name;
2798
2799                 /* This happens when using --stdin. */
2800                 if (!strlen(name))
2801                         continue;
2802
2803                 if (!get_oid(name, &oid)) {
2804                         if (!lookup_commit_reference_gently(&oid, 1)) {
2805                                 enum object_type type = sha1_object_info(oid.hash, NULL);
2806                                 return error(_("%s: can't cherry-pick a %s"),
2807                                         name, typename(type));
2808                         }
2809                 } else
2810                         return error(_("%s: bad revision"), name);
2811         }
2812
2813         /*
2814          * If we were called as "git cherry-pick <commit>", just
2815          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2816          * REVERT_HEAD, and don't touch the sequencer state.
2817          * This means it is possible to cherry-pick in the middle
2818          * of a cherry-pick sequence.
2819          */
2820         if (opts->revs->cmdline.nr == 1 &&
2821             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2822             opts->revs->no_walk &&
2823             !opts->revs->cmdline.rev->flags) {
2824                 struct commit *cmit;
2825                 if (prepare_revision_walk(opts->revs))
2826                         return error(_("revision walk setup failed"));
2827                 cmit = get_revision(opts->revs);
2828                 if (!cmit || get_revision(opts->revs))
2829                         return error("BUG: expected exactly one commit from walk");
2830                 return single_pick(cmit, opts);
2831         }
2832
2833         /*
2834          * Start a new cherry-pick/ revert sequence; but
2835          * first, make sure that an existing one isn't in
2836          * progress
2837          */
2838
2839         if (walk_revs_populate_todo(&todo_list, opts) ||
2840                         create_seq_dir() < 0)
2841                 return -1;
2842         if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
2843                 return error(_("can't revert as initial commit"));
2844         if (save_head(oid_to_hex(&oid)))
2845                 return -1;
2846         if (save_opts(opts))
2847                 return -1;
2848         update_abort_safety_file();
2849         res = pick_commits(&todo_list, opts);
2850         todo_list_release(&todo_list);
2851         return res;
2852 }
2853
2854 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2855 {
2856         unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2857         struct strbuf sob = STRBUF_INIT;
2858         int has_footer;
2859
2860         strbuf_addstr(&sob, sign_off_header);
2861         strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2862                                 getenv("GIT_COMMITTER_EMAIL")));
2863         strbuf_addch(&sob, '\n');
2864
2865         if (!ignore_footer)
2866                 strbuf_complete_line(msgbuf);
2867
2868         /*
2869          * If the whole message buffer is equal to the sob, pretend that we
2870          * found a conforming footer with a matching sob
2871          */
2872         if (msgbuf->len - ignore_footer == sob.len &&
2873             !strncmp(msgbuf->buf, sob.buf, sob.len))
2874                 has_footer = 3;
2875         else
2876                 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2877
2878         if (!has_footer) {
2879                 const char *append_newlines = NULL;
2880                 size_t len = msgbuf->len - ignore_footer;
2881
2882                 if (!len) {
2883                         /*
2884                          * The buffer is completely empty.  Leave foom for
2885                          * the title and body to be filled in by the user.
2886                          */
2887                         append_newlines = "\n\n";
2888                 } else if (len == 1) {
2889                         /*
2890                          * Buffer contains a single newline.  Add another
2891                          * so that we leave room for the title and body.
2892                          */
2893                         append_newlines = "\n";
2894                 } else if (msgbuf->buf[len - 2] != '\n') {
2895                         /*
2896                          * Buffer ends with a single newline.  Add another
2897                          * so that there is an empty line between the message
2898                          * body and the sob.
2899                          */
2900                         append_newlines = "\n";
2901                 } /* else, the buffer already ends with two newlines. */
2902
2903                 if (append_newlines)
2904                         strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2905                                 append_newlines, strlen(append_newlines));
2906         }
2907
2908         if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2909                 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2910                                 sob.buf, sob.len);
2911
2912         strbuf_release(&sob);
2913 }
2914
2915 int sequencer_make_script(int keep_empty, FILE *out,
2916                 int argc, const char **argv)
2917 {
2918         char *format = NULL;
2919         struct pretty_print_context pp = {0};
2920         struct strbuf buf = STRBUF_INIT;
2921         struct rev_info revs;
2922         struct commit *commit;
2923
2924         init_revisions(&revs, NULL);
2925         revs.verbose_header = 1;
2926         revs.max_parents = 1;
2927         revs.cherry_pick = 1;
2928         revs.limited = 1;
2929         revs.reverse = 1;
2930         revs.right_only = 1;
2931         revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
2932         revs.topo_order = 1;
2933
2934         revs.pretty_given = 1;
2935         git_config_get_string("rebase.instructionFormat", &format);
2936         if (!format || !*format) {
2937                 free(format);
2938                 format = xstrdup("%s");
2939         }
2940         get_commit_format(format, &revs);
2941         free(format);
2942         pp.fmt = revs.commit_format;
2943         pp.output_encoding = get_log_output_encoding();
2944
2945         if (setup_revisions(argc, argv, &revs, NULL) > 1)
2946                 return error(_("make_script: unhandled options"));
2947
2948         if (prepare_revision_walk(&revs) < 0)
2949                 return error(_("make_script: error preparing revisions"));
2950
2951         while ((commit = get_revision(&revs))) {
2952                 strbuf_reset(&buf);
2953                 if (!keep_empty && is_original_commit_empty(commit))
2954                         strbuf_addf(&buf, "%c ", comment_line_char);
2955                 strbuf_addf(&buf, "pick %s ", oid_to_hex(&commit->object.oid));
2956                 pretty_print_commit(&pp, commit, &buf);
2957                 strbuf_addch(&buf, '\n');
2958                 fputs(buf.buf, out);
2959         }
2960         strbuf_release(&buf);
2961         return 0;
2962 }
2963
2964
2965 int transform_todo_ids(int shorten_ids)
2966 {
2967         const char *todo_file = rebase_path_todo();
2968         struct todo_list todo_list = TODO_LIST_INIT;
2969         int fd, res, i;
2970         FILE *out;
2971
2972         strbuf_reset(&todo_list.buf);
2973         fd = open(todo_file, O_RDONLY);
2974         if (fd < 0)
2975                 return error_errno(_("could not open '%s'"), todo_file);
2976         if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2977                 close(fd);
2978                 return error(_("could not read '%s'."), todo_file);
2979         }
2980         close(fd);
2981
2982         res = parse_insn_buffer(todo_list.buf.buf, &todo_list);
2983         if (res) {
2984                 todo_list_release(&todo_list);
2985                 return error(_("unusable todo list: '%s'"), todo_file);
2986         }
2987
2988         out = fopen(todo_file, "w");
2989         if (!out) {
2990                 todo_list_release(&todo_list);
2991                 return error(_("unable to open '%s' for writing"), todo_file);
2992         }
2993         for (i = 0; i < todo_list.nr; i++) {
2994                 struct todo_item *item = todo_list.items + i;
2995                 int bol = item->offset_in_buf;
2996                 const char *p = todo_list.buf.buf + bol;
2997                 int eol = i + 1 < todo_list.nr ?
2998                         todo_list.items[i + 1].offset_in_buf :
2999                         todo_list.buf.len;
3000
3001                 if (item->command >= TODO_EXEC && item->command != TODO_DROP)
3002                         fwrite(p, eol - bol, 1, out);
3003                 else {
3004                         const char *id = shorten_ids ?
3005                                 short_commit_name(item->commit) :
3006                                 oid_to_hex(&item->commit->object.oid);
3007                         int len;
3008
3009                         p += strspn(p, " \t"); /* left-trim command */
3010                         len = strcspn(p, " \t"); /* length of command */
3011
3012                         fprintf(out, "%.*s %s %.*s\n",
3013                                 len, p, id, item->arg_len, item->arg);
3014                 }
3015         }
3016         fclose(out);
3017         todo_list_release(&todo_list);
3018         return 0;
3019 }
3020
3021 enum check_level {
3022         CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
3023 };
3024
3025 static enum check_level get_missing_commit_check_level(void)
3026 {
3027         const char *value;
3028
3029         if (git_config_get_value("rebase.missingcommitscheck", &value) ||
3030                         !strcasecmp("ignore", value))
3031                 return CHECK_IGNORE;
3032         if (!strcasecmp("warn", value))
3033                 return CHECK_WARN;
3034         if (!strcasecmp("error", value))
3035                 return CHECK_ERROR;
3036         warning(_("unrecognized setting %s for option "
3037                   "rebase.missingCommitsCheck. Ignoring."), value);
3038         return CHECK_IGNORE;
3039 }
3040
3041 /*
3042  * Check if the user dropped some commits by mistake
3043  * Behaviour determined by rebase.missingCommitsCheck.
3044  * Check if there is an unrecognized command or a
3045  * bad SHA-1 in a command.
3046  */
3047 int check_todo_list(void)
3048 {
3049         enum check_level check_level = get_missing_commit_check_level();
3050         struct strbuf todo_file = STRBUF_INIT;
3051         struct todo_list todo_list = TODO_LIST_INIT;
3052         struct strbuf missing = STRBUF_INIT;
3053         int advise_to_edit_todo = 0, res = 0, fd, i;
3054
3055         strbuf_addstr(&todo_file, rebase_path_todo());
3056         fd = open(todo_file.buf, O_RDONLY);
3057         if (fd < 0) {
3058                 res = error_errno(_("could not open '%s'"), todo_file.buf);
3059                 goto leave_check;
3060         }
3061         if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3062                 close(fd);
3063                 res = error(_("could not read '%s'."), todo_file.buf);
3064                 goto leave_check;
3065         }
3066         close(fd);
3067         advise_to_edit_todo = res =
3068                 parse_insn_buffer(todo_list.buf.buf, &todo_list);
3069
3070         if (res || check_level == CHECK_IGNORE)
3071                 goto leave_check;
3072
3073         /* Mark the commits in git-rebase-todo as seen */
3074         for (i = 0; i < todo_list.nr; i++) {
3075                 struct commit *commit = todo_list.items[i].commit;
3076                 if (commit)
3077                         commit->util = (void *)1;
3078         }
3079
3080         todo_list_release(&todo_list);
3081         strbuf_addstr(&todo_file, ".backup");
3082         fd = open(todo_file.buf, O_RDONLY);
3083         if (fd < 0) {
3084                 res = error_errno(_("could not open '%s'"), todo_file.buf);
3085                 goto leave_check;
3086         }
3087         if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3088                 close(fd);
3089                 res = error(_("could not read '%s'."), todo_file.buf);
3090                 goto leave_check;
3091         }
3092         close(fd);
3093         strbuf_release(&todo_file);
3094         res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
3095
3096         /* Find commits in git-rebase-todo.backup yet unseen */
3097         for (i = todo_list.nr - 1; i >= 0; i--) {
3098                 struct todo_item *item = todo_list.items + i;
3099                 struct commit *commit = item->commit;
3100                 if (commit && !commit->util) {
3101                         strbuf_addf(&missing, " - %s %.*s\n",
3102                                     short_commit_name(commit),
3103                                     item->arg_len, item->arg);
3104                         commit->util = (void *)1;
3105                 }
3106         }
3107
3108         /* Warn about missing commits */
3109         if (!missing.len)
3110                 goto leave_check;
3111
3112         if (check_level == CHECK_ERROR)
3113                 advise_to_edit_todo = res = 1;
3114
3115         fprintf(stderr,
3116                 _("Warning: some commits may have been dropped accidentally.\n"
3117                 "Dropped commits (newer to older):\n"));
3118
3119         /* Make the list user-friendly and display */
3120         fputs(missing.buf, stderr);
3121         strbuf_release(&missing);
3122
3123         fprintf(stderr, _("To avoid this message, use \"drop\" to "
3124                 "explicitly remove a commit.\n\n"
3125                 "Use 'git config rebase.missingCommitsCheck' to change "
3126                 "the level of warnings.\n"
3127                 "The possible behaviours are: ignore, warn, error.\n\n"));
3128
3129 leave_check:
3130         strbuf_release(&todo_file);
3131         todo_list_release(&todo_list);
3132
3133         if (advise_to_edit_todo)
3134                 fprintf(stderr,
3135                         _("You can fix this with 'git rebase --edit-todo' "
3136                           "and then run 'git rebase --continue'.\n"
3137                           "Or you can abort the rebase with 'git rebase"
3138                           " --abort'.\n"));
3139
3140         return res;
3141 }
3142
3143 /* skip picking commits whose parents are unchanged */
3144 int skip_unnecessary_picks(void)
3145 {
3146         const char *todo_file = rebase_path_todo();
3147         struct strbuf buf = STRBUF_INIT;
3148         struct todo_list todo_list = TODO_LIST_INIT;
3149         struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
3150         int fd, i;
3151
3152         if (!read_oneliner(&buf, rebase_path_onto(), 0))
3153                 return error(_("could not read 'onto'"));
3154         if (get_oid(buf.buf, &onto_oid)) {
3155                 strbuf_release(&buf);
3156                 return error(_("need a HEAD to fixup"));
3157         }
3158         strbuf_release(&buf);
3159
3160         fd = open(todo_file, O_RDONLY);
3161         if (fd < 0) {
3162                 return error_errno(_("could not open '%s'"), todo_file);
3163         }
3164         if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3165                 close(fd);
3166                 return error(_("could not read '%s'."), todo_file);
3167         }
3168         close(fd);
3169         if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3170                 todo_list_release(&todo_list);
3171                 return -1;
3172         }
3173
3174         for (i = 0; i < todo_list.nr; i++) {
3175                 struct todo_item *item = todo_list.items + i;
3176
3177                 if (item->command >= TODO_NOOP)
3178                         continue;
3179                 if (item->command != TODO_PICK)
3180                         break;
3181                 if (parse_commit(item->commit)) {
3182                         todo_list_release(&todo_list);
3183                         return error(_("could not parse commit '%s'"),
3184                                 oid_to_hex(&item->commit->object.oid));
3185                 }
3186                 if (!item->commit->parents)
3187                         break; /* root commit */
3188                 if (item->commit->parents->next)
3189                         break; /* merge commit */
3190                 parent_oid = &item->commit->parents->item->object.oid;
3191                 if (hashcmp(parent_oid->hash, oid->hash))
3192                         break;
3193                 oid = &item->commit->object.oid;
3194         }
3195         if (i > 0) {
3196                 int offset = i < todo_list.nr ?
3197                         todo_list.items[i].offset_in_buf : todo_list.buf.len;
3198                 const char *done_path = rebase_path_done();
3199
3200                 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
3201                 if (fd < 0) {
3202                         error_errno(_("could not open '%s' for writing"),
3203                                     done_path);
3204                         todo_list_release(&todo_list);
3205                         return -1;
3206                 }
3207                 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
3208                         error_errno(_("could not write to '%s'"), done_path);
3209                         todo_list_release(&todo_list);
3210                         close(fd);
3211                         return -1;
3212                 }
3213                 close(fd);
3214
3215                 fd = open(rebase_path_todo(), O_WRONLY, 0666);
3216                 if (fd < 0) {
3217                         error_errno(_("could not open '%s' for writing"),
3218                                     rebase_path_todo());
3219                         todo_list_release(&todo_list);
3220                         return -1;
3221                 }
3222                 if (write_in_full(fd, todo_list.buf.buf + offset,
3223                                 todo_list.buf.len - offset) < 0) {
3224                         error_errno(_("could not write to '%s'"),
3225                                     rebase_path_todo());
3226                         close(fd);
3227                         todo_list_release(&todo_list);
3228                         return -1;
3229                 }
3230                 if (ftruncate(fd, todo_list.buf.len - offset) < 0) {
3231                         error_errno(_("could not truncate '%s'"),
3232                                     rebase_path_todo());
3233                         todo_list_release(&todo_list);
3234                         close(fd);
3235                         return -1;
3236                 }
3237                 close(fd);
3238
3239                 todo_list.current = i;
3240                 if (is_fixup(peek_command(&todo_list, 0)))
3241                         record_in_rewritten(oid, peek_command(&todo_list, 0));
3242         }
3243
3244         todo_list_release(&todo_list);
3245         printf("%s\n", oid_to_hex(oid));
3246
3247         return 0;
3248 }
3249
3250 struct subject2item_entry {
3251         struct hashmap_entry entry;
3252         int i;
3253         char subject[FLEX_ARRAY];
3254 };
3255
3256 static int subject2item_cmp(const void *fndata,
3257                             const struct subject2item_entry *a,
3258                             const struct subject2item_entry *b, const void *key)
3259 {
3260         return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
3261 }
3262
3263 /*
3264  * Rearrange the todo list that has both "pick commit-id msg" and "pick
3265  * commit-id fixup!/squash! msg" in it so that the latter is put immediately
3266  * after the former, and change "pick" to "fixup"/"squash".
3267  *
3268  * Note that if the config has specified a custom instruction format, each log
3269  * message will have to be retrieved from the commit (as the oneline in the
3270  * script cannot be trusted) in order to normalize the autosquash arrangement.
3271  */
3272 int rearrange_squash(void)
3273 {
3274         const char *todo_file = rebase_path_todo();
3275         struct todo_list todo_list = TODO_LIST_INIT;
3276         struct hashmap subject2item;
3277         int res = 0, rearranged = 0, *next, *tail, fd, i;
3278         char **subjects;
3279
3280         fd = open(todo_file, O_RDONLY);
3281         if (fd < 0)
3282                 return error_errno(_("could not open '%s'"), todo_file);
3283         if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3284                 close(fd);
3285                 return error(_("could not read '%s'."), todo_file);
3286         }
3287         close(fd);
3288         if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3289                 todo_list_release(&todo_list);
3290                 return -1;
3291         }
3292
3293         /*
3294          * The hashmap maps onelines to the respective todo list index.
3295          *
3296          * If any items need to be rearranged, the next[i] value will indicate
3297          * which item was moved directly after the i'th.
3298          *
3299          * In that case, last[i] will indicate the index of the latest item to
3300          * be moved to appear after the i'th.
3301          */
3302         hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
3303                      NULL, todo_list.nr);
3304         ALLOC_ARRAY(next, todo_list.nr);
3305         ALLOC_ARRAY(tail, todo_list.nr);
3306         ALLOC_ARRAY(subjects, todo_list.nr);
3307         for (i = 0; i < todo_list.nr; i++) {
3308                 struct strbuf buf = STRBUF_INIT;
3309                 struct todo_item *item = todo_list.items + i;
3310                 const char *commit_buffer, *subject, *p;
3311                 size_t subject_len;
3312                 int i2 = -1;
3313                 struct subject2item_entry *entry;
3314
3315                 next[i] = tail[i] = -1;
3316                 if (item->command >= TODO_EXEC) {
3317                         subjects[i] = NULL;
3318                         continue;
3319                 }
3320
3321                 if (is_fixup(item->command)) {
3322                         todo_list_release(&todo_list);
3323                         return error(_("the script was already rearranged."));
3324                 }
3325
3326                 item->commit->util = item;
3327
3328                 parse_commit(item->commit);
3329                 commit_buffer = get_commit_buffer(item->commit, NULL);
3330                 find_commit_subject(commit_buffer, &subject);
3331                 format_subject(&buf, subject, " ");
3332                 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
3333                 unuse_commit_buffer(item->commit, commit_buffer);
3334                 if ((skip_prefix(subject, "fixup! ", &p) ||
3335                      skip_prefix(subject, "squash! ", &p))) {
3336                         struct commit *commit2;
3337
3338                         for (;;) {
3339                                 while (isspace(*p))
3340                                         p++;
3341                                 if (!skip_prefix(p, "fixup! ", &p) &&
3342                                     !skip_prefix(p, "squash! ", &p))
3343                                         break;
3344                         }
3345
3346                         if ((entry = hashmap_get_from_hash(&subject2item,
3347                                                            strhash(p), p)))
3348                                 /* found by title */
3349                                 i2 = entry->i;
3350                         else if (!strchr(p, ' ') &&
3351                                  (commit2 =
3352                                   lookup_commit_reference_by_name(p)) &&
3353                                  commit2->util)
3354                                 /* found by commit name */
3355                                 i2 = (struct todo_item *)commit2->util
3356                                         - todo_list.items;
3357                         else {
3358                                 /* copy can be a prefix of the commit subject */
3359                                 for (i2 = 0; i2 < i; i2++)
3360                                         if (subjects[i2] &&
3361                                             starts_with(subjects[i2], p))
3362                                                 break;
3363                                 if (i2 == i)
3364                                         i2 = -1;
3365                         }
3366                 }
3367                 if (i2 >= 0) {
3368                         rearranged = 1;
3369                         todo_list.items[i].command =
3370                                 starts_with(subject, "fixup!") ?
3371                                 TODO_FIXUP : TODO_SQUASH;
3372                         if (next[i2] < 0)
3373                                 next[i2] = i;
3374                         else
3375                                 next[tail[i2]] = i;
3376                         tail[i2] = i;
3377                 } else if (!hashmap_get_from_hash(&subject2item,
3378                                                 strhash(subject), subject)) {
3379                         FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
3380                         entry->i = i;
3381                         hashmap_entry_init(entry, strhash(entry->subject));
3382                         hashmap_put(&subject2item, entry);
3383                 }
3384         }
3385
3386         if (rearranged) {
3387                 struct strbuf buf = STRBUF_INIT;
3388
3389                 for (i = 0; i < todo_list.nr; i++) {
3390                         enum todo_command command = todo_list.items[i].command;
3391                         int cur = i;
3392
3393                         /*
3394                          * Initially, all commands are 'pick's. If it is a
3395                          * fixup or a squash now, we have rearranged it.
3396                          */
3397                         if (is_fixup(command))
3398                                 continue;
3399
3400                         while (cur >= 0) {
3401                                 int offset = todo_list.items[cur].offset_in_buf;
3402                                 int end_offset = cur + 1 < todo_list.nr ?
3403                                         todo_list.items[cur + 1].offset_in_buf :
3404                                         todo_list.buf.len;
3405                                 char *bol = todo_list.buf.buf + offset;
3406                                 char *eol = todo_list.buf.buf + end_offset;
3407
3408                                 /* replace 'pick', by 'fixup' or 'squash' */
3409                                 command = todo_list.items[cur].command;
3410                                 if (is_fixup(command)) {
3411                                         strbuf_addstr(&buf,
3412                                                 todo_command_info[command].str);
3413                                         bol += strcspn(bol, " \t");
3414                                 }
3415
3416                                 strbuf_add(&buf, bol, eol - bol);
3417
3418                                 cur = next[cur];
3419                         }
3420                 }
3421
3422                 fd = open(todo_file, O_WRONLY);
3423                 if (fd < 0)
3424                         res = error_errno(_("could not open '%s'"), todo_file);
3425                 else if (write(fd, buf.buf, buf.len) < 0)
3426                         res = error_errno(_("could not write to '%s'"), todo_file);
3427                 else if (ftruncate(fd, buf.len) < 0)
3428                         res = error_errno(_("could not truncate '%s'"),
3429                                            todo_file);
3430                 close(fd);
3431                 strbuf_release(&buf);
3432         }
3433
3434         free(next);
3435         free(tail);
3436         for (i = 0; i < todo_list.nr; i++)
3437                 free(subjects[i]);
3438         free(subjects);
3439         hashmap_free(&subject2item, 1);
3440         todo_list_release(&todo_list);
3441
3442         return res;
3443 }