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