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