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