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