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