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