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