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