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