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