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