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