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