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