rebase: extend --signoff support
[git] / sequencer.c
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "dir.h"
5 #include "object.h"
6 #include "commit.h"
7 #include "sequencer.h"
8 #include "tag.h"
9 #include "run-command.h"
10 #include "exec_cmd.h"
11 #include "utf8.h"
12 #include "cache-tree.h"
13 #include "diff.h"
14 #include "revision.h"
15 #include "rerere.h"
16 #include "merge-recursive.h"
17 #include "refs.h"
18 #include "argv-array.h"
19 #include "quote.h"
20 #include "trailer.h"
21 #include "log-tree.h"
22 #include "wt-status.h"
23 #include "hashmap.h"
24 #include "notes-utils.h"
25 #include "sigchain.h"
26
27 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
28
29 const char sign_off_header[] = "Signed-off-by: ";
30 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
31
32 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
33
34 GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
35
36 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
37 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
38 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
39 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
40
41 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
42 /*
43  * The file containing rebase commands, comments, and empty lines.
44  * This file is created by "git rebase -i" then edited by the user. As
45  * the lines are processed, they are removed from the front of this
46  * file and written to the tail of 'done'.
47  */
48 static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
49 /*
50  * The rebase command lines that have already been processed. A line
51  * is moved here when it is first handled, before any associated user
52  * actions.
53  */
54 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
55 /*
56  * The file to keep track of how many commands were already processed (e.g.
57  * for the prompt).
58  */
59 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
60 /*
61  * The file to keep track of how many commands are to be processed in total
62  * (e.g. for the prompt).
63  */
64 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
65 /*
66  * The commit message that is planned to be used for any changes that
67  * need to be committed following a user interaction.
68  */
69 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
70 /*
71  * The file into which is accumulated the suggested commit message for
72  * squash/fixup commands. When the first of a series of squash/fixups
73  * is seen, the file is created and the commit message from the
74  * previous commit and from the first squash/fixup commit are written
75  * to it. The commit message for each subsequent squash/fixup commit
76  * is appended to the file as it is processed.
77  *
78  * The first line of the file is of the form
79  *     # This is a combination of $count commits.
80  * where $count is the number of commits whose messages have been
81  * written to the file so far (including the initial "pick" commit).
82  * Each time that a commit message is processed, this line is read and
83  * updated. It is deleted just before the combined commit is made.
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  * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
96  * GIT_AUTHOR_DATE that will be used for the commit that is currently
97  * being rebased.
98  */
99 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
100 /*
101  * When an "edit" rebase command is being processed, the SHA1 of the
102  * commit to be edited is recorded in this file.  When "git rebase
103  * --continue" is executed, if there are any staged changes then they
104  * will be amended to the HEAD commit, but only provided the HEAD
105  * commit is still the commit to be edited.  When any other rebase
106  * command is processed, this file is deleted.
107  */
108 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
109 /*
110  * When we stop at a given patch via the "edit" command, this file contains
111  * the abbreviated commit name of the corresponding patch.
112  */
113 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
114 /*
115  * For the post-rewrite hook, we make a list of rewritten commits and
116  * their new sha1s.  The rewritten-pending list keeps the sha1s of
117  * commits that have been processed, but not committed yet,
118  * e.g. because they are waiting for a 'squash' command.
119  */
120 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
121 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
122         "rebase-merge/rewritten-pending")
123 /*
124  * The following files are written by git-rebase just after parsing the
125  * command-line (and are only consumed, not modified, by the sequencer).
126  */
127 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
128 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
129 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
130 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
131 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
132 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
133 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
134 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
135 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
136 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
137
138 static int git_sequencer_config(const char *k, const char *v, void *cb)
139 {
140         struct replay_opts *opts = cb;
141         int status;
142
143         if (!strcmp(k, "commit.cleanup")) {
144                 const char *s;
145
146                 status = git_config_string(&s, k, v);
147                 if (status)
148                         return status;
149
150                 if (!strcmp(s, "verbatim"))
151                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
152                 else if (!strcmp(s, "whitespace"))
153                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
154                 else if (!strcmp(s, "strip"))
155                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
156                 else if (!strcmp(s, "scissors"))
157                         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
158                 else
159                         warning(_("invalid commit message cleanup mode '%s'"),
160                                   s);
161
162                 return status;
163         }
164
165         if (!strcmp(k, "commit.gpgsign")) {
166                 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
167                 return 0;
168         }
169
170         status = git_gpg_config(k, v, NULL);
171         if (status)
172                 return status;
173
174         return git_diff_basic_config(k, v, NULL);
175 }
176
177 void sequencer_init_config(struct replay_opts *opts)
178 {
179         opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
180         git_config(git_sequencer_config, opts);
181 }
182
183 static inline int is_rebase_i(const struct replay_opts *opts)
184 {
185         return opts->action == REPLAY_INTERACTIVE_REBASE;
186 }
187
188 static const char *get_dir(const struct replay_opts *opts)
189 {
190         if (is_rebase_i(opts))
191                 return rebase_path();
192         return git_path_seq_dir();
193 }
194
195 static const char *get_todo_path(const struct replay_opts *opts)
196 {
197         if (is_rebase_i(opts))
198                 return rebase_path_todo();
199         return git_path_todo_file();
200 }
201
202 /*
203  * Returns 0 for non-conforming footer
204  * Returns 1 for conforming footer
205  * Returns 2 when sob exists within conforming footer
206  * Returns 3 when sob exists within conforming footer as last entry
207  */
208 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
209         int ignore_footer)
210 {
211         struct trailer_info info;
212         int i;
213         int found_sob = 0, found_sob_last = 0;
214
215         trailer_info_get(&info, sb->buf);
216
217         if (info.trailer_start == info.trailer_end)
218                 return 0;
219
220         for (i = 0; i < info.trailer_nr; i++)
221                 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
222                         found_sob = 1;
223                         if (i == info.trailer_nr - 1)
224                                 found_sob_last = 1;
225                 }
226
227         trailer_info_release(&info);
228
229         if (found_sob_last)
230                 return 3;
231         if (found_sob)
232                 return 2;
233         return 1;
234 }
235
236 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
237 {
238         static struct strbuf buf = STRBUF_INIT;
239
240         strbuf_reset(&buf);
241         if (opts->gpg_sign)
242                 sq_quotef(&buf, "-S%s", opts->gpg_sign);
243         return buf.buf;
244 }
245
246 int sequencer_remove_state(struct replay_opts *opts)
247 {
248         struct strbuf dir = STRBUF_INIT;
249         int i;
250
251         free(opts->gpg_sign);
252         free(opts->strategy);
253         for (i = 0; i < opts->xopts_nr; i++)
254                 free(opts->xopts[i]);
255         free(opts->xopts);
256
257         strbuf_addstr(&dir, get_dir(opts));
258         remove_dir_recursively(&dir, 0);
259         strbuf_release(&dir);
260
261         return 0;
262 }
263
264 static const char *action_name(const struct replay_opts *opts)
265 {
266         switch (opts->action) {
267         case REPLAY_REVERT:
268                 return N_("revert");
269         case REPLAY_PICK:
270                 return N_("cherry-pick");
271         case REPLAY_INTERACTIVE_REBASE:
272                 return N_("rebase -i");
273         }
274         die(_("Unknown action: %d"), opts->action);
275 }
276
277 struct commit_message {
278         char *parent_label;
279         char *label;
280         char *subject;
281         const char *message;
282 };
283
284 static const char *short_commit_name(struct commit *commit)
285 {
286         return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
287 }
288
289 static int get_message(struct commit *commit, struct commit_message *out)
290 {
291         const char *abbrev, *subject;
292         int subject_len;
293
294         out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
295         abbrev = short_commit_name(commit);
296
297         subject_len = find_commit_subject(out->message, &subject);
298
299         out->subject = xmemdupz(subject, subject_len);
300         out->label = xstrfmt("%s... %s", abbrev, out->subject);
301         out->parent_label = xstrfmt("parent of %s", out->label);
302
303         return 0;
304 }
305
306 static void free_message(struct commit *commit, struct commit_message *msg)
307 {
308         free(msg->parent_label);
309         free(msg->label);
310         free(msg->subject);
311         unuse_commit_buffer(commit, msg->message);
312 }
313
314 static void print_advice(int show_hint, struct replay_opts *opts)
315 {
316         char *msg = getenv("GIT_CHERRY_PICK_HELP");
317
318         if (msg) {
319                 fprintf(stderr, "%s\n", msg);
320                 /*
321                  * A conflict has occurred but the porcelain
322                  * (typically rebase --interactive) wants to take care
323                  * of the commit itself so remove CHERRY_PICK_HEAD
324                  */
325                 unlink(git_path_cherry_pick_head());
326                 return;
327         }
328
329         if (show_hint) {
330                 if (opts->no_commit)
331                         advise(_("after resolving the conflicts, mark the corrected paths\n"
332                                  "with 'git add <paths>' or 'git rm <paths>'"));
333                 else
334                         advise(_("after resolving the conflicts, mark the corrected paths\n"
335                                  "with 'git add <paths>' or 'git rm <paths>'\n"
336                                  "and commit the result with 'git commit'"));
337         }
338 }
339
340 static int write_message(const void *buf, size_t len, const char *filename,
341                          int append_eol)
342 {
343         static struct lock_file msg_file;
344
345         int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
346         if (msg_fd < 0)
347                 return error_errno(_("could not lock '%s'"), filename);
348         if (write_in_full(msg_fd, buf, len) < 0) {
349                 rollback_lock_file(&msg_file);
350                 return error_errno(_("could not write to '%s'"), filename);
351         }
352         if (append_eol && write(msg_fd, "\n", 1) < 0) {
353                 rollback_lock_file(&msg_file);
354                 return error_errno(_("could not write eol to '%s'"), filename);
355         }
356         if (commit_lock_file(&msg_file) < 0) {
357                 rollback_lock_file(&msg_file);
358                 return error(_("failed to finalize '%s'."), filename);
359         }
360
361         return 0;
362 }
363
364 /*
365  * Reads a file that was presumably written by a shell script, i.e. with an
366  * end-of-line marker that needs to be stripped.
367  *
368  * Note that only the last end-of-line marker is stripped, consistent with the
369  * behavior of "$(cat path)" in a shell script.
370  *
371  * Returns 1 if the file was read, 0 if it could not be read or does not exist.
372  */
373 static int read_oneliner(struct strbuf *buf,
374         const char *path, int skip_if_empty)
375 {
376         int orig_len = buf->len;
377
378         if (!file_exists(path))
379                 return 0;
380
381         if (strbuf_read_file(buf, path, 0) < 0) {
382                 warning_errno(_("could not read '%s'"), path);
383                 return 0;
384         }
385
386         if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
387                 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
388                         --buf->len;
389                 buf->buf[buf->len] = '\0';
390         }
391
392         if (skip_if_empty && buf->len == orig_len)
393                 return 0;
394
395         return 1;
396 }
397
398 static struct tree *empty_tree(void)
399 {
400         return lookup_tree(the_hash_algo->empty_tree);
401 }
402
403 static int error_dirty_index(struct replay_opts *opts)
404 {
405         if (read_cache_unmerged())
406                 return error_resolve_conflict(_(action_name(opts)));
407
408         error(_("your local changes would be overwritten by %s."),
409                 _(action_name(opts)));
410
411         if (advice_commit_before_merge)
412                 advise(_("commit your changes or stash them to proceed."));
413         return -1;
414 }
415
416 static void update_abort_safety_file(void)
417 {
418         struct object_id head;
419
420         /* Do nothing on a single-pick */
421         if (!file_exists(git_path_seq_dir()))
422                 return;
423
424         if (!get_oid("HEAD", &head))
425                 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
426         else
427                 write_file(git_path_abort_safety_file(), "%s", "");
428 }
429
430 static int fast_forward_to(const struct object_id *to, const struct object_id *from,
431                         int unborn, struct replay_opts *opts)
432 {
433         struct ref_transaction *transaction;
434         struct strbuf sb = STRBUF_INIT;
435         struct strbuf err = STRBUF_INIT;
436
437         read_cache();
438         if (checkout_fast_forward(from, to, 1))
439                 return -1; /* the callee should have complained already */
440
441         strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
442
443         transaction = ref_transaction_begin(&err);
444         if (!transaction ||
445             ref_transaction_update(transaction, "HEAD",
446                                    to, unborn ? &null_oid : from,
447                                    0, sb.buf, &err) ||
448             ref_transaction_commit(transaction, &err)) {
449                 ref_transaction_free(transaction);
450                 error("%s", err.buf);
451                 strbuf_release(&sb);
452                 strbuf_release(&err);
453                 return -1;
454         }
455
456         strbuf_release(&sb);
457         strbuf_release(&err);
458         ref_transaction_free(transaction);
459         update_abort_safety_file();
460         return 0;
461 }
462
463 void append_conflicts_hint(struct strbuf *msgbuf)
464 {
465         int i;
466
467         strbuf_addch(msgbuf, '\n');
468         strbuf_commented_addf(msgbuf, "Conflicts:\n");
469         for (i = 0; i < active_nr;) {
470                 const struct cache_entry *ce = active_cache[i++];
471                 if (ce_stage(ce)) {
472                         strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
473                         while (i < active_nr && !strcmp(ce->name,
474                                                         active_cache[i]->name))
475                                 i++;
476                 }
477         }
478 }
479
480 static int do_recursive_merge(struct commit *base, struct commit *next,
481                               const char *base_label, const char *next_label,
482                               struct object_id *head, struct strbuf *msgbuf,
483                               struct replay_opts *opts)
484 {
485         struct merge_options o;
486         struct tree *result, *next_tree, *base_tree, *head_tree;
487         int clean;
488         char **xopt;
489         static struct lock_file index_lock;
490
491         if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
492                 return -1;
493
494         read_cache();
495
496         init_merge_options(&o);
497         o.ancestor = base ? base_label : "(empty tree)";
498         o.branch1 = "HEAD";
499         o.branch2 = next ? next_label : "(empty tree)";
500         if (is_rebase_i(opts))
501                 o.buffer_output = 2;
502         o.show_rename_progress = 1;
503
504         head_tree = parse_tree_indirect(head);
505         next_tree = next ? next->tree : empty_tree();
506         base_tree = base ? base->tree : empty_tree();
507
508         for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
509                 parse_merge_opt(&o, *xopt);
510
511         clean = merge_trees(&o,
512                             head_tree,
513                             next_tree, base_tree, &result);
514         if (is_rebase_i(opts) && clean <= 0)
515                 fputs(o.obuf.buf, stdout);
516         strbuf_release(&o.obuf);
517         diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
518         if (clean < 0)
519                 return clean;
520
521         if (active_cache_changed &&
522             write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
523                 /*
524                  * TRANSLATORS: %s will be "revert", "cherry-pick" or
525                  * "rebase -i".
526                  */
527                 return error(_("%s: Unable to write new index file"),
528                         _(action_name(opts)));
529         rollback_lock_file(&index_lock);
530
531         if (!clean)
532                 append_conflicts_hint(msgbuf);
533
534         return !clean;
535 }
536
537 static int is_index_unchanged(void)
538 {
539         struct object_id head_oid;
540         struct commit *head_commit;
541
542         if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
543                 return error(_("could not resolve HEAD commit"));
544
545         head_commit = lookup_commit(&head_oid);
546
547         /*
548          * If head_commit is NULL, check_commit, called from
549          * lookup_commit, would have indicated that head_commit is not
550          * a commit object already.  parse_commit() will return failure
551          * without further complaints in such a case.  Otherwise, if
552          * the commit is invalid, parse_commit() will complain.  So
553          * there is nothing for us to say here.  Just return failure.
554          */
555         if (parse_commit(head_commit))
556                 return -1;
557
558         if (!active_cache_tree)
559                 active_cache_tree = cache_tree();
560
561         if (!cache_tree_fully_valid(active_cache_tree))
562                 if (cache_tree_update(&the_index, 0))
563                         return error(_("unable to update cache tree"));
564
565         return !oidcmp(&active_cache_tree->oid,
566                        &head_commit->tree->object.oid);
567 }
568
569 static int write_author_script(const char *message)
570 {
571         struct strbuf buf = STRBUF_INIT;
572         const char *eol;
573         int res;
574
575         for (;;)
576                 if (!*message || starts_with(message, "\n")) {
577 missing_author:
578                         /* Missing 'author' line? */
579                         unlink(rebase_path_author_script());
580                         return 0;
581                 } else if (skip_prefix(message, "author ", &message))
582                         break;
583                 else if ((eol = strchr(message, '\n')))
584                         message = eol + 1;
585                 else
586                         goto missing_author;
587
588         strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
589         while (*message && *message != '\n' && *message != '\r')
590                 if (skip_prefix(message, " <", &message))
591                         break;
592                 else if (*message != '\'')
593                         strbuf_addch(&buf, *(message++));
594                 else
595                         strbuf_addf(&buf, "'\\\\%c'", *(message++));
596         strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
597         while (*message && *message != '\n' && *message != '\r')
598                 if (skip_prefix(message, "> ", &message))
599                         break;
600                 else if (*message != '\'')
601                         strbuf_addch(&buf, *(message++));
602                 else
603                         strbuf_addf(&buf, "'\\\\%c'", *(message++));
604         strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
605         while (*message && *message != '\n' && *message != '\r')
606                 if (*message != '\'')
607                         strbuf_addch(&buf, *(message++));
608                 else
609                         strbuf_addf(&buf, "'\\\\%c'", *(message++));
610         res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
611         strbuf_release(&buf);
612         return res;
613 }
614
615 /*
616  * Read a list of environment variable assignments (such as the author-script
617  * file) into an environment block. Returns -1 on error, 0 otherwise.
618  */
619 static int read_env_script(struct argv_array *env)
620 {
621         struct strbuf script = STRBUF_INIT;
622         int i, count = 0;
623         char *p, *p2;
624
625         if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
626                 return -1;
627
628         for (p = script.buf; *p; p++)
629                 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
630                         strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
631                 else if (*p == '\'')
632                         strbuf_splice(&script, p-- - script.buf, 1, "", 0);
633                 else if (*p == '\n') {
634                         *p = '\0';
635                         count++;
636                 }
637
638         for (i = 0, p = script.buf; i < count; i++) {
639                 argv_array_push(env, p);
640                 p += strlen(p) + 1;
641         }
642
643         return 0;
644 }
645
646 static char *get_author(const char *message)
647 {
648         size_t len;
649         const char *a;
650
651         a = find_commit_header(message, "author", &len);
652         if (a)
653                 return xmemdupz(a, len);
654
655         return NULL;
656 }
657
658 static const char staged_changes_advice[] =
659 N_("you have staged changes in your working tree\n"
660 "If these changes are meant to be squashed into the previous commit, run:\n"
661 "\n"
662 "  git commit --amend %s\n"
663 "\n"
664 "If they are meant to go into a new commit, run:\n"
665 "\n"
666 "  git commit %s\n"
667 "\n"
668 "In both cases, once you're done, continue with:\n"
669 "\n"
670 "  git rebase --continue\n");
671
672 #define ALLOW_EMPTY (1<<0)
673 #define EDIT_MSG    (1<<1)
674 #define AMEND_MSG   (1<<2)
675 #define CLEANUP_MSG (1<<3)
676 #define VERIFY_MSG  (1<<4)
677
678 /*
679  * If we are cherry-pick, and if the merge did not result in
680  * hand-editing, we will hit this commit and inherit the original
681  * author date and name.
682  *
683  * If we are revert, or if our cherry-pick results in a hand merge,
684  * we had better say that the current user is responsible for that.
685  *
686  * An exception is when run_git_commit() is called during an
687  * interactive rebase: in that case, we will want to retain the
688  * author metadata.
689  */
690 static int run_git_commit(const char *defmsg, struct replay_opts *opts,
691                           unsigned int flags)
692 {
693         struct child_process cmd = CHILD_PROCESS_INIT;
694         const char *value;
695
696         cmd.git_cmd = 1;
697
698         if (is_rebase_i(opts)) {
699                 if (!(flags & EDIT_MSG)) {
700                         cmd.stdout_to_stderr = 1;
701                         cmd.err = -1;
702                 }
703
704                 if (read_env_script(&cmd.env_array)) {
705                         const char *gpg_opt = gpg_sign_opt_quoted(opts);
706
707                         return error(_(staged_changes_advice),
708                                      gpg_opt, gpg_opt);
709                 }
710         }
711
712         argv_array_push(&cmd.args, "commit");
713
714         if (!(flags & VERIFY_MSG))
715                 argv_array_push(&cmd.args, "-n");
716         if ((flags & AMEND_MSG))
717                 argv_array_push(&cmd.args, "--amend");
718         if (opts->gpg_sign)
719                 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
720         if (defmsg)
721                 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
722         if ((flags & CLEANUP_MSG))
723                 argv_array_push(&cmd.args, "--cleanup=strip");
724         if ((flags & EDIT_MSG))
725                 argv_array_push(&cmd.args, "-e");
726         else if (!(flags & CLEANUP_MSG) &&
727                  !opts->signoff && !opts->record_origin &&
728                  git_config_get_value("commit.cleanup", &value))
729                 argv_array_push(&cmd.args, "--cleanup=verbatim");
730
731         if ((flags & ALLOW_EMPTY))
732                 argv_array_push(&cmd.args, "--allow-empty");
733
734         if (opts->allow_empty_message)
735                 argv_array_push(&cmd.args, "--allow-empty-message");
736
737         if (cmd.err == -1) {
738                 /* hide stderr on success */
739                 struct strbuf buf = STRBUF_INIT;
740                 int rc = pipe_command(&cmd,
741                                       NULL, 0,
742                                       /* stdout is already redirected */
743                                       NULL, 0,
744                                       &buf, 0);
745                 if (rc)
746                         fputs(buf.buf, stderr);
747                 strbuf_release(&buf);
748                 return rc;
749         }
750
751         return run_command(&cmd);
752 }
753
754 static int rest_is_empty(const struct strbuf *sb, int start)
755 {
756         int i, eol;
757         const char *nl;
758
759         /* Check if the rest is just whitespace and Signed-off-by's. */
760         for (i = start; i < sb->len; i++) {
761                 nl = memchr(sb->buf + i, '\n', sb->len - i);
762                 if (nl)
763                         eol = nl - sb->buf;
764                 else
765                         eol = sb->len;
766
767                 if (strlen(sign_off_header) <= eol - i &&
768                     starts_with(sb->buf + i, sign_off_header)) {
769                         i = eol;
770                         continue;
771                 }
772                 while (i < eol)
773                         if (!isspace(sb->buf[i++]))
774                                 return 0;
775         }
776
777         return 1;
778 }
779
780 /*
781  * Find out if the message in the strbuf contains only whitespace and
782  * Signed-off-by lines.
783  */
784 int message_is_empty(const struct strbuf *sb,
785                      enum commit_msg_cleanup_mode cleanup_mode)
786 {
787         if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
788                 return 0;
789         return rest_is_empty(sb, 0);
790 }
791
792 /*
793  * See if the user edited the message in the editor or left what
794  * was in the template intact
795  */
796 int template_untouched(const struct strbuf *sb, const char *template_file,
797                        enum commit_msg_cleanup_mode cleanup_mode)
798 {
799         struct strbuf tmpl = STRBUF_INIT;
800         const char *start;
801
802         if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
803                 return 0;
804
805         if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
806                 return 0;
807
808         strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
809         if (!skip_prefix(sb->buf, tmpl.buf, &start))
810                 start = sb->buf;
811         strbuf_release(&tmpl);
812         return rest_is_empty(sb, start - sb->buf);
813 }
814
815 int update_head_with_reflog(const struct commit *old_head,
816                             const struct object_id *new_head,
817                             const char *action, const struct strbuf *msg,
818                             struct strbuf *err)
819 {
820         struct ref_transaction *transaction;
821         struct strbuf sb = STRBUF_INIT;
822         const char *nl;
823         int ret = 0;
824
825         if (action) {
826                 strbuf_addstr(&sb, action);
827                 strbuf_addstr(&sb, ": ");
828         }
829
830         nl = strchr(msg->buf, '\n');
831         if (nl) {
832                 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
833         } else {
834                 strbuf_addbuf(&sb, msg);
835                 strbuf_addch(&sb, '\n');
836         }
837
838         transaction = ref_transaction_begin(err);
839         if (!transaction ||
840             ref_transaction_update(transaction, "HEAD", new_head,
841                                    old_head ? &old_head->object.oid : &null_oid,
842                                    0, sb.buf, err) ||
843             ref_transaction_commit(transaction, err)) {
844                 ret = -1;
845         }
846         ref_transaction_free(transaction);
847         strbuf_release(&sb);
848
849         return ret;
850 }
851
852 static int run_rewrite_hook(const struct object_id *oldoid,
853                             const struct object_id *newoid)
854 {
855         struct child_process proc = CHILD_PROCESS_INIT;
856         const char *argv[3];
857         int code;
858         struct strbuf sb = STRBUF_INIT;
859
860         argv[0] = find_hook("post-rewrite");
861         if (!argv[0])
862                 return 0;
863
864         argv[1] = "amend";
865         argv[2] = NULL;
866
867         proc.argv = argv;
868         proc.in = -1;
869         proc.stdout_to_stderr = 1;
870
871         code = start_command(&proc);
872         if (code)
873                 return code;
874         strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
875         sigchain_push(SIGPIPE, SIG_IGN);
876         write_in_full(proc.in, sb.buf, sb.len);
877         close(proc.in);
878         strbuf_release(&sb);
879         sigchain_pop(SIGPIPE);
880         return finish_command(&proc);
881 }
882
883 void commit_post_rewrite(const struct commit *old_head,
884                          const struct object_id *new_head)
885 {
886         struct notes_rewrite_cfg *cfg;
887
888         cfg = init_copy_notes_for_rewrite("amend");
889         if (cfg) {
890                 /* we are amending, so old_head is not NULL */
891                 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
892                 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
893         }
894         run_rewrite_hook(&old_head->object.oid, new_head);
895 }
896
897 static int run_prepare_commit_msg_hook(struct strbuf *msg, const char *commit)
898 {
899         struct argv_array hook_env = ARGV_ARRAY_INIT;
900         int ret;
901         const char *name;
902
903         name = git_path_commit_editmsg();
904         if (write_message(msg->buf, msg->len, name, 0))
905                 return -1;
906
907         argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", get_index_file());
908         argv_array_push(&hook_env, "GIT_EDITOR=:");
909         if (commit)
910                 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
911                                   "commit", commit, NULL);
912         else
913                 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
914                                   "message", NULL);
915         if (ret)
916                 ret = error(_("'prepare-commit-msg' hook failed"));
917         argv_array_clear(&hook_env);
918
919         return ret;
920 }
921
922 static const char implicit_ident_advice_noconfig[] =
923 N_("Your name and email address were configured automatically based\n"
924 "on your username and hostname. Please check that they are accurate.\n"
925 "You can suppress this message by setting them explicitly. Run the\n"
926 "following command and follow the instructions in your editor to edit\n"
927 "your configuration file:\n"
928 "\n"
929 "    git config --global --edit\n"
930 "\n"
931 "After doing this, you may fix the identity used for this commit with:\n"
932 "\n"
933 "    git commit --amend --reset-author\n");
934
935 static const char implicit_ident_advice_config[] =
936 N_("Your name and email address were configured automatically based\n"
937 "on your username and hostname. Please check that they are accurate.\n"
938 "You can suppress this message by setting them explicitly:\n"
939 "\n"
940 "    git config --global user.name \"Your Name\"\n"
941 "    git config --global user.email you@example.com\n"
942 "\n"
943 "After doing this, you may fix the identity used for this commit with:\n"
944 "\n"
945 "    git commit --amend --reset-author\n");
946
947 static const char *implicit_ident_advice(void)
948 {
949         char *user_config = expand_user_path("~/.gitconfig", 0);
950         char *xdg_config = xdg_config_home("config");
951         int config_exists = file_exists(user_config) || file_exists(xdg_config);
952
953         free(user_config);
954         free(xdg_config);
955
956         if (config_exists)
957                 return _(implicit_ident_advice_config);
958         else
959                 return _(implicit_ident_advice_noconfig);
960
961 }
962
963 void print_commit_summary(const char *prefix, const struct object_id *oid,
964                           unsigned int flags)
965 {
966         struct rev_info rev;
967         struct commit *commit;
968         struct strbuf format = STRBUF_INIT;
969         const char *head;
970         struct pretty_print_context pctx = {0};
971         struct strbuf author_ident = STRBUF_INIT;
972         struct strbuf committer_ident = STRBUF_INIT;
973
974         commit = lookup_commit(oid);
975         if (!commit)
976                 die(_("couldn't look up newly created commit"));
977         if (parse_commit(commit))
978                 die(_("could not parse newly created commit"));
979
980         strbuf_addstr(&format, "format:%h] %s");
981
982         format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
983         format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
984         if (strbuf_cmp(&author_ident, &committer_ident)) {
985                 strbuf_addstr(&format, "\n Author: ");
986                 strbuf_addbuf_percentquote(&format, &author_ident);
987         }
988         if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
989                 struct strbuf date = STRBUF_INIT;
990
991                 format_commit_message(commit, "%ad", &date, &pctx);
992                 strbuf_addstr(&format, "\n Date: ");
993                 strbuf_addbuf_percentquote(&format, &date);
994                 strbuf_release(&date);
995         }
996         if (!committer_ident_sufficiently_given()) {
997                 strbuf_addstr(&format, "\n Committer: ");
998                 strbuf_addbuf_percentquote(&format, &committer_ident);
999                 if (advice_implicit_identity) {
1000                         strbuf_addch(&format, '\n');
1001                         strbuf_addstr(&format, implicit_ident_advice());
1002                 }
1003         }
1004         strbuf_release(&author_ident);
1005         strbuf_release(&committer_ident);
1006
1007         init_revisions(&rev, prefix);
1008         setup_revisions(0, NULL, &rev, NULL);
1009
1010         rev.diff = 1;
1011         rev.diffopt.output_format =
1012                 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1013
1014         rev.verbose_header = 1;
1015         rev.show_root_diff = 1;
1016         get_commit_format(format.buf, &rev);
1017         rev.always_show_header = 0;
1018         rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1019         rev.diffopt.break_opt = 0;
1020         diff_setup_done(&rev.diffopt);
1021
1022         head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1023         if (!head)
1024                 die_errno(_("unable to resolve HEAD after creating commit"));
1025         if (!strcmp(head, "HEAD"))
1026                 head = _("detached HEAD");
1027         else
1028                 skip_prefix(head, "refs/heads/", &head);
1029         printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1030                                                 _(" (root-commit)") : "");
1031
1032         if (!log_tree_commit(&rev, commit)) {
1033                 rev.always_show_header = 1;
1034                 rev.use_terminator = 1;
1035                 log_tree_commit(&rev, commit);
1036         }
1037
1038         strbuf_release(&format);
1039 }
1040
1041 static int parse_head(struct commit **head)
1042 {
1043         struct commit *current_head;
1044         struct object_id oid;
1045
1046         if (get_oid("HEAD", &oid)) {
1047                 current_head = NULL;
1048         } else {
1049                 current_head = lookup_commit_reference(&oid);
1050                 if (!current_head)
1051                         return error(_("could not parse HEAD"));
1052                 if (oidcmp(&oid, &current_head->object.oid)) {
1053                         warning(_("HEAD %s is not a commit!"),
1054                                 oid_to_hex(&oid));
1055                 }
1056                 if (parse_commit(current_head))
1057                         return error(_("could not parse HEAD commit"));
1058         }
1059         *head = current_head;
1060
1061         return 0;
1062 }
1063
1064 /*
1065  * Try to commit without forking 'git commit'. In some cases we need
1066  * to run 'git commit' to display an error message
1067  *
1068  * Returns:
1069  *  -1 - error unable to commit
1070  *   0 - success
1071  *   1 - run 'git commit'
1072  */
1073 static int try_to_commit(struct strbuf *msg, const char *author,
1074                          struct replay_opts *opts, unsigned int flags,
1075                          struct object_id *oid)
1076 {
1077         struct object_id tree;
1078         struct commit *current_head;
1079         struct commit_list *parents = NULL;
1080         struct commit_extra_header *extra = NULL;
1081         struct strbuf err = STRBUF_INIT;
1082         struct strbuf commit_msg = STRBUF_INIT;
1083         char *amend_author = NULL;
1084         const char *hook_commit = NULL;
1085         enum commit_msg_cleanup_mode cleanup;
1086         int res = 0;
1087
1088         if (parse_head(&current_head))
1089                 return -1;
1090
1091         if (flags & AMEND_MSG) {
1092                 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1093                 const char *out_enc = get_commit_output_encoding();
1094                 const char *message = logmsg_reencode(current_head, NULL,
1095                                                       out_enc);
1096
1097                 if (!msg) {
1098                         const char *orig_message = NULL;
1099
1100                         find_commit_subject(message, &orig_message);
1101                         msg = &commit_msg;
1102                         strbuf_addstr(msg, orig_message);
1103                         hook_commit = "HEAD";
1104                 }
1105                 author = amend_author = get_author(message);
1106                 unuse_commit_buffer(current_head, message);
1107                 if (!author) {
1108                         res = error(_("unable to parse commit author"));
1109                         goto out;
1110                 }
1111                 parents = copy_commit_list(current_head->parents);
1112                 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1113         } else if (current_head) {
1114                 commit_list_insert(current_head, &parents);
1115         }
1116
1117         if (write_cache_as_tree(tree.hash, 0, NULL)) {
1118                 res = error(_("git write-tree failed to write a tree"));
1119                 goto out;
1120         }
1121
1122         if (!(flags & ALLOW_EMPTY) && !oidcmp(current_head ?
1123                                               &current_head->tree->object.oid :
1124                                               &empty_tree_oid, &tree)) {
1125                 res = 1; /* run 'git commit' to display error message */
1126                 goto out;
1127         }
1128
1129         if (find_hook("prepare-commit-msg")) {
1130                 res = run_prepare_commit_msg_hook(msg, hook_commit);
1131                 if (res)
1132                         goto out;
1133                 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1134                                      2048) < 0) {
1135                         res = error_errno(_("unable to read commit message "
1136                                               "from '%s'"),
1137                                             git_path_commit_editmsg());
1138                         goto out;
1139                 }
1140                 msg = &commit_msg;
1141         }
1142
1143         cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1144                                           opts->default_msg_cleanup;
1145
1146         if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1147                 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1148         if (!opts->allow_empty_message && message_is_empty(msg, cleanup)) {
1149                 res = 1; /* run 'git commit' to display error message */
1150                 goto out;
1151         }
1152
1153         if (commit_tree_extended(msg->buf, msg->len, tree.hash, parents,
1154                                  oid->hash, author, opts->gpg_sign, extra)) {
1155                 res = error(_("failed to write commit object"));
1156                 goto out;
1157         }
1158
1159         if (update_head_with_reflog(current_head, oid,
1160                                     getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1161                 res = error("%s", err.buf);
1162                 goto out;
1163         }
1164
1165         if (flags & AMEND_MSG)
1166                 commit_post_rewrite(current_head, oid);
1167
1168 out:
1169         free_commit_extra_headers(extra);
1170         strbuf_release(&err);
1171         strbuf_release(&commit_msg);
1172         free(amend_author);
1173
1174         return res;
1175 }
1176
1177 static int do_commit(const char *msg_file, const char *author,
1178                      struct replay_opts *opts, unsigned int flags)
1179 {
1180         int res = 1;
1181
1182         if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1183                 struct object_id oid;
1184                 struct strbuf sb = STRBUF_INIT;
1185
1186                 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1187                         return error_errno(_("unable to read commit message "
1188                                              "from '%s'"),
1189                                            msg_file);
1190
1191                 res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1192                                     &oid);
1193                 strbuf_release(&sb);
1194                 if (!res) {
1195                         unlink(git_path_cherry_pick_head());
1196                         unlink(git_path_merge_msg());
1197                         if (!is_rebase_i(opts))
1198                                 print_commit_summary(NULL, &oid,
1199                                                 SUMMARY_SHOW_AUTHOR_DATE);
1200                         return res;
1201                 }
1202         }
1203         if (res == 1)
1204                 return run_git_commit(msg_file, opts, flags);
1205
1206         return res;
1207 }
1208
1209 static int is_original_commit_empty(struct commit *commit)
1210 {
1211         const struct object_id *ptree_oid;
1212
1213         if (parse_commit(commit))
1214                 return error(_("could not parse commit %s"),
1215                              oid_to_hex(&commit->object.oid));
1216         if (commit->parents) {
1217                 struct commit *parent = commit->parents->item;
1218                 if (parse_commit(parent))
1219                         return error(_("could not parse parent commit %s"),
1220                                 oid_to_hex(&parent->object.oid));
1221                 ptree_oid = &parent->tree->object.oid;
1222         } else {
1223                 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1224         }
1225
1226         return !oidcmp(ptree_oid, &commit->tree->object.oid);
1227 }
1228
1229 /*
1230  * Do we run "git commit" with "--allow-empty"?
1231  */
1232 static int allow_empty(struct replay_opts *opts, struct commit *commit)
1233 {
1234         int index_unchanged, empty_commit;
1235
1236         /*
1237          * Three cases:
1238          *
1239          * (1) we do not allow empty at all and error out.
1240          *
1241          * (2) we allow ones that were initially empty, but
1242          * forbid the ones that become empty;
1243          *
1244          * (3) we allow both.
1245          */
1246         if (!opts->allow_empty)
1247                 return 0; /* let "git commit" barf as necessary */
1248
1249         index_unchanged = is_index_unchanged();
1250         if (index_unchanged < 0)
1251                 return index_unchanged;
1252         if (!index_unchanged)
1253                 return 0; /* we do not have to say --allow-empty */
1254
1255         if (opts->keep_redundant_commits)
1256                 return 1;
1257
1258         empty_commit = is_original_commit_empty(commit);
1259         if (empty_commit < 0)
1260                 return empty_commit;
1261         if (!empty_commit)
1262                 return 0;
1263         else
1264                 return 1;
1265 }
1266
1267 /*
1268  * Note that ordering matters in this enum. Not only must it match the mapping
1269  * below, it is also divided into several sections that matter.  When adding
1270  * new commands, make sure you add it in the right section.
1271  */
1272 enum todo_command {
1273         /* commands that handle commits */
1274         TODO_PICK = 0,
1275         TODO_REVERT,
1276         TODO_EDIT,
1277         TODO_REWORD,
1278         TODO_FIXUP,
1279         TODO_SQUASH,
1280         /* commands that do something else than handling a single commit */
1281         TODO_EXEC,
1282         /* commands that do nothing but are counted for reporting progress */
1283         TODO_NOOP,
1284         TODO_DROP,
1285         /* comments (not counted for reporting progress) */
1286         TODO_COMMENT
1287 };
1288
1289 static struct {
1290         char c;
1291         const char *str;
1292 } todo_command_info[] = {
1293         { 'p', "pick" },
1294         { 0,   "revert" },
1295         { 'e', "edit" },
1296         { 'r', "reword" },
1297         { 'f', "fixup" },
1298         { 's', "squash" },
1299         { 'x', "exec" },
1300         { 0,   "noop" },
1301         { 'd', "drop" },
1302         { 0,   NULL }
1303 };
1304
1305 static const char *command_to_string(const enum todo_command command)
1306 {
1307         if (command < TODO_COMMENT)
1308                 return todo_command_info[command].str;
1309         die("Unknown command: %d", command);
1310 }
1311
1312 static char command_to_char(const enum todo_command command)
1313 {
1314         if (command < TODO_COMMENT && todo_command_info[command].c)
1315                 return todo_command_info[command].c;
1316         return comment_line_char;
1317 }
1318
1319 static int is_noop(const enum todo_command command)
1320 {
1321         return TODO_NOOP <= command;
1322 }
1323
1324 static int is_fixup(enum todo_command command)
1325 {
1326         return command == TODO_FIXUP || command == TODO_SQUASH;
1327 }
1328
1329 static int update_squash_messages(enum todo_command command,
1330                 struct commit *commit, struct replay_opts *opts)
1331 {
1332         struct strbuf buf = STRBUF_INIT;
1333         int count, res;
1334         const char *message, *body;
1335
1336         if (file_exists(rebase_path_squash_msg())) {
1337                 struct strbuf header = STRBUF_INIT;
1338                 char *eol, *p;
1339
1340                 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
1341                         return error(_("could not read '%s'"),
1342                                 rebase_path_squash_msg());
1343
1344                 p = buf.buf + 1;
1345                 eol = strchrnul(buf.buf, '\n');
1346                 if (buf.buf[0] != comment_line_char ||
1347                     (p += strcspn(p, "0123456789\n")) == eol)
1348                         return error(_("unexpected 1st line of squash message:"
1349                                        "\n\n\t%.*s"),
1350                                      (int)(eol - buf.buf), buf.buf);
1351                 count = strtol(p, NULL, 10);
1352
1353                 if (count < 1)
1354                         return error(_("invalid 1st line of squash message:\n"
1355                                        "\n\t%.*s"),
1356                                      (int)(eol - buf.buf), buf.buf);
1357
1358                 strbuf_addf(&header, "%c ", comment_line_char);
1359                 strbuf_addf(&header,
1360                             _("This is a combination of %d commits."), ++count);
1361                 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1362                 strbuf_release(&header);
1363         } else {
1364                 struct object_id head;
1365                 struct commit *head_commit;
1366                 const char *head_message, *body;
1367
1368                 if (get_oid("HEAD", &head))
1369                         return error(_("need a HEAD to fixup"));
1370                 if (!(head_commit = lookup_commit_reference(&head)))
1371                         return error(_("could not read HEAD"));
1372                 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1373                         return error(_("could not read HEAD's commit message"));
1374
1375                 find_commit_subject(head_message, &body);
1376                 if (write_message(body, strlen(body),
1377                                   rebase_path_fixup_msg(), 0)) {
1378                         unuse_commit_buffer(head_commit, head_message);
1379                         return error(_("cannot write '%s'"),
1380                                      rebase_path_fixup_msg());
1381                 }
1382
1383                 count = 2;
1384                 strbuf_addf(&buf, "%c ", comment_line_char);
1385                 strbuf_addf(&buf, _("This is a combination of %d commits."),
1386                             count);
1387                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1388                 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1389                 strbuf_addstr(&buf, "\n\n");
1390                 strbuf_addstr(&buf, body);
1391
1392                 unuse_commit_buffer(head_commit, head_message);
1393         }
1394
1395         if (!(message = get_commit_buffer(commit, NULL)))
1396                 return error(_("could not read commit message of %s"),
1397                              oid_to_hex(&commit->object.oid));
1398         find_commit_subject(message, &body);
1399
1400         if (command == TODO_SQUASH) {
1401                 unlink(rebase_path_fixup_msg());
1402                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1403                 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
1404                 strbuf_addstr(&buf, "\n\n");
1405                 strbuf_addstr(&buf, body);
1406         } else if (command == TODO_FIXUP) {
1407                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1408                 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
1409                             count);
1410                 strbuf_addstr(&buf, "\n\n");
1411                 strbuf_add_commented_lines(&buf, body, strlen(body));
1412         } else
1413                 return error(_("unknown command: %d"), command);
1414         unuse_commit_buffer(commit, message);
1415
1416         res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1417         strbuf_release(&buf);
1418         return res;
1419 }
1420
1421 static void flush_rewritten_pending(void) {
1422         struct strbuf buf = STRBUF_INIT;
1423         struct object_id newoid;
1424         FILE *out;
1425
1426         if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1427             !get_oid("HEAD", &newoid) &&
1428             (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1429                 char *bol = buf.buf, *eol;
1430
1431                 while (*bol) {
1432                         eol = strchrnul(bol, '\n');
1433                         fprintf(out, "%.*s %s\n", (int)(eol - bol),
1434                                         bol, oid_to_hex(&newoid));
1435                         if (!*eol)
1436                                 break;
1437                         bol = eol + 1;
1438                 }
1439                 fclose(out);
1440                 unlink(rebase_path_rewritten_pending());
1441         }
1442         strbuf_release(&buf);
1443 }
1444
1445 static void record_in_rewritten(struct object_id *oid,
1446                 enum todo_command next_command) {
1447         FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1448
1449         if (!out)
1450                 return;
1451
1452         fprintf(out, "%s\n", oid_to_hex(oid));
1453         fclose(out);
1454
1455         if (!is_fixup(next_command))
1456                 flush_rewritten_pending();
1457 }
1458
1459 static int do_pick_commit(enum todo_command command, struct commit *commit,
1460                 struct replay_opts *opts, int final_fixup)
1461 {
1462         unsigned int flags = opts->edit ? EDIT_MSG : 0;
1463         const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
1464         struct object_id head;
1465         struct commit *base, *next, *parent;
1466         const char *base_label, *next_label;
1467         char *author = NULL;
1468         struct commit_message msg = { NULL, NULL, NULL, NULL };
1469         struct strbuf msgbuf = STRBUF_INIT;
1470         int res, unborn = 0, allow;
1471
1472         if (opts->no_commit) {
1473                 /*
1474                  * We do not intend to commit immediately.  We just want to
1475                  * merge the differences in, so let's compute the tree
1476                  * that represents the "current" state for merge-recursive
1477                  * to work on.
1478                  */
1479                 if (write_cache_as_tree(head.hash, 0, NULL))
1480                         return error(_("your index file is unmerged."));
1481         } else {
1482                 unborn = get_oid("HEAD", &head);
1483                 if (unborn)
1484                         oidcpy(&head, the_hash_algo->empty_tree);
1485                 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
1486                                        NULL, 0))
1487                         return error_dirty_index(opts);
1488         }
1489         discard_cache();
1490
1491         if (!commit->parents)
1492                 parent = NULL;
1493         else if (commit->parents->next) {
1494                 /* Reverting or cherry-picking a merge commit */
1495                 int cnt;
1496                 struct commit_list *p;
1497
1498                 if (!opts->mainline)
1499                         return error(_("commit %s is a merge but no -m option was given."),
1500                                 oid_to_hex(&commit->object.oid));
1501
1502                 for (cnt = 1, p = commit->parents;
1503                      cnt != opts->mainline && p;
1504                      cnt++)
1505                         p = p->next;
1506                 if (cnt != opts->mainline || !p)
1507                         return error(_("commit %s does not have parent %d"),
1508                                 oid_to_hex(&commit->object.oid), opts->mainline);
1509                 parent = p->item;
1510         } else if (0 < opts->mainline)
1511                 return error(_("mainline was specified but commit %s is not a merge."),
1512                         oid_to_hex(&commit->object.oid));
1513         else
1514                 parent = commit->parents->item;
1515
1516         if (get_message(commit, &msg) != 0)
1517                 return error(_("cannot get commit message for %s"),
1518                         oid_to_hex(&commit->object.oid));
1519
1520         if (opts->allow_ff && !is_fixup(command) &&
1521             ((parent && !oidcmp(&parent->object.oid, &head)) ||
1522              (!parent && unborn))) {
1523                 if (is_rebase_i(opts))
1524                         write_author_script(msg.message);
1525                 res = fast_forward_to(&commit->object.oid, &head, unborn,
1526                         opts);
1527                 if (res || command != TODO_REWORD)
1528                         goto leave;
1529                 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1530                 msg_file = NULL;
1531                 goto fast_forward_edit;
1532         }
1533         if (parent && parse_commit(parent) < 0)
1534                 /* TRANSLATORS: The first %s will be a "todo" command like
1535                    "revert" or "pick", the second %s a SHA1. */
1536                 return error(_("%s: cannot parse parent commit %s"),
1537                         command_to_string(command),
1538                         oid_to_hex(&parent->object.oid));
1539
1540         /*
1541          * "commit" is an existing commit.  We would want to apply
1542          * the difference it introduces since its first parent "prev"
1543          * on top of the current HEAD if we are cherry-pick.  Or the
1544          * reverse of it if we are revert.
1545          */
1546
1547         if (command == TODO_REVERT) {
1548                 base = commit;
1549                 base_label = msg.label;
1550                 next = parent;
1551                 next_label = msg.parent_label;
1552                 strbuf_addstr(&msgbuf, "Revert \"");
1553                 strbuf_addstr(&msgbuf, msg.subject);
1554                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1555                 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1556
1557                 if (commit->parents && commit->parents->next) {
1558                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1559                         strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1560                 }
1561                 strbuf_addstr(&msgbuf, ".\n");
1562         } else {
1563                 const char *p;
1564
1565                 base = parent;
1566                 base_label = msg.parent_label;
1567                 next = commit;
1568                 next_label = msg.label;
1569
1570                 /* Append the commit log message to msgbuf. */
1571                 if (find_commit_subject(msg.message, &p))
1572                         strbuf_addstr(&msgbuf, p);
1573
1574                 if (opts->record_origin) {
1575                         strbuf_complete_line(&msgbuf);
1576                         if (!has_conforming_footer(&msgbuf, NULL, 0))
1577                                 strbuf_addch(&msgbuf, '\n');
1578                         strbuf_addstr(&msgbuf, cherry_picked_prefix);
1579                         strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1580                         strbuf_addstr(&msgbuf, ")\n");
1581                 }
1582                 if (!is_fixup(command))
1583                         author = get_author(msg.message);
1584         }
1585
1586         if (command == TODO_REWORD)
1587                 flags |= EDIT_MSG | VERIFY_MSG;
1588         else if (is_fixup(command)) {
1589                 if (update_squash_messages(command, commit, opts))
1590                         return -1;
1591                 flags |= AMEND_MSG;
1592                 if (!final_fixup)
1593                         msg_file = rebase_path_squash_msg();
1594                 else if (file_exists(rebase_path_fixup_msg())) {
1595                         flags |= CLEANUP_MSG;
1596                         msg_file = rebase_path_fixup_msg();
1597                 } else {
1598                         const char *dest = git_path_squash_msg();
1599                         unlink(dest);
1600                         if (copy_file(dest, rebase_path_squash_msg(), 0666))
1601                                 return error(_("could not rename '%s' to '%s'"),
1602                                              rebase_path_squash_msg(), dest);
1603                         unlink(git_path_merge_msg());
1604                         msg_file = dest;
1605                         flags |= EDIT_MSG;
1606                 }
1607         }
1608
1609         if (opts->signoff && !is_fixup(command))
1610                 append_signoff(&msgbuf, 0, 0);
1611
1612         if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1613                 res = -1;
1614         else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1615                 res = do_recursive_merge(base, next, base_label, next_label,
1616                                          &head, &msgbuf, opts);
1617                 if (res < 0)
1618                         return res;
1619                 res |= write_message(msgbuf.buf, msgbuf.len,
1620                                      git_path_merge_msg(), 0);
1621         } else {
1622                 struct commit_list *common = NULL;
1623                 struct commit_list *remotes = NULL;
1624
1625                 res = write_message(msgbuf.buf, msgbuf.len,
1626                                     git_path_merge_msg(), 0);
1627
1628                 commit_list_insert(base, &common);
1629                 commit_list_insert(next, &remotes);
1630                 res |= try_merge_command(opts->strategy,
1631                                          opts->xopts_nr, (const char **)opts->xopts,
1632                                         common, oid_to_hex(&head), remotes);
1633                 free_commit_list(common);
1634                 free_commit_list(remotes);
1635         }
1636         strbuf_release(&msgbuf);
1637
1638         /*
1639          * If the merge was clean or if it failed due to conflict, we write
1640          * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1641          * However, if the merge did not even start, then we don't want to
1642          * write it at all.
1643          */
1644         if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1645             update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1646                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1647                 res = -1;
1648         if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1649             update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1650                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1651                 res = -1;
1652
1653         if (res) {
1654                 error(command == TODO_REVERT
1655                       ? _("could not revert %s... %s")
1656                       : _("could not apply %s... %s"),
1657                       short_commit_name(commit), msg.subject);
1658                 print_advice(res == 1, opts);
1659                 rerere(opts->allow_rerere_auto);
1660                 goto leave;
1661         }
1662
1663         allow = allow_empty(opts, commit);
1664         if (allow < 0) {
1665                 res = allow;
1666                 goto leave;
1667         } else if (allow)
1668                 flags |= ALLOW_EMPTY;
1669         if (!opts->no_commit) {
1670 fast_forward_edit:
1671                 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1672                         res = do_commit(msg_file, author, opts, flags);
1673                 else
1674                         res = error(_("unable to parse commit author"));
1675         }
1676
1677         if (!res && final_fixup) {
1678                 unlink(rebase_path_fixup_msg());
1679                 unlink(rebase_path_squash_msg());
1680         }
1681
1682 leave:
1683         free_message(commit, &msg);
1684         free(author);
1685         update_abort_safety_file();
1686
1687         return res;
1688 }
1689
1690 static int prepare_revs(struct replay_opts *opts)
1691 {
1692         /*
1693          * picking (but not reverting) ranges (but not individual revisions)
1694          * should be done in reverse
1695          */
1696         if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1697                 opts->revs->reverse ^= 1;
1698
1699         if (prepare_revision_walk(opts->revs))
1700                 return error(_("revision walk setup failed"));
1701
1702         if (!opts->revs->commits)
1703                 return error(_("empty commit set passed"));
1704         return 0;
1705 }
1706
1707 static int read_and_refresh_cache(struct replay_opts *opts)
1708 {
1709         static struct lock_file index_lock;
1710         int index_fd = hold_locked_index(&index_lock, 0);
1711         if (read_index_preload(&the_index, NULL) < 0) {
1712                 rollback_lock_file(&index_lock);
1713                 return error(_("git %s: failed to read the index"),
1714                         _(action_name(opts)));
1715         }
1716         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1717         if (the_index.cache_changed && index_fd >= 0) {
1718                 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1719                         return error(_("git %s: failed to refresh the index"),
1720                                 _(action_name(opts)));
1721                 }
1722         }
1723         rollback_lock_file(&index_lock);
1724         return 0;
1725 }
1726
1727 struct todo_item {
1728         enum todo_command command;
1729         struct commit *commit;
1730         const char *arg;
1731         int arg_len;
1732         size_t offset_in_buf;
1733 };
1734
1735 struct todo_list {
1736         struct strbuf buf;
1737         struct todo_item *items;
1738         int nr, alloc, current;
1739         int done_nr, total_nr;
1740         struct stat_data stat;
1741 };
1742
1743 #define TODO_LIST_INIT { STRBUF_INIT }
1744
1745 static void todo_list_release(struct todo_list *todo_list)
1746 {
1747         strbuf_release(&todo_list->buf);
1748         FREE_AND_NULL(todo_list->items);
1749         todo_list->nr = todo_list->alloc = 0;
1750 }
1751
1752 static struct todo_item *append_new_todo(struct todo_list *todo_list)
1753 {
1754         ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1755         return todo_list->items + todo_list->nr++;
1756 }
1757
1758 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1759 {
1760         struct object_id commit_oid;
1761         char *end_of_object_name;
1762         int i, saved, status, padding;
1763
1764         /* left-trim */
1765         bol += strspn(bol, " \t");
1766
1767         if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1768                 item->command = TODO_COMMENT;
1769                 item->commit = NULL;
1770                 item->arg = bol;
1771                 item->arg_len = eol - bol;
1772                 return 0;
1773         }
1774
1775         for (i = 0; i < TODO_COMMENT; i++)
1776                 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1777                         item->command = i;
1778                         break;
1779                 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1780                         bol++;
1781                         item->command = i;
1782                         break;
1783                 }
1784         if (i >= TODO_COMMENT)
1785                 return -1;
1786
1787         /* Eat up extra spaces/ tabs before object name */
1788         padding = strspn(bol, " \t");
1789         bol += padding;
1790
1791         if (item->command == TODO_NOOP) {
1792                 if (bol != eol)
1793                         return error(_("%s does not accept arguments: '%s'"),
1794                                      command_to_string(item->command), bol);
1795                 item->commit = NULL;
1796                 item->arg = bol;
1797                 item->arg_len = eol - bol;
1798                 return 0;
1799         }
1800
1801         if (!padding)
1802                 return error(_("missing arguments for %s"),
1803                              command_to_string(item->command));
1804
1805         if (item->command == TODO_EXEC) {
1806                 item->commit = NULL;
1807                 item->arg = bol;
1808                 item->arg_len = (int)(eol - bol);
1809                 return 0;
1810         }
1811
1812         end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1813         saved = *end_of_object_name;
1814         *end_of_object_name = '\0';
1815         status = get_oid(bol, &commit_oid);
1816         *end_of_object_name = saved;
1817
1818         item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1819         item->arg_len = (int)(eol - item->arg);
1820
1821         if (status < 0)
1822                 return -1;
1823
1824         item->commit = lookup_commit_reference(&commit_oid);
1825         return !item->commit;
1826 }
1827
1828 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1829 {
1830         struct todo_item *item;
1831         char *p = buf, *next_p;
1832         int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1833
1834         for (i = 1; *p; i++, p = next_p) {
1835                 char *eol = strchrnul(p, '\n');
1836
1837                 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1838
1839                 if (p != eol && eol[-1] == '\r')
1840                         eol--; /* strip Carriage Return */
1841
1842                 item = append_new_todo(todo_list);
1843                 item->offset_in_buf = p - todo_list->buf.buf;
1844                 if (parse_insn_line(item, p, eol)) {
1845                         res = error(_("invalid line %d: %.*s"),
1846                                 i, (int)(eol - p), p);
1847                         item->command = TODO_NOOP;
1848                 }
1849
1850                 if (fixup_okay)
1851                         ; /* do nothing */
1852                 else if (is_fixup(item->command))
1853                         return error(_("cannot '%s' without a previous commit"),
1854                                 command_to_string(item->command));
1855                 else if (!is_noop(item->command))
1856                         fixup_okay = 1;
1857         }
1858
1859         return res;
1860 }
1861
1862 static int count_commands(struct todo_list *todo_list)
1863 {
1864         int count = 0, i;
1865
1866         for (i = 0; i < todo_list->nr; i++)
1867                 if (todo_list->items[i].command != TODO_COMMENT)
1868                         count++;
1869
1870         return count;
1871 }
1872
1873 static int read_populate_todo(struct todo_list *todo_list,
1874                         struct replay_opts *opts)
1875 {
1876         struct stat st;
1877         const char *todo_file = get_todo_path(opts);
1878         int fd, res;
1879
1880         strbuf_reset(&todo_list->buf);
1881         fd = open(todo_file, O_RDONLY);
1882         if (fd < 0)
1883                 return error_errno(_("could not open '%s'"), todo_file);
1884         if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1885                 close(fd);
1886                 return error(_("could not read '%s'."), todo_file);
1887         }
1888         close(fd);
1889
1890         res = stat(todo_file, &st);
1891         if (res)
1892                 return error(_("could not stat '%s'"), todo_file);
1893         fill_stat_data(&todo_list->stat, &st);
1894
1895         res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1896         if (res) {
1897                 if (is_rebase_i(opts))
1898                         return error(_("please fix this using "
1899                                        "'git rebase --edit-todo'."));
1900                 return error(_("unusable instruction sheet: '%s'"), todo_file);
1901         }
1902
1903         if (!todo_list->nr &&
1904             (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1905                 return error(_("no commits parsed."));
1906
1907         if (!is_rebase_i(opts)) {
1908                 enum todo_command valid =
1909                         opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1910                 int i;
1911
1912                 for (i = 0; i < todo_list->nr; i++)
1913                         if (valid == todo_list->items[i].command)
1914                                 continue;
1915                         else if (valid == TODO_PICK)
1916                                 return error(_("cannot cherry-pick during a revert."));
1917                         else
1918                                 return error(_("cannot revert during a cherry-pick."));
1919         }
1920
1921         if (is_rebase_i(opts)) {
1922                 struct todo_list done = TODO_LIST_INIT;
1923                 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
1924
1925                 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1926                                 !parse_insn_buffer(done.buf.buf, &done))
1927                         todo_list->done_nr = count_commands(&done);
1928                 else
1929                         todo_list->done_nr = 0;
1930
1931                 todo_list->total_nr = todo_list->done_nr
1932                         + count_commands(todo_list);
1933                 todo_list_release(&done);
1934
1935                 if (f) {
1936                         fprintf(f, "%d\n", todo_list->total_nr);
1937                         fclose(f);
1938                 }
1939         }
1940
1941         return 0;
1942 }
1943
1944 static int git_config_string_dup(char **dest,
1945                                  const char *var, const char *value)
1946 {
1947         if (!value)
1948                 return config_error_nonbool(var);
1949         free(*dest);
1950         *dest = xstrdup(value);
1951         return 0;
1952 }
1953
1954 static int populate_opts_cb(const char *key, const char *value, void *data)
1955 {
1956         struct replay_opts *opts = data;
1957         int error_flag = 1;
1958
1959         if (!value)
1960                 error_flag = 0;
1961         else if (!strcmp(key, "options.no-commit"))
1962                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1963         else if (!strcmp(key, "options.edit"))
1964                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1965         else if (!strcmp(key, "options.signoff"))
1966                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1967         else if (!strcmp(key, "options.record-origin"))
1968                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1969         else if (!strcmp(key, "options.allow-ff"))
1970                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1971         else if (!strcmp(key, "options.mainline"))
1972                 opts->mainline = git_config_int(key, value);
1973         else if (!strcmp(key, "options.strategy"))
1974                 git_config_string_dup(&opts->strategy, key, value);
1975         else if (!strcmp(key, "options.gpg-sign"))
1976                 git_config_string_dup(&opts->gpg_sign, key, value);
1977         else if (!strcmp(key, "options.strategy-option")) {
1978                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1979                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1980         } else if (!strcmp(key, "options.allow-rerere-auto"))
1981                 opts->allow_rerere_auto =
1982                         git_config_bool_or_int(key, value, &error_flag) ?
1983                                 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
1984         else
1985                 return error(_("invalid key: %s"), key);
1986
1987         if (!error_flag)
1988                 return error(_("invalid value for %s: %s"), key, value);
1989
1990         return 0;
1991 }
1992
1993 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1994 {
1995         int i;
1996
1997         strbuf_reset(buf);
1998         if (!read_oneliner(buf, rebase_path_strategy(), 0))
1999                 return;
2000         opts->strategy = strbuf_detach(buf, NULL);
2001         if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2002                 return;
2003
2004         opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
2005         for (i = 0; i < opts->xopts_nr; i++) {
2006                 const char *arg = opts->xopts[i];
2007
2008                 skip_prefix(arg, "--", &arg);
2009                 opts->xopts[i] = xstrdup(arg);
2010         }
2011 }
2012
2013 static int read_populate_opts(struct replay_opts *opts)
2014 {
2015         if (is_rebase_i(opts)) {
2016                 struct strbuf buf = STRBUF_INIT;
2017
2018                 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2019                         if (!starts_with(buf.buf, "-S"))
2020                                 strbuf_reset(&buf);
2021                         else {
2022                                 free(opts->gpg_sign);
2023                                 opts->gpg_sign = xstrdup(buf.buf + 2);
2024                         }
2025                         strbuf_reset(&buf);
2026                 }
2027
2028                 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2029                         if (!strcmp(buf.buf, "--rerere-autoupdate"))
2030                                 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2031                         else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2032                                 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2033                         strbuf_reset(&buf);
2034                 }
2035
2036                 if (file_exists(rebase_path_verbose()))
2037                         opts->verbose = 1;
2038
2039                 if (file_exists(rebase_path_signoff())) {
2040                         opts->allow_ff = 0;
2041                         opts->signoff = 1;
2042                 }
2043
2044                 read_strategy_opts(opts, &buf);
2045                 strbuf_release(&buf);
2046
2047                 return 0;
2048         }
2049
2050         if (!file_exists(git_path_opts_file()))
2051                 return 0;
2052         /*
2053          * The function git_parse_source(), called from git_config_from_file(),
2054          * may die() in case of a syntactically incorrect file. We do not care
2055          * about this case, though, because we wrote that file ourselves, so we
2056          * are pretty certain that it is syntactically correct.
2057          */
2058         if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2059                 return error(_("malformed options sheet: '%s'"),
2060                         git_path_opts_file());
2061         return 0;
2062 }
2063
2064 static int walk_revs_populate_todo(struct todo_list *todo_list,
2065                                 struct replay_opts *opts)
2066 {
2067         enum todo_command command = opts->action == REPLAY_PICK ?
2068                 TODO_PICK : TODO_REVERT;
2069         const char *command_string = todo_command_info[command].str;
2070         struct commit *commit;
2071
2072         if (prepare_revs(opts))
2073                 return -1;
2074
2075         while ((commit = get_revision(opts->revs))) {
2076                 struct todo_item *item = append_new_todo(todo_list);
2077                 const char *commit_buffer = get_commit_buffer(commit, NULL);
2078                 const char *subject;
2079                 int subject_len;
2080
2081                 item->command = command;
2082                 item->commit = commit;
2083                 item->arg = NULL;
2084                 item->arg_len = 0;
2085                 item->offset_in_buf = todo_list->buf.len;
2086                 subject_len = find_commit_subject(commit_buffer, &subject);
2087                 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2088                         short_commit_name(commit), subject_len, subject);
2089                 unuse_commit_buffer(commit, commit_buffer);
2090         }
2091         return 0;
2092 }
2093
2094 static int create_seq_dir(void)
2095 {
2096         if (file_exists(git_path_seq_dir())) {
2097                 error(_("a cherry-pick or revert is already in progress"));
2098                 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2099                 return -1;
2100         } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2101                 return error_errno(_("could not create sequencer directory '%s'"),
2102                                    git_path_seq_dir());
2103         return 0;
2104 }
2105
2106 static int save_head(const char *head)
2107 {
2108         static struct lock_file head_lock;
2109         struct strbuf buf = STRBUF_INIT;
2110         int fd;
2111         ssize_t written;
2112
2113         fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2114         if (fd < 0) {
2115                 rollback_lock_file(&head_lock);
2116                 return error_errno(_("could not lock HEAD"));
2117         }
2118         strbuf_addf(&buf, "%s\n", head);
2119         written = write_in_full(fd, buf.buf, buf.len);
2120         strbuf_release(&buf);
2121         if (written < 0) {
2122                 rollback_lock_file(&head_lock);
2123                 return error_errno(_("could not write to '%s'"),
2124                                    git_path_head_file());
2125         }
2126         if (commit_lock_file(&head_lock) < 0) {
2127                 rollback_lock_file(&head_lock);
2128                 return error(_("failed to finalize '%s'."), git_path_head_file());
2129         }
2130         return 0;
2131 }
2132
2133 static int rollback_is_safe(void)
2134 {
2135         struct strbuf sb = STRBUF_INIT;
2136         struct object_id expected_head, actual_head;
2137
2138         if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2139                 strbuf_trim(&sb);
2140                 if (get_oid_hex(sb.buf, &expected_head)) {
2141                         strbuf_release(&sb);
2142                         die(_("could not parse %s"), git_path_abort_safety_file());
2143                 }
2144                 strbuf_release(&sb);
2145         }
2146         else if (errno == ENOENT)
2147                 oidclr(&expected_head);
2148         else
2149                 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2150
2151         if (get_oid("HEAD", &actual_head))
2152                 oidclr(&actual_head);
2153
2154         return !oidcmp(&actual_head, &expected_head);
2155 }
2156
2157 static int reset_for_rollback(const struct object_id *oid)
2158 {
2159         const char *argv[4];    /* reset --merge <arg> + NULL */
2160
2161         argv[0] = "reset";
2162         argv[1] = "--merge";
2163         argv[2] = oid_to_hex(oid);
2164         argv[3] = NULL;
2165         return run_command_v_opt(argv, RUN_GIT_CMD);
2166 }
2167
2168 static int rollback_single_pick(void)
2169 {
2170         struct object_id head_oid;
2171
2172         if (!file_exists(git_path_cherry_pick_head()) &&
2173             !file_exists(git_path_revert_head()))
2174                 return error(_("no cherry-pick or revert in progress"));
2175         if (read_ref_full("HEAD", 0, &head_oid, NULL))
2176                 return error(_("cannot resolve HEAD"));
2177         if (is_null_oid(&head_oid))
2178                 return error(_("cannot abort from a branch yet to be born"));
2179         return reset_for_rollback(&head_oid);
2180 }
2181
2182 int sequencer_rollback(struct replay_opts *opts)
2183 {
2184         FILE *f;
2185         struct object_id oid;
2186         struct strbuf buf = STRBUF_INIT;
2187         const char *p;
2188
2189         f = fopen(git_path_head_file(), "r");
2190         if (!f && errno == ENOENT) {
2191                 /*
2192                  * There is no multiple-cherry-pick in progress.
2193                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2194                  * a single-cherry-pick in progress, abort that.
2195                  */
2196                 return rollback_single_pick();
2197         }
2198         if (!f)
2199                 return error_errno(_("cannot open '%s'"), git_path_head_file());
2200         if (strbuf_getline_lf(&buf, f)) {
2201                 error(_("cannot read '%s': %s"), git_path_head_file(),
2202                       ferror(f) ?  strerror(errno) : _("unexpected end of file"));
2203                 fclose(f);
2204                 goto fail;
2205         }
2206         fclose(f);
2207         if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2208                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2209                         git_path_head_file());
2210                 goto fail;
2211         }
2212         if (is_null_oid(&oid)) {
2213                 error(_("cannot abort from a branch yet to be born"));
2214                 goto fail;
2215         }
2216
2217         if (!rollback_is_safe()) {
2218                 /* Do not error, just do not rollback */
2219                 warning(_("You seem to have moved HEAD. "
2220                           "Not rewinding, check your HEAD!"));
2221         } else
2222         if (reset_for_rollback(&oid))
2223                 goto fail;
2224         strbuf_release(&buf);
2225         return sequencer_remove_state(opts);
2226 fail:
2227         strbuf_release(&buf);
2228         return -1;
2229 }
2230
2231 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2232 {
2233         static struct lock_file todo_lock;
2234         const char *todo_path = get_todo_path(opts);
2235         int next = todo_list->current, offset, fd;
2236
2237         /*
2238          * rebase -i writes "git-rebase-todo" without the currently executing
2239          * command, appending it to "done" instead.
2240          */
2241         if (is_rebase_i(opts))
2242                 next++;
2243
2244         fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2245         if (fd < 0)
2246                 return error_errno(_("could not lock '%s'"), todo_path);
2247         offset = next < todo_list->nr ?
2248                 todo_list->items[next].offset_in_buf : todo_list->buf.len;
2249         if (write_in_full(fd, todo_list->buf.buf + offset,
2250                         todo_list->buf.len - offset) < 0)
2251                 return error_errno(_("could not write to '%s'"), todo_path);
2252         if (commit_lock_file(&todo_lock) < 0)
2253                 return error(_("failed to finalize '%s'."), todo_path);
2254
2255         if (is_rebase_i(opts)) {
2256                 const char *done_path = rebase_path_done();
2257                 int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
2258                 int prev_offset = !next ? 0 :
2259                         todo_list->items[next - 1].offset_in_buf;
2260
2261                 if (fd >= 0 && offset > prev_offset &&
2262                     write_in_full(fd, todo_list->buf.buf + prev_offset,
2263                                   offset - prev_offset) < 0) {
2264                         close(fd);
2265                         return error_errno(_("could not write to '%s'"),
2266                                            done_path);
2267                 }
2268                 if (fd >= 0)
2269                         close(fd);
2270         }
2271         return 0;
2272 }
2273
2274 static int save_opts(struct replay_opts *opts)
2275 {
2276         const char *opts_file = git_path_opts_file();
2277         int res = 0;
2278
2279         if (opts->no_commit)
2280                 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2281         if (opts->edit)
2282                 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2283         if (opts->signoff)
2284                 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2285         if (opts->record_origin)
2286                 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2287         if (opts->allow_ff)
2288                 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2289         if (opts->mainline) {
2290                 struct strbuf buf = STRBUF_INIT;
2291                 strbuf_addf(&buf, "%d", opts->mainline);
2292                 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2293                 strbuf_release(&buf);
2294         }
2295         if (opts->strategy)
2296                 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2297         if (opts->gpg_sign)
2298                 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2299         if (opts->xopts) {
2300                 int i;
2301                 for (i = 0; i < opts->xopts_nr; i++)
2302                         res |= git_config_set_multivar_in_file_gently(opts_file,
2303                                                         "options.strategy-option",
2304                                                         opts->xopts[i], "^$", 0);
2305         }
2306         if (opts->allow_rerere_auto)
2307                 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2308                                                      opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2309                                                      "true" : "false");
2310         return res;
2311 }
2312
2313 static int make_patch(struct commit *commit, struct replay_opts *opts)
2314 {
2315         struct strbuf buf = STRBUF_INIT;
2316         struct rev_info log_tree_opt;
2317         const char *subject, *p;
2318         int res = 0;
2319
2320         p = short_commit_name(commit);
2321         if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2322                 return -1;
2323
2324         strbuf_addf(&buf, "%s/patch", get_dir(opts));
2325         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2326         init_revisions(&log_tree_opt, NULL);
2327         log_tree_opt.abbrev = 0;
2328         log_tree_opt.diff = 1;
2329         log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2330         log_tree_opt.disable_stdin = 1;
2331         log_tree_opt.no_commit_id = 1;
2332         log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2333         log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2334         if (!log_tree_opt.diffopt.file)
2335                 res |= error_errno(_("could not open '%s'"), buf.buf);
2336         else {
2337                 res |= log_tree_commit(&log_tree_opt, commit);
2338                 fclose(log_tree_opt.diffopt.file);
2339         }
2340         strbuf_reset(&buf);
2341
2342         strbuf_addf(&buf, "%s/message", get_dir(opts));
2343         if (!file_exists(buf.buf)) {
2344                 const char *commit_buffer = get_commit_buffer(commit, NULL);
2345                 find_commit_subject(commit_buffer, &subject);
2346                 res |= write_message(subject, strlen(subject), buf.buf, 1);
2347                 unuse_commit_buffer(commit, commit_buffer);
2348         }
2349         strbuf_release(&buf);
2350
2351         return res;
2352 }
2353
2354 static int intend_to_amend(void)
2355 {
2356         struct object_id head;
2357         char *p;
2358
2359         if (get_oid("HEAD", &head))
2360                 return error(_("cannot read HEAD"));
2361
2362         p = oid_to_hex(&head);
2363         return write_message(p, strlen(p), rebase_path_amend(), 1);
2364 }
2365
2366 static int error_with_patch(struct commit *commit,
2367         const char *subject, int subject_len,
2368         struct replay_opts *opts, int exit_code, int to_amend)
2369 {
2370         if (make_patch(commit, opts))
2371                 return -1;
2372
2373         if (to_amend) {
2374                 if (intend_to_amend())
2375                         return -1;
2376
2377                 fprintf(stderr, "You can amend the commit now, with\n"
2378                         "\n"
2379                         "  git commit --amend %s\n"
2380                         "\n"
2381                         "Once you are satisfied with your changes, run\n"
2382                         "\n"
2383                         "  git rebase --continue\n", gpg_sign_opt_quoted(opts));
2384         } else if (exit_code)
2385                 fprintf(stderr, "Could not apply %s... %.*s\n",
2386                         short_commit_name(commit), subject_len, subject);
2387
2388         return exit_code;
2389 }
2390
2391 static int error_failed_squash(struct commit *commit,
2392         struct replay_opts *opts, int subject_len, const char *subject)
2393 {
2394         if (rename(rebase_path_squash_msg(), rebase_path_message()))
2395                 return error(_("could not rename '%s' to '%s'"),
2396                         rebase_path_squash_msg(), rebase_path_message());
2397         unlink(rebase_path_fixup_msg());
2398         unlink(git_path_merge_msg());
2399         if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
2400                 return error(_("could not copy '%s' to '%s'"),
2401                              rebase_path_message(), git_path_merge_msg());
2402         return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2403 }
2404
2405 static int do_exec(const char *command_line)
2406 {
2407         struct argv_array child_env = ARGV_ARRAY_INIT;
2408         const char *child_argv[] = { NULL, NULL };
2409         int dirty, status;
2410
2411         fprintf(stderr, "Executing: %s\n", command_line);
2412         child_argv[0] = command_line;
2413         argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2414         status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2415                                           child_env.argv);
2416
2417         /* force re-reading of the cache */
2418         if (discard_cache() < 0 || read_cache() < 0)
2419                 return error(_("could not read index"));
2420
2421         dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2422
2423         if (status) {
2424                 warning(_("execution failed: %s\n%s"
2425                           "You can fix the problem, and then run\n"
2426                           "\n"
2427                           "  git rebase --continue\n"
2428                           "\n"),
2429                         command_line,
2430                         dirty ? N_("and made changes to the index and/or the "
2431                                 "working tree\n") : "");
2432                 if (status == 127)
2433                         /* command not found */
2434                         status = 1;
2435         } else if (dirty) {
2436                 warning(_("execution succeeded: %s\nbut "
2437                           "left changes to the index and/or the working tree\n"
2438                           "Commit or stash your changes, and then run\n"
2439                           "\n"
2440                           "  git rebase --continue\n"
2441                           "\n"), command_line);
2442                 status = 1;
2443         }
2444
2445         argv_array_clear(&child_env);
2446
2447         return status;
2448 }
2449
2450 static int is_final_fixup(struct todo_list *todo_list)
2451 {
2452         int i = todo_list->current;
2453
2454         if (!is_fixup(todo_list->items[i].command))
2455                 return 0;
2456
2457         while (++i < todo_list->nr)
2458                 if (is_fixup(todo_list->items[i].command))
2459                         return 0;
2460                 else if (!is_noop(todo_list->items[i].command))
2461                         break;
2462         return 1;
2463 }
2464
2465 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2466 {
2467         int i;
2468
2469         for (i = todo_list->current + offset; i < todo_list->nr; i++)
2470                 if (!is_noop(todo_list->items[i].command))
2471                         return todo_list->items[i].command;
2472
2473         return -1;
2474 }
2475
2476 static int apply_autostash(struct replay_opts *opts)
2477 {
2478         struct strbuf stash_sha1 = STRBUF_INIT;
2479         struct child_process child = CHILD_PROCESS_INIT;
2480         int ret = 0;
2481
2482         if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2483                 strbuf_release(&stash_sha1);
2484                 return 0;
2485         }
2486         strbuf_trim(&stash_sha1);
2487
2488         child.git_cmd = 1;
2489         child.no_stdout = 1;
2490         child.no_stderr = 1;
2491         argv_array_push(&child.args, "stash");
2492         argv_array_push(&child.args, "apply");
2493         argv_array_push(&child.args, stash_sha1.buf);
2494         if (!run_command(&child))
2495                 fprintf(stderr, _("Applied autostash.\n"));
2496         else {
2497                 struct child_process store = CHILD_PROCESS_INIT;
2498
2499                 store.git_cmd = 1;
2500                 argv_array_push(&store.args, "stash");
2501                 argv_array_push(&store.args, "store");
2502                 argv_array_push(&store.args, "-m");
2503                 argv_array_push(&store.args, "autostash");
2504                 argv_array_push(&store.args, "-q");
2505                 argv_array_push(&store.args, stash_sha1.buf);
2506                 if (run_command(&store))
2507                         ret = error(_("cannot store %s"), stash_sha1.buf);
2508                 else
2509                         fprintf(stderr,
2510                                 _("Applying autostash resulted in conflicts.\n"
2511                                   "Your changes are safe in the stash.\n"
2512                                   "You can run \"git stash pop\" or"
2513                                   " \"git stash drop\" at any time.\n"));
2514         }
2515
2516         strbuf_release(&stash_sha1);
2517         return ret;
2518 }
2519
2520 static const char *reflog_message(struct replay_opts *opts,
2521         const char *sub_action, const char *fmt, ...)
2522 {
2523         va_list ap;
2524         static struct strbuf buf = STRBUF_INIT;
2525
2526         va_start(ap, fmt);
2527         strbuf_reset(&buf);
2528         strbuf_addstr(&buf, action_name(opts));
2529         if (sub_action)
2530                 strbuf_addf(&buf, " (%s)", sub_action);
2531         if (fmt) {
2532                 strbuf_addstr(&buf, ": ");
2533                 strbuf_vaddf(&buf, fmt, ap);
2534         }
2535         va_end(ap);
2536
2537         return buf.buf;
2538 }
2539
2540 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2541 {
2542         int res = 0;
2543
2544         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2545         if (opts->allow_ff)
2546                 assert(!(opts->signoff || opts->no_commit ||
2547                                 opts->record_origin || opts->edit));
2548         if (read_and_refresh_cache(opts))
2549                 return -1;
2550
2551         while (todo_list->current < todo_list->nr) {
2552                 struct todo_item *item = todo_list->items + todo_list->current;
2553                 if (save_todo(todo_list, opts))
2554                         return -1;
2555                 if (is_rebase_i(opts)) {
2556                         if (item->command != TODO_COMMENT) {
2557                                 FILE *f = fopen(rebase_path_msgnum(), "w");
2558
2559                                 todo_list->done_nr++;
2560
2561                                 if (f) {
2562                                         fprintf(f, "%d\n", todo_list->done_nr);
2563                                         fclose(f);
2564                                 }
2565                                 fprintf(stderr, "Rebasing (%d/%d)%s",
2566                                         todo_list->done_nr,
2567                                         todo_list->total_nr,
2568                                         opts->verbose ? "\n" : "\r");
2569                         }
2570                         unlink(rebase_path_message());
2571                         unlink(rebase_path_author_script());
2572                         unlink(rebase_path_stopped_sha());
2573                         unlink(rebase_path_amend());
2574                 }
2575                 if (item->command <= TODO_SQUASH) {
2576                         if (is_rebase_i(opts))
2577                                 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
2578                                         command_to_string(item->command), NULL),
2579                                         1);
2580                         res = do_pick_commit(item->command, item->commit,
2581                                         opts, is_final_fixup(todo_list));
2582                         if (is_rebase_i(opts) && res < 0) {
2583                                 /* Reschedule */
2584                                 todo_list->current--;
2585                                 if (save_todo(todo_list, opts))
2586                                         return -1;
2587                         }
2588                         if (item->command == TODO_EDIT) {
2589                                 struct commit *commit = item->commit;
2590                                 if (!res)
2591                                         fprintf(stderr,
2592                                                 _("Stopped at %s...  %.*s\n"),
2593                                                 short_commit_name(commit),
2594                                                 item->arg_len, item->arg);
2595                                 return error_with_patch(commit,
2596                                         item->arg, item->arg_len, opts, res,
2597                                         !res);
2598                         }
2599                         if (is_rebase_i(opts) && !res)
2600                                 record_in_rewritten(&item->commit->object.oid,
2601                                         peek_command(todo_list, 1));
2602                         if (res && is_fixup(item->command)) {
2603                                 if (res == 1)
2604                                         intend_to_amend();
2605                                 return error_failed_squash(item->commit, opts,
2606                                         item->arg_len, item->arg);
2607                         } else if (res && is_rebase_i(opts))
2608                                 return res | error_with_patch(item->commit,
2609                                         item->arg, item->arg_len, opts, res,
2610                                         item->command == TODO_REWORD);
2611                 } else if (item->command == TODO_EXEC) {
2612                         char *end_of_arg = (char *)(item->arg + item->arg_len);
2613                         int saved = *end_of_arg;
2614                         struct stat st;
2615
2616                         *end_of_arg = '\0';
2617                         res = do_exec(item->arg);
2618                         *end_of_arg = saved;
2619
2620                         /* Reread the todo file if it has changed. */
2621                         if (res)
2622                                 ; /* fall through */
2623                         else if (stat(get_todo_path(opts), &st))
2624                                 res = error_errno(_("could not stat '%s'"),
2625                                                   get_todo_path(opts));
2626                         else if (match_stat_data(&todo_list->stat, &st)) {
2627                                 todo_list_release(todo_list);
2628                                 if (read_populate_todo(todo_list, opts))
2629                                         res = -1; /* message was printed */
2630                                 /* `current` will be incremented below */
2631                                 todo_list->current = -1;
2632                         }
2633                 } else if (!is_noop(item->command))
2634                         return error(_("unknown command %d"), item->command);
2635
2636                 todo_list->current++;
2637                 if (res)
2638                         return res;
2639         }
2640
2641         if (is_rebase_i(opts)) {
2642                 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2643                 struct stat st;
2644
2645                 /* Stopped in the middle, as planned? */
2646                 if (todo_list->current < todo_list->nr)
2647                         return 0;
2648
2649                 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2650                                 starts_with(head_ref.buf, "refs/")) {
2651                         const char *msg;
2652                         struct object_id head, orig;
2653                         int res;
2654
2655                         if (get_oid("HEAD", &head)) {
2656                                 res = error(_("cannot read HEAD"));
2657 cleanup_head_ref:
2658                                 strbuf_release(&head_ref);
2659                                 strbuf_release(&buf);
2660                                 return res;
2661                         }
2662                         if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2663                                         get_oid_hex(buf.buf, &orig)) {
2664                                 res = error(_("could not read orig-head"));
2665                                 goto cleanup_head_ref;
2666                         }
2667                         strbuf_reset(&buf);
2668                         if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2669                                 res = error(_("could not read 'onto'"));
2670                                 goto cleanup_head_ref;
2671                         }
2672                         msg = reflog_message(opts, "finish", "%s onto %s",
2673                                 head_ref.buf, buf.buf);
2674                         if (update_ref(msg, head_ref.buf, &head, &orig,
2675                                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
2676                                 res = error(_("could not update %s"),
2677                                         head_ref.buf);
2678                                 goto cleanup_head_ref;
2679                         }
2680                         msg = reflog_message(opts, "finish", "returning to %s",
2681                                 head_ref.buf);
2682                         if (create_symref("HEAD", head_ref.buf, msg)) {
2683                                 res = error(_("could not update HEAD to %s"),
2684                                         head_ref.buf);
2685                                 goto cleanup_head_ref;
2686                         }
2687                         strbuf_reset(&buf);
2688                 }
2689
2690                 if (opts->verbose) {
2691                         struct rev_info log_tree_opt;
2692                         struct object_id orig, head;
2693
2694                         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2695                         init_revisions(&log_tree_opt, NULL);
2696                         log_tree_opt.diff = 1;
2697                         log_tree_opt.diffopt.output_format =
2698                                 DIFF_FORMAT_DIFFSTAT;
2699                         log_tree_opt.disable_stdin = 1;
2700
2701                         if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2702                             !get_oid(buf.buf, &orig) &&
2703                             !get_oid("HEAD", &head)) {
2704                                 diff_tree_oid(&orig, &head, "",
2705                                               &log_tree_opt.diffopt);
2706                                 log_tree_diff_flush(&log_tree_opt);
2707                         }
2708                 }
2709                 flush_rewritten_pending();
2710                 if (!stat(rebase_path_rewritten_list(), &st) &&
2711                                 st.st_size > 0) {
2712                         struct child_process child = CHILD_PROCESS_INIT;
2713                         const char *post_rewrite_hook =
2714                                 find_hook("post-rewrite");
2715
2716                         child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2717                         child.git_cmd = 1;
2718                         argv_array_push(&child.args, "notes");
2719                         argv_array_push(&child.args, "copy");
2720                         argv_array_push(&child.args, "--for-rewrite=rebase");
2721                         /* we don't care if this copying failed */
2722                         run_command(&child);
2723
2724                         if (post_rewrite_hook) {
2725                                 struct child_process hook = CHILD_PROCESS_INIT;
2726
2727                                 hook.in = open(rebase_path_rewritten_list(),
2728                                         O_RDONLY);
2729                                 hook.stdout_to_stderr = 1;
2730                                 argv_array_push(&hook.args, post_rewrite_hook);
2731                                 argv_array_push(&hook.args, "rebase");
2732                                 /* we don't care if this hook failed */
2733                                 run_command(&hook);
2734                         }
2735                 }
2736                 apply_autostash(opts);
2737
2738                 fprintf(stderr, "Successfully rebased and updated %s.\n",
2739                         head_ref.buf);
2740
2741                 strbuf_release(&buf);
2742                 strbuf_release(&head_ref);
2743         }
2744
2745         /*
2746          * Sequence of picks finished successfully; cleanup by
2747          * removing the .git/sequencer directory
2748          */
2749         return sequencer_remove_state(opts);
2750 }
2751
2752 static int continue_single_pick(void)
2753 {
2754         const char *argv[] = { "commit", NULL };
2755
2756         if (!file_exists(git_path_cherry_pick_head()) &&
2757             !file_exists(git_path_revert_head()))
2758                 return error(_("no cherry-pick or revert in progress"));
2759         return run_command_v_opt(argv, RUN_GIT_CMD);
2760 }
2761
2762 static int commit_staged_changes(struct replay_opts *opts)
2763 {
2764         unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
2765
2766         if (has_unstaged_changes(1))
2767                 return error(_("cannot rebase: You have unstaged changes."));
2768         if (!has_uncommitted_changes(0)) {
2769                 const char *cherry_pick_head = git_path_cherry_pick_head();
2770
2771                 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2772                         return error(_("could not remove CHERRY_PICK_HEAD"));
2773                 return 0;
2774         }
2775
2776         if (file_exists(rebase_path_amend())) {
2777                 struct strbuf rev = STRBUF_INIT;
2778                 struct object_id head, to_amend;
2779
2780                 if (get_oid("HEAD", &head))
2781                         return error(_("cannot amend non-existing commit"));
2782                 if (!read_oneliner(&rev, rebase_path_amend(), 0))
2783                         return error(_("invalid file: '%s'"), rebase_path_amend());
2784                 if (get_oid_hex(rev.buf, &to_amend))
2785                         return error(_("invalid contents: '%s'"),
2786                                 rebase_path_amend());
2787                 if (oidcmp(&head, &to_amend))
2788                         return error(_("\nYou have uncommitted changes in your "
2789                                        "working tree. Please, commit them\n"
2790                                        "first and then run 'git rebase "
2791                                        "--continue' again."));
2792
2793                 strbuf_release(&rev);
2794                 flags |= AMEND_MSG;
2795         }
2796
2797         if (run_git_commit(rebase_path_message(), opts, flags))
2798                 return error(_("could not commit staged changes."));
2799         unlink(rebase_path_amend());
2800         return 0;
2801 }
2802
2803 int sequencer_continue(struct replay_opts *opts)
2804 {
2805         struct todo_list todo_list = TODO_LIST_INIT;
2806         int res;
2807
2808         if (read_and_refresh_cache(opts))
2809                 return -1;
2810
2811         if (is_rebase_i(opts)) {
2812                 if (commit_staged_changes(opts))
2813                         return -1;
2814         } else if (!file_exists(get_todo_path(opts)))
2815                 return continue_single_pick();
2816         if (read_populate_opts(opts))
2817                 return -1;
2818         if ((res = read_populate_todo(&todo_list, opts)))
2819                 goto release_todo_list;
2820
2821         if (!is_rebase_i(opts)) {
2822                 /* Verify that the conflict has been resolved */
2823                 if (file_exists(git_path_cherry_pick_head()) ||
2824                     file_exists(git_path_revert_head())) {
2825                         res = continue_single_pick();
2826                         if (res)
2827                                 goto release_todo_list;
2828                 }
2829                 if (index_differs_from("HEAD", NULL, 0)) {
2830                         res = error_dirty_index(opts);
2831                         goto release_todo_list;
2832                 }
2833                 todo_list.current++;
2834         } else if (file_exists(rebase_path_stopped_sha())) {
2835                 struct strbuf buf = STRBUF_INIT;
2836                 struct object_id oid;
2837
2838                 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2839                     !get_oid_committish(buf.buf, &oid))
2840                         record_in_rewritten(&oid, peek_command(&todo_list, 0));
2841                 strbuf_release(&buf);
2842         }
2843
2844         res = pick_commits(&todo_list, opts);
2845 release_todo_list:
2846         todo_list_release(&todo_list);
2847         return res;
2848 }
2849
2850 static int single_pick(struct commit *cmit, struct replay_opts *opts)
2851 {
2852         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2853         return do_pick_commit(opts->action == REPLAY_PICK ?
2854                 TODO_PICK : TODO_REVERT, cmit, opts, 0);
2855 }
2856
2857 int sequencer_pick_revisions(struct replay_opts *opts)
2858 {
2859         struct todo_list todo_list = TODO_LIST_INIT;
2860         struct object_id oid;
2861         int i, res;
2862
2863         assert(opts->revs);
2864         if (read_and_refresh_cache(opts))
2865                 return -1;
2866
2867         for (i = 0; i < opts->revs->pending.nr; i++) {
2868                 struct object_id oid;
2869                 const char *name = opts->revs->pending.objects[i].name;
2870
2871                 /* This happens when using --stdin. */
2872                 if (!strlen(name))
2873                         continue;
2874
2875                 if (!get_oid(name, &oid)) {
2876                         if (!lookup_commit_reference_gently(&oid, 1)) {
2877                                 enum object_type type = sha1_object_info(oid.hash, NULL);
2878                                 return error(_("%s: can't cherry-pick a %s"),
2879                                         name, typename(type));
2880                         }
2881                 } else
2882                         return error(_("%s: bad revision"), name);
2883         }
2884
2885         /*
2886          * If we were called as "git cherry-pick <commit>", just
2887          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2888          * REVERT_HEAD, and don't touch the sequencer state.
2889          * This means it is possible to cherry-pick in the middle
2890          * of a cherry-pick sequence.
2891          */
2892         if (opts->revs->cmdline.nr == 1 &&
2893             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2894             opts->revs->no_walk &&
2895             !opts->revs->cmdline.rev->flags) {
2896                 struct commit *cmit;
2897                 if (prepare_revision_walk(opts->revs))
2898                         return error(_("revision walk setup failed"));
2899                 cmit = get_revision(opts->revs);
2900                 if (!cmit || get_revision(opts->revs))
2901                         return error("BUG: expected exactly one commit from walk");
2902                 return single_pick(cmit, opts);
2903         }
2904
2905         /*
2906          * Start a new cherry-pick/ revert sequence; but
2907          * first, make sure that an existing one isn't in
2908          * progress
2909          */
2910
2911         if (walk_revs_populate_todo(&todo_list, opts) ||
2912                         create_seq_dir() < 0)
2913                 return -1;
2914         if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
2915                 return error(_("can't revert as initial commit"));
2916         if (save_head(oid_to_hex(&oid)))
2917                 return -1;
2918         if (save_opts(opts))
2919                 return -1;
2920         update_abort_safety_file();
2921         res = pick_commits(&todo_list, opts);
2922         todo_list_release(&todo_list);
2923         return res;
2924 }
2925
2926 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2927 {
2928         unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2929         struct strbuf sob = STRBUF_INIT;
2930         int has_footer;
2931
2932         strbuf_addstr(&sob, sign_off_header);
2933         strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2934                                 getenv("GIT_COMMITTER_EMAIL")));
2935         strbuf_addch(&sob, '\n');
2936
2937         if (!ignore_footer)
2938                 strbuf_complete_line(msgbuf);
2939
2940         /*
2941          * If the whole message buffer is equal to the sob, pretend that we
2942          * found a conforming footer with a matching sob
2943          */
2944         if (msgbuf->len - ignore_footer == sob.len &&
2945             !strncmp(msgbuf->buf, sob.buf, sob.len))
2946                 has_footer = 3;
2947         else
2948                 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2949
2950         if (!has_footer) {
2951                 const char *append_newlines = NULL;
2952                 size_t len = msgbuf->len - ignore_footer;
2953
2954                 if (!len) {
2955                         /*
2956                          * The buffer is completely empty.  Leave foom for
2957                          * the title and body to be filled in by the user.
2958                          */
2959                         append_newlines = "\n\n";
2960                 } else if (len == 1) {
2961                         /*
2962                          * Buffer contains a single newline.  Add another
2963                          * so that we leave room for the title and body.
2964                          */
2965                         append_newlines = "\n";
2966                 } else if (msgbuf->buf[len - 2] != '\n') {
2967                         /*
2968                          * Buffer ends with a single newline.  Add another
2969                          * so that there is an empty line between the message
2970                          * body and the sob.
2971                          */
2972                         append_newlines = "\n";
2973                 } /* else, the buffer already ends with two newlines. */
2974
2975                 if (append_newlines)
2976                         strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2977                                 append_newlines, strlen(append_newlines));
2978         }
2979
2980         if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2981                 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2982                                 sob.buf, sob.len);
2983
2984         strbuf_release(&sob);
2985 }
2986
2987 int sequencer_make_script(FILE *out, int argc, const char **argv,
2988                           unsigned flags)
2989 {
2990         char *format = NULL;
2991         struct pretty_print_context pp = {0};
2992         struct strbuf buf = STRBUF_INIT;
2993         struct rev_info revs;
2994         struct commit *commit;
2995         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
2996         const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
2997
2998         init_revisions(&revs, NULL);
2999         revs.verbose_header = 1;
3000         revs.max_parents = 1;
3001         revs.cherry_mark = 1;
3002         revs.limited = 1;
3003         revs.reverse = 1;
3004         revs.right_only = 1;
3005         revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
3006         revs.topo_order = 1;
3007
3008         revs.pretty_given = 1;
3009         git_config_get_string("rebase.instructionFormat", &format);
3010         if (!format || !*format) {
3011                 free(format);
3012                 format = xstrdup("%s");
3013         }
3014         get_commit_format(format, &revs);
3015         free(format);
3016         pp.fmt = revs.commit_format;
3017         pp.output_encoding = get_log_output_encoding();
3018
3019         if (setup_revisions(argc, argv, &revs, NULL) > 1)
3020                 return error(_("make_script: unhandled options"));
3021
3022         if (prepare_revision_walk(&revs) < 0)
3023                 return error(_("make_script: error preparing revisions"));
3024
3025         while ((commit = get_revision(&revs))) {
3026                 int is_empty  = is_original_commit_empty(commit);
3027
3028                 if (!is_empty && (commit->object.flags & PATCHSAME))
3029                         continue;
3030                 strbuf_reset(&buf);
3031                 if (!keep_empty && is_empty)
3032                         strbuf_addf(&buf, "%c ", comment_line_char);
3033                 strbuf_addf(&buf, "%s %s ", insn,
3034                             oid_to_hex(&commit->object.oid));
3035                 pretty_print_commit(&pp, commit, &buf);
3036                 strbuf_addch(&buf, '\n');
3037                 fputs(buf.buf, out);
3038         }
3039         strbuf_release(&buf);
3040         return 0;
3041 }
3042
3043 /*
3044  * Add commands after pick and (series of) squash/fixup commands
3045  * in the todo list.
3046  */
3047 int sequencer_add_exec_commands(const char *commands)
3048 {
3049         const char *todo_file = rebase_path_todo();
3050         struct todo_list todo_list = TODO_LIST_INIT;
3051         struct todo_item *item;
3052         struct strbuf *buf = &todo_list.buf;
3053         size_t offset = 0, commands_len = strlen(commands);
3054         int i, first;
3055
3056         if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3057                 return error(_("could not read '%s'."), todo_file);
3058
3059         if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3060                 todo_list_release(&todo_list);
3061                 return error(_("unusable todo list: '%s'"), todo_file);
3062         }
3063
3064         first = 1;
3065         /* insert <commands> before every pick except the first one */
3066         for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3067                 if (item->command == TODO_PICK && !first) {
3068                         strbuf_insert(buf, item->offset_in_buf + offset,
3069                                       commands, commands_len);
3070                         offset += commands_len;
3071                 }
3072                 first = 0;
3073         }
3074
3075         /* append final <commands> */
3076         strbuf_add(buf, commands, commands_len);
3077
3078         i = write_message(buf->buf, buf->len, todo_file, 0);
3079         todo_list_release(&todo_list);
3080         return i;
3081 }
3082
3083 int transform_todos(unsigned flags)
3084 {
3085         const char *todo_file = rebase_path_todo();
3086         struct todo_list todo_list = TODO_LIST_INIT;
3087         struct strbuf buf = STRBUF_INIT;
3088         struct todo_item *item;
3089         int i;
3090
3091         if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3092                 return error(_("could not read '%s'."), todo_file);
3093
3094         if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3095                 todo_list_release(&todo_list);
3096                 return error(_("unusable todo list: '%s'"), todo_file);
3097         }
3098
3099         for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3100                 /* if the item is not a command write it and continue */
3101                 if (item->command >= TODO_COMMENT) {
3102                         strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
3103                         continue;
3104                 }
3105
3106                 /* add command to the buffer */
3107                 if (flags & TODO_LIST_ABBREVIATE_CMDS)
3108                         strbuf_addch(&buf, command_to_char(item->command));
3109                 else
3110                         strbuf_addstr(&buf, command_to_string(item->command));
3111
3112                 /* add commit id */
3113                 if (item->commit) {
3114                         const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
3115                                           short_commit_name(item->commit) :
3116                                           oid_to_hex(&item->commit->object.oid);
3117
3118                         strbuf_addf(&buf, " %s", oid);
3119                 }
3120                 /* add all the rest */
3121                 if (!item->arg_len)
3122                         strbuf_addch(&buf, '\n');
3123                 else
3124                         strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
3125         }
3126
3127         i = write_message(buf.buf, buf.len, todo_file, 0);
3128         todo_list_release(&todo_list);
3129         return i;
3130 }
3131
3132 enum check_level {
3133         CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
3134 };
3135
3136 static enum check_level get_missing_commit_check_level(void)
3137 {
3138         const char *value;
3139
3140         if (git_config_get_value("rebase.missingcommitscheck", &value) ||
3141                         !strcasecmp("ignore", value))
3142                 return CHECK_IGNORE;
3143         if (!strcasecmp("warn", value))
3144                 return CHECK_WARN;
3145         if (!strcasecmp("error", value))
3146                 return CHECK_ERROR;
3147         warning(_("unrecognized setting %s for option "
3148                   "rebase.missingCommitsCheck. Ignoring."), value);
3149         return CHECK_IGNORE;
3150 }
3151
3152 /*
3153  * Check if the user dropped some commits by mistake
3154  * Behaviour determined by rebase.missingCommitsCheck.
3155  * Check if there is an unrecognized command or a
3156  * bad SHA-1 in a command.
3157  */
3158 int check_todo_list(void)
3159 {
3160         enum check_level check_level = get_missing_commit_check_level();
3161         struct strbuf todo_file = STRBUF_INIT;
3162         struct todo_list todo_list = TODO_LIST_INIT;
3163         struct strbuf missing = STRBUF_INIT;
3164         int advise_to_edit_todo = 0, res = 0, fd, i;
3165
3166         strbuf_addstr(&todo_file, rebase_path_todo());
3167         fd = open(todo_file.buf, O_RDONLY);
3168         if (fd < 0) {
3169                 res = error_errno(_("could not open '%s'"), todo_file.buf);
3170                 goto leave_check;
3171         }
3172         if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3173                 close(fd);
3174                 res = error(_("could not read '%s'."), todo_file.buf);
3175                 goto leave_check;
3176         }
3177         close(fd);
3178         advise_to_edit_todo = res =
3179                 parse_insn_buffer(todo_list.buf.buf, &todo_list);
3180
3181         if (res || check_level == CHECK_IGNORE)
3182                 goto leave_check;
3183
3184         /* Mark the commits in git-rebase-todo as seen */
3185         for (i = 0; i < todo_list.nr; i++) {
3186                 struct commit *commit = todo_list.items[i].commit;
3187                 if (commit)
3188                         commit->util = (void *)1;
3189         }
3190
3191         todo_list_release(&todo_list);
3192         strbuf_addstr(&todo_file, ".backup");
3193         fd = open(todo_file.buf, O_RDONLY);
3194         if (fd < 0) {
3195                 res = error_errno(_("could not open '%s'"), todo_file.buf);
3196                 goto leave_check;
3197         }
3198         if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3199                 close(fd);
3200                 res = error(_("could not read '%s'."), todo_file.buf);
3201                 goto leave_check;
3202         }
3203         close(fd);
3204         strbuf_release(&todo_file);
3205         res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
3206
3207         /* Find commits in git-rebase-todo.backup yet unseen */
3208         for (i = todo_list.nr - 1; i >= 0; i--) {
3209                 struct todo_item *item = todo_list.items + i;
3210                 struct commit *commit = item->commit;
3211                 if (commit && !commit->util) {
3212                         strbuf_addf(&missing, " - %s %.*s\n",
3213                                     short_commit_name(commit),
3214                                     item->arg_len, item->arg);
3215                         commit->util = (void *)1;
3216                 }
3217         }
3218
3219         /* Warn about missing commits */
3220         if (!missing.len)
3221                 goto leave_check;
3222
3223         if (check_level == CHECK_ERROR)
3224                 advise_to_edit_todo = res = 1;
3225
3226         fprintf(stderr,
3227                 _("Warning: some commits may have been dropped accidentally.\n"
3228                 "Dropped commits (newer to older):\n"));
3229
3230         /* Make the list user-friendly and display */
3231         fputs(missing.buf, stderr);
3232         strbuf_release(&missing);
3233
3234         fprintf(stderr, _("To avoid this message, use \"drop\" to "
3235                 "explicitly remove a commit.\n\n"
3236                 "Use 'git config rebase.missingCommitsCheck' to change "
3237                 "the level of warnings.\n"
3238                 "The possible behaviours are: ignore, warn, error.\n\n"));
3239
3240 leave_check:
3241         strbuf_release(&todo_file);
3242         todo_list_release(&todo_list);
3243
3244         if (advise_to_edit_todo)
3245                 fprintf(stderr,
3246                         _("You can fix this with 'git rebase --edit-todo' "
3247                           "and then run 'git rebase --continue'.\n"
3248                           "Or you can abort the rebase with 'git rebase"
3249                           " --abort'.\n"));
3250
3251         return res;
3252 }
3253
3254 static int rewrite_file(const char *path, const char *buf, size_t len)
3255 {
3256         int rc = 0;
3257         int fd = open(path, O_WRONLY | O_TRUNC);
3258         if (fd < 0)
3259                 return error_errno(_("could not open '%s' for writing"), path);
3260         if (write_in_full(fd, buf, len) < 0)
3261                 rc = error_errno(_("could not write to '%s'"), path);
3262         if (close(fd) && !rc)
3263                 rc = error_errno(_("could not close '%s'"), path);
3264         return rc;
3265 }
3266
3267 /* skip picking commits whose parents are unchanged */
3268 int skip_unnecessary_picks(void)
3269 {
3270         const char *todo_file = rebase_path_todo();
3271         struct strbuf buf = STRBUF_INIT;
3272         struct todo_list todo_list = TODO_LIST_INIT;
3273         struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
3274         int fd, i;
3275
3276         if (!read_oneliner(&buf, rebase_path_onto(), 0))
3277                 return error(_("could not read 'onto'"));
3278         if (get_oid(buf.buf, &onto_oid)) {
3279                 strbuf_release(&buf);
3280                 return error(_("need a HEAD to fixup"));
3281         }
3282         strbuf_release(&buf);
3283
3284         fd = open(todo_file, O_RDONLY);
3285         if (fd < 0) {
3286                 return error_errno(_("could not open '%s'"), todo_file);
3287         }
3288         if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3289                 close(fd);
3290                 return error(_("could not read '%s'."), todo_file);
3291         }
3292         close(fd);
3293         if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3294                 todo_list_release(&todo_list);
3295                 return -1;
3296         }
3297
3298         for (i = 0; i < todo_list.nr; i++) {
3299                 struct todo_item *item = todo_list.items + i;
3300
3301                 if (item->command >= TODO_NOOP)
3302                         continue;
3303                 if (item->command != TODO_PICK)
3304                         break;
3305                 if (parse_commit(item->commit)) {
3306                         todo_list_release(&todo_list);
3307                         return error(_("could not parse commit '%s'"),
3308                                 oid_to_hex(&item->commit->object.oid));
3309                 }
3310                 if (!item->commit->parents)
3311                         break; /* root commit */
3312                 if (item->commit->parents->next)
3313                         break; /* merge commit */
3314                 parent_oid = &item->commit->parents->item->object.oid;
3315                 if (hashcmp(parent_oid->hash, oid->hash))
3316                         break;
3317                 oid = &item->commit->object.oid;
3318         }
3319         if (i > 0) {
3320                 int offset = i < todo_list.nr ?
3321                         todo_list.items[i].offset_in_buf : todo_list.buf.len;
3322                 const char *done_path = rebase_path_done();
3323
3324                 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
3325                 if (fd < 0) {
3326                         error_errno(_("could not open '%s' for writing"),
3327                                     done_path);
3328                         todo_list_release(&todo_list);
3329                         return -1;
3330                 }
3331                 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
3332                         error_errno(_("could not write to '%s'"), done_path);
3333                         todo_list_release(&todo_list);
3334                         close(fd);
3335                         return -1;
3336                 }
3337                 close(fd);
3338
3339                 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
3340                                  todo_list.buf.len - offset) < 0) {
3341                         todo_list_release(&todo_list);
3342                         return -1;
3343                 }
3344
3345                 todo_list.current = i;
3346                 if (is_fixup(peek_command(&todo_list, 0)))
3347                         record_in_rewritten(oid, peek_command(&todo_list, 0));
3348         }
3349
3350         todo_list_release(&todo_list);
3351         printf("%s\n", oid_to_hex(oid));
3352
3353         return 0;
3354 }
3355
3356 struct subject2item_entry {
3357         struct hashmap_entry entry;
3358         int i;
3359         char subject[FLEX_ARRAY];
3360 };
3361
3362 static int subject2item_cmp(const void *fndata,
3363                             const struct subject2item_entry *a,
3364                             const struct subject2item_entry *b, const void *key)
3365 {
3366         return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
3367 }
3368
3369 /*
3370  * Rearrange the todo list that has both "pick commit-id msg" and "pick
3371  * commit-id fixup!/squash! msg" in it so that the latter is put immediately
3372  * after the former, and change "pick" to "fixup"/"squash".
3373  *
3374  * Note that if the config has specified a custom instruction format, each log
3375  * message will have to be retrieved from the commit (as the oneline in the
3376  * script cannot be trusted) in order to normalize the autosquash arrangement.
3377  */
3378 int rearrange_squash(void)
3379 {
3380         const char *todo_file = rebase_path_todo();
3381         struct todo_list todo_list = TODO_LIST_INIT;
3382         struct hashmap subject2item;
3383         int res = 0, rearranged = 0, *next, *tail, fd, i;
3384         char **subjects;
3385
3386         fd = open(todo_file, O_RDONLY);
3387         if (fd < 0)
3388                 return error_errno(_("could not open '%s'"), todo_file);
3389         if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
3390                 close(fd);
3391                 return error(_("could not read '%s'."), todo_file);
3392         }
3393         close(fd);
3394         if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
3395                 todo_list_release(&todo_list);
3396                 return -1;
3397         }
3398
3399         /*
3400          * The hashmap maps onelines to the respective todo list index.
3401          *
3402          * If any items need to be rearranged, the next[i] value will indicate
3403          * which item was moved directly after the i'th.
3404          *
3405          * In that case, last[i] will indicate the index of the latest item to
3406          * be moved to appear after the i'th.
3407          */
3408         hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
3409                      NULL, todo_list.nr);
3410         ALLOC_ARRAY(next, todo_list.nr);
3411         ALLOC_ARRAY(tail, todo_list.nr);
3412         ALLOC_ARRAY(subjects, todo_list.nr);
3413         for (i = 0; i < todo_list.nr; i++) {
3414                 struct strbuf buf = STRBUF_INIT;
3415                 struct todo_item *item = todo_list.items + i;
3416                 const char *commit_buffer, *subject, *p;
3417                 size_t subject_len;
3418                 int i2 = -1;
3419                 struct subject2item_entry *entry;
3420
3421                 next[i] = tail[i] = -1;
3422                 if (item->command >= TODO_EXEC) {
3423                         subjects[i] = NULL;
3424                         continue;
3425                 }
3426
3427                 if (is_fixup(item->command)) {
3428                         todo_list_release(&todo_list);
3429                         return error(_("the script was already rearranged."));
3430                 }
3431
3432                 item->commit->util = item;
3433
3434                 parse_commit(item->commit);
3435                 commit_buffer = get_commit_buffer(item->commit, NULL);
3436                 find_commit_subject(commit_buffer, &subject);
3437                 format_subject(&buf, subject, " ");
3438                 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
3439                 unuse_commit_buffer(item->commit, commit_buffer);
3440                 if ((skip_prefix(subject, "fixup! ", &p) ||
3441                      skip_prefix(subject, "squash! ", &p))) {
3442                         struct commit *commit2;
3443
3444                         for (;;) {
3445                                 while (isspace(*p))
3446                                         p++;
3447                                 if (!skip_prefix(p, "fixup! ", &p) &&
3448                                     !skip_prefix(p, "squash! ", &p))
3449                                         break;
3450                         }
3451
3452                         if ((entry = hashmap_get_from_hash(&subject2item,
3453                                                            strhash(p), p)))
3454                                 /* found by title */
3455                                 i2 = entry->i;
3456                         else if (!strchr(p, ' ') &&
3457                                  (commit2 =
3458                                   lookup_commit_reference_by_name(p)) &&
3459                                  commit2->util)
3460                                 /* found by commit name */
3461                                 i2 = (struct todo_item *)commit2->util
3462                                         - todo_list.items;
3463                         else {
3464                                 /* copy can be a prefix of the commit subject */
3465                                 for (i2 = 0; i2 < i; i2++)
3466                                         if (subjects[i2] &&
3467                                             starts_with(subjects[i2], p))
3468                                                 break;
3469                                 if (i2 == i)
3470                                         i2 = -1;
3471                         }
3472                 }
3473                 if (i2 >= 0) {
3474                         rearranged = 1;
3475                         todo_list.items[i].command =
3476                                 starts_with(subject, "fixup!") ?
3477                                 TODO_FIXUP : TODO_SQUASH;
3478                         if (next[i2] < 0)
3479                                 next[i2] = i;
3480                         else
3481                                 next[tail[i2]] = i;
3482                         tail[i2] = i;
3483                 } else if (!hashmap_get_from_hash(&subject2item,
3484                                                 strhash(subject), subject)) {
3485                         FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
3486                         entry->i = i;
3487                         hashmap_entry_init(entry, strhash(entry->subject));
3488                         hashmap_put(&subject2item, entry);
3489                 }
3490         }
3491
3492         if (rearranged) {
3493                 struct strbuf buf = STRBUF_INIT;
3494
3495                 for (i = 0; i < todo_list.nr; i++) {
3496                         enum todo_command command = todo_list.items[i].command;
3497                         int cur = i;
3498
3499                         /*
3500                          * Initially, all commands are 'pick's. If it is a
3501                          * fixup or a squash now, we have rearranged it.
3502                          */
3503                         if (is_fixup(command))
3504                                 continue;
3505
3506                         while (cur >= 0) {
3507                                 int offset = todo_list.items[cur].offset_in_buf;
3508                                 int end_offset = cur + 1 < todo_list.nr ?
3509                                         todo_list.items[cur + 1].offset_in_buf :
3510                                         todo_list.buf.len;
3511                                 char *bol = todo_list.buf.buf + offset;
3512                                 char *eol = todo_list.buf.buf + end_offset;
3513
3514                                 /* replace 'pick', by 'fixup' or 'squash' */
3515                                 command = todo_list.items[cur].command;
3516                                 if (is_fixup(command)) {
3517                                         strbuf_addstr(&buf,
3518                                                 todo_command_info[command].str);
3519                                         bol += strcspn(bol, " \t");
3520                                 }
3521
3522                                 strbuf_add(&buf, bol, eol - bol);
3523
3524                                 cur = next[cur];
3525                         }
3526                 }
3527
3528                 res = rewrite_file(todo_file, buf.buf, buf.len);
3529                 strbuf_release(&buf);
3530         }
3531
3532         free(next);
3533         free(tail);
3534         for (i = 0; i < todo_list.nr; i++)
3535                 free(subjects[i]);
3536         free(subjects);
3537         hashmap_free(&subject2item, 1);
3538         todo_list_release(&todo_list);
3539
3540         return res;
3541 }