aa31191d9aa0544f1da56029136bf6886bc4f604
1#include "cache.h"
2#include "lockfile.h"
3#include "sequencer.h"
4#include "dir.h"
5#include "object.h"
6#include "commit.h"
7#include "tag.h"
8#include "run-command.h"
9#include "exec_cmd.h"
10#include "utf8.h"
11#include "cache-tree.h"
12#include "diff.h"
13#include "revision.h"
14#include "rerere.h"
15#include "merge-recursive.h"
16#include "refs.h"
17#include "argv-array.h"
18#include "quote.h"
19#include "trailer.h"
20#include "log-tree.h"
21#include "wt-status.h"
22
23#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
24
25const char sign_off_header[] = "Signed-off-by: ";
26static const char cherry_picked_prefix[] = "(cherry picked from commit ";
27
28GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
29
30static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
31static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
32static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
33static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
34
35static GIT_PATH_FUNC(rebase_path, "rebase-merge")
36/*
37 * The file containing rebase commands, comments, and empty lines.
38 * This file is created by "git rebase -i" then edited by the user. As
39 * the lines are processed, they are removed from the front of this
40 * file and written to the tail of 'done'.
41 */
42static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
43/*
44 * The rebase command lines that have already been processed. A line
45 * is moved here when it is first handled, before any associated user
46 * actions.
47 */
48static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
49/*
50 * The commit message that is planned to be used for any changes that
51 * need to be committed following a user interaction.
52 */
53static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
54/*
55 * The file into which is accumulated the suggested commit message for
56 * squash/fixup commands. When the first of a series of squash/fixups
57 * is seen, the file is created and the commit message from the
58 * previous commit and from the first squash/fixup commit are written
59 * to it. The commit message for each subsequent squash/fixup commit
60 * is appended to the file as it is processed.
61 *
62 * The first line of the file is of the form
63 * # This is a combination of $count commits.
64 * where $count is the number of commits whose messages have been
65 * written to the file so far (including the initial "pick" commit).
66 * Each time that a commit message is processed, this line is read and
67 * updated. It is deleted just before the combined commit is made.
68 */
69static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
70/*
71 * If the current series of squash/fixups has not yet included a squash
72 * command, then this file exists and holds the commit message of the
73 * original "pick" commit. (If the series ends without a "squash"
74 * command, then this can be used as the commit message of the combined
75 * commit without opening the editor.)
76 */
77static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
78/*
79 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
80 * GIT_AUTHOR_DATE that will be used for the commit that is currently
81 * being rebased.
82 */
83static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
84/*
85 * When an "edit" rebase command is being processed, the SHA1 of the
86 * commit to be edited is recorded in this file. When "git rebase
87 * --continue" is executed, if there are any staged changes then they
88 * will be amended to the HEAD commit, but only provided the HEAD
89 * commit is still the commit to be edited. When any other rebase
90 * command is processed, this file is deleted.
91 */
92static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
93/*
94 * When we stop at a given patch via the "edit" command, this file contains
95 * the abbreviated commit name of the corresponding patch.
96 */
97static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
98/*
99 * For the post-rewrite hook, we make a list of rewritten commits and
100 * their new sha1s. The rewritten-pending list keeps the sha1s of
101 * commits that have been processed, but not committed yet,
102 * e.g. because they are waiting for a 'squash' command.
103 */
104static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
105static GIT_PATH_FUNC(rebase_path_rewritten_pending,
106 "rebase-merge/rewritten-pending")
107/*
108 * The following files are written by git-rebase just after parsing the
109 * command-line (and are only consumed, not modified, by the sequencer).
110 */
111static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
112static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
113static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
114static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
115static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
116static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
117static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
118static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
119
120static inline int is_rebase_i(const struct replay_opts *opts)
121{
122 return opts->action == REPLAY_INTERACTIVE_REBASE;
123}
124
125static const char *get_dir(const struct replay_opts *opts)
126{
127 if (is_rebase_i(opts))
128 return rebase_path();
129 return git_path_seq_dir();
130}
131
132static const char *get_todo_path(const struct replay_opts *opts)
133{
134 if (is_rebase_i(opts))
135 return rebase_path_todo();
136 return git_path_todo_file();
137}
138
139/*
140 * Returns 0 for non-conforming footer
141 * Returns 1 for conforming footer
142 * Returns 2 when sob exists within conforming footer
143 * Returns 3 when sob exists within conforming footer as last entry
144 */
145static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
146 int ignore_footer)
147{
148 struct trailer_info info;
149 int i;
150 int found_sob = 0, found_sob_last = 0;
151
152 trailer_info_get(&info, sb->buf);
153
154 if (info.trailer_start == info.trailer_end)
155 return 0;
156
157 for (i = 0; i < info.trailer_nr; i++)
158 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
159 found_sob = 1;
160 if (i == info.trailer_nr - 1)
161 found_sob_last = 1;
162 }
163
164 trailer_info_release(&info);
165
166 if (found_sob_last)
167 return 3;
168 if (found_sob)
169 return 2;
170 return 1;
171}
172
173static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
174{
175 static struct strbuf buf = STRBUF_INIT;
176
177 strbuf_reset(&buf);
178 if (opts->gpg_sign)
179 sq_quotef(&buf, "-S%s", opts->gpg_sign);
180 return buf.buf;
181}
182
183int sequencer_remove_state(struct replay_opts *opts)
184{
185 struct strbuf dir = STRBUF_INIT;
186 int i;
187
188 free(opts->gpg_sign);
189 free(opts->strategy);
190 for (i = 0; i < opts->xopts_nr; i++)
191 free(opts->xopts[i]);
192 free(opts->xopts);
193
194 strbuf_addf(&dir, "%s", get_dir(opts));
195 remove_dir_recursively(&dir, 0);
196 strbuf_release(&dir);
197
198 return 0;
199}
200
201static const char *action_name(const struct replay_opts *opts)
202{
203 switch (opts->action) {
204 case REPLAY_REVERT:
205 return N_("revert");
206 case REPLAY_PICK:
207 return N_("cherry-pick");
208 case REPLAY_INTERACTIVE_REBASE:
209 return N_("rebase -i");
210 }
211 die(_("Unknown action: %d"), opts->action);
212}
213
214struct commit_message {
215 char *parent_label;
216 char *label;
217 char *subject;
218 const char *message;
219};
220
221static const char *short_commit_name(struct commit *commit)
222{
223 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
224}
225
226static int get_message(struct commit *commit, struct commit_message *out)
227{
228 const char *abbrev, *subject;
229 int subject_len;
230
231 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
232 abbrev = short_commit_name(commit);
233
234 subject_len = find_commit_subject(out->message, &subject);
235
236 out->subject = xmemdupz(subject, subject_len);
237 out->label = xstrfmt("%s... %s", abbrev, out->subject);
238 out->parent_label = xstrfmt("parent of %s", out->label);
239
240 return 0;
241}
242
243static void free_message(struct commit *commit, struct commit_message *msg)
244{
245 free(msg->parent_label);
246 free(msg->label);
247 free(msg->subject);
248 unuse_commit_buffer(commit, msg->message);
249}
250
251static void print_advice(int show_hint, struct replay_opts *opts)
252{
253 char *msg = getenv("GIT_CHERRY_PICK_HELP");
254
255 if (msg) {
256 fprintf(stderr, "%s\n", msg);
257 /*
258 * A conflict has occurred but the porcelain
259 * (typically rebase --interactive) wants to take care
260 * of the commit itself so remove CHERRY_PICK_HEAD
261 */
262 unlink(git_path_cherry_pick_head());
263 return;
264 }
265
266 if (show_hint) {
267 if (opts->no_commit)
268 advise(_("after resolving the conflicts, mark the corrected paths\n"
269 "with 'git add <paths>' or 'git rm <paths>'"));
270 else
271 advise(_("after resolving the conflicts, mark the corrected paths\n"
272 "with 'git add <paths>' or 'git rm <paths>'\n"
273 "and commit the result with 'git commit'"));
274 }
275}
276
277static int write_message(const void *buf, size_t len, const char *filename,
278 int append_eol)
279{
280 static struct lock_file msg_file;
281
282 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
283 if (msg_fd < 0)
284 return error_errno(_("could not lock '%s'"), filename);
285 if (write_in_full(msg_fd, buf, len) < 0) {
286 rollback_lock_file(&msg_file);
287 return error_errno(_("could not write to '%s'"), filename);
288 }
289 if (append_eol && write(msg_fd, "\n", 1) < 0) {
290 rollback_lock_file(&msg_file);
291 return error_errno(_("could not write eol to '%s'"), filename);
292 }
293 if (commit_lock_file(&msg_file) < 0) {
294 rollback_lock_file(&msg_file);
295 return error(_("failed to finalize '%s'."), filename);
296 }
297
298 return 0;
299}
300
301/*
302 * Reads a file that was presumably written by a shell script, i.e. with an
303 * end-of-line marker that needs to be stripped.
304 *
305 * Note that only the last end-of-line marker is stripped, consistent with the
306 * behavior of "$(cat path)" in a shell script.
307 *
308 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
309 */
310static int read_oneliner(struct strbuf *buf,
311 const char *path, int skip_if_empty)
312{
313 int orig_len = buf->len;
314
315 if (!file_exists(path))
316 return 0;
317
318 if (strbuf_read_file(buf, path, 0) < 0) {
319 warning_errno(_("could not read '%s'"), path);
320 return 0;
321 }
322
323 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
324 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
325 --buf->len;
326 buf->buf[buf->len] = '\0';
327 }
328
329 if (skip_if_empty && buf->len == orig_len)
330 return 0;
331
332 return 1;
333}
334
335static struct tree *empty_tree(void)
336{
337 return lookup_tree(EMPTY_TREE_SHA1_BIN);
338}
339
340static int error_dirty_index(struct replay_opts *opts)
341{
342 if (read_cache_unmerged())
343 return error_resolve_conflict(_(action_name(opts)));
344
345 error(_("your local changes would be overwritten by %s."),
346 _(action_name(opts)));
347
348 if (advice_commit_before_merge)
349 advise(_("commit your changes or stash them to proceed."));
350 return -1;
351}
352
353static void update_abort_safety_file(void)
354{
355 struct object_id head;
356
357 /* Do nothing on a single-pick */
358 if (!file_exists(git_path_seq_dir()))
359 return;
360
361 if (!get_oid("HEAD", &head))
362 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
363 else
364 write_file(git_path_abort_safety_file(), "%s", "");
365}
366
367static int fast_forward_to(const unsigned char *to, const unsigned char *from,
368 int unborn, struct replay_opts *opts)
369{
370 struct ref_transaction *transaction;
371 struct strbuf sb = STRBUF_INIT;
372 struct strbuf err = STRBUF_INIT;
373
374 read_cache();
375 if (checkout_fast_forward(from, to, 1))
376 return -1; /* the callee should have complained already */
377
378 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
379
380 transaction = ref_transaction_begin(&err);
381 if (!transaction ||
382 ref_transaction_update(transaction, "HEAD",
383 to, unborn ? null_sha1 : from,
384 0, sb.buf, &err) ||
385 ref_transaction_commit(transaction, &err)) {
386 ref_transaction_free(transaction);
387 error("%s", err.buf);
388 strbuf_release(&sb);
389 strbuf_release(&err);
390 return -1;
391 }
392
393 strbuf_release(&sb);
394 strbuf_release(&err);
395 ref_transaction_free(transaction);
396 update_abort_safety_file();
397 return 0;
398}
399
400void append_conflicts_hint(struct strbuf *msgbuf)
401{
402 int i;
403
404 strbuf_addch(msgbuf, '\n');
405 strbuf_commented_addf(msgbuf, "Conflicts:\n");
406 for (i = 0; i < active_nr;) {
407 const struct cache_entry *ce = active_cache[i++];
408 if (ce_stage(ce)) {
409 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
410 while (i < active_nr && !strcmp(ce->name,
411 active_cache[i]->name))
412 i++;
413 }
414 }
415}
416
417static int do_recursive_merge(struct commit *base, struct commit *next,
418 const char *base_label, const char *next_label,
419 unsigned char *head, struct strbuf *msgbuf,
420 struct replay_opts *opts)
421{
422 struct merge_options o;
423 struct tree *result, *next_tree, *base_tree, *head_tree;
424 int clean;
425 char **xopt;
426 static struct lock_file index_lock;
427
428 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
429
430 read_cache();
431
432 init_merge_options(&o);
433 o.ancestor = base ? base_label : "(empty tree)";
434 o.branch1 = "HEAD";
435 o.branch2 = next ? next_label : "(empty tree)";
436 if (is_rebase_i(opts))
437 o.buffer_output = 2;
438
439 head_tree = parse_tree_indirect(head);
440 next_tree = next ? next->tree : empty_tree();
441 base_tree = base ? base->tree : empty_tree();
442
443 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
444 parse_merge_opt(&o, *xopt);
445
446 clean = merge_trees(&o,
447 head_tree,
448 next_tree, base_tree, &result);
449 if (is_rebase_i(opts) && clean <= 0)
450 fputs(o.obuf.buf, stdout);
451 strbuf_release(&o.obuf);
452 if (clean < 0)
453 return clean;
454
455 if (active_cache_changed &&
456 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
457 /* TRANSLATORS: %s will be "revert", "cherry-pick" or
458 * "rebase -i".
459 */
460 return error(_("%s: Unable to write new index file"),
461 _(action_name(opts)));
462 rollback_lock_file(&index_lock);
463
464 if (opts->signoff)
465 append_signoff(msgbuf, 0, 0);
466
467 if (!clean)
468 append_conflicts_hint(msgbuf);
469
470 return !clean;
471}
472
473static int is_index_unchanged(void)
474{
475 unsigned char head_sha1[20];
476 struct commit *head_commit;
477
478 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
479 return error(_("could not resolve HEAD commit\n"));
480
481 head_commit = lookup_commit(head_sha1);
482
483 /*
484 * If head_commit is NULL, check_commit, called from
485 * lookup_commit, would have indicated that head_commit is not
486 * a commit object already. parse_commit() will return failure
487 * without further complaints in such a case. Otherwise, if
488 * the commit is invalid, parse_commit() will complain. So
489 * there is nothing for us to say here. Just return failure.
490 */
491 if (parse_commit(head_commit))
492 return -1;
493
494 if (!active_cache_tree)
495 active_cache_tree = cache_tree();
496
497 if (!cache_tree_fully_valid(active_cache_tree))
498 if (cache_tree_update(&the_index, 0))
499 return error(_("unable to update cache tree\n"));
500
501 return !hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash);
502}
503
504static int write_author_script(const char *message)
505{
506 struct strbuf buf = STRBUF_INIT;
507 const char *eol;
508 int res;
509
510 for (;;)
511 if (!*message || starts_with(message, "\n")) {
512missing_author:
513 /* Missing 'author' line? */
514 unlink(rebase_path_author_script());
515 return 0;
516 } else if (skip_prefix(message, "author ", &message))
517 break;
518 else if ((eol = strchr(message, '\n')))
519 message = eol + 1;
520 else
521 goto missing_author;
522
523 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
524 while (*message && *message != '\n' && *message != '\r')
525 if (skip_prefix(message, " <", &message))
526 break;
527 else if (*message != '\'')
528 strbuf_addch(&buf, *(message++));
529 else
530 strbuf_addf(&buf, "'\\\\%c'", *(message++));
531 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
532 while (*message && *message != '\n' && *message != '\r')
533 if (skip_prefix(message, "> ", &message))
534 break;
535 else if (*message != '\'')
536 strbuf_addch(&buf, *(message++));
537 else
538 strbuf_addf(&buf, "'\\\\%c'", *(message++));
539 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
540 while (*message && *message != '\n' && *message != '\r')
541 if (*message != '\'')
542 strbuf_addch(&buf, *(message++));
543 else
544 strbuf_addf(&buf, "'\\\\%c'", *(message++));
545 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
546 strbuf_release(&buf);
547 return res;
548}
549
550/*
551 * Read a list of environment variable assignments (such as the author-script
552 * file) into an environment block. Returns -1 on error, 0 otherwise.
553 */
554static int read_env_script(struct argv_array *env)
555{
556 struct strbuf script = STRBUF_INIT;
557 int i, count = 0;
558 char *p, *p2;
559
560 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
561 return -1;
562
563 for (p = script.buf; *p; p++)
564 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
565 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
566 else if (*p == '\'')
567 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
568 else if (*p == '\n') {
569 *p = '\0';
570 count++;
571 }
572
573 for (i = 0, p = script.buf; i < count; i++) {
574 argv_array_push(env, p);
575 p += strlen(p) + 1;
576 }
577
578 return 0;
579}
580
581static const char staged_changes_advice[] =
582N_("you have staged changes in your working tree\n"
583"If these changes are meant to be squashed into the previous commit, run:\n"
584"\n"
585" git commit --amend %s\n"
586"\n"
587"If they are meant to go into a new commit, run:\n"
588"\n"
589" git commit %s\n"
590"\n"
591"In both cases, once you're done, continue with:\n"
592"\n"
593" git rebase --continue\n");
594
595/*
596 * If we are cherry-pick, and if the merge did not result in
597 * hand-editing, we will hit this commit and inherit the original
598 * author date and name.
599 *
600 * If we are revert, or if our cherry-pick results in a hand merge,
601 * we had better say that the current user is responsible for that.
602 *
603 * An exception is when run_git_commit() is called during an
604 * interactive rebase: in that case, we will want to retain the
605 * author metadata.
606 */
607static int run_git_commit(const char *defmsg, struct replay_opts *opts,
608 int allow_empty, int edit, int amend,
609 int cleanup_commit_message)
610{
611 struct child_process cmd = CHILD_PROCESS_INIT;
612 const char *value;
613
614 cmd.git_cmd = 1;
615
616 if (is_rebase_i(opts)) {
617 if (!edit) {
618 cmd.stdout_to_stderr = 1;
619 cmd.err = -1;
620 }
621
622 if (read_env_script(&cmd.env_array)) {
623 const char *gpg_opt = gpg_sign_opt_quoted(opts);
624
625 return error(_(staged_changes_advice),
626 gpg_opt, gpg_opt);
627 }
628 }
629
630 argv_array_push(&cmd.args, "commit");
631 argv_array_push(&cmd.args, "-n");
632
633 if (amend)
634 argv_array_push(&cmd.args, "--amend");
635 if (opts->gpg_sign)
636 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
637 if (opts->signoff)
638 argv_array_push(&cmd.args, "-s");
639 if (defmsg)
640 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
641 if (cleanup_commit_message)
642 argv_array_push(&cmd.args, "--cleanup=strip");
643 if (edit)
644 argv_array_push(&cmd.args, "-e");
645 else if (!cleanup_commit_message &&
646 !opts->signoff && !opts->record_origin &&
647 git_config_get_value("commit.cleanup", &value))
648 argv_array_push(&cmd.args, "--cleanup=verbatim");
649
650 if (allow_empty)
651 argv_array_push(&cmd.args, "--allow-empty");
652
653 if (opts->allow_empty_message)
654 argv_array_push(&cmd.args, "--allow-empty-message");
655
656 if (cmd.err == -1) {
657 /* hide stderr on success */
658 struct strbuf buf = STRBUF_INIT;
659 int rc = pipe_command(&cmd,
660 NULL, 0,
661 /* stdout is already redirected */
662 NULL, 0,
663 &buf, 0);
664 if (rc)
665 fputs(buf.buf, stderr);
666 strbuf_release(&buf);
667 return rc;
668 }
669
670 return run_command(&cmd);
671}
672
673static int is_original_commit_empty(struct commit *commit)
674{
675 const unsigned char *ptree_sha1;
676
677 if (parse_commit(commit))
678 return error(_("could not parse commit %s\n"),
679 oid_to_hex(&commit->object.oid));
680 if (commit->parents) {
681 struct commit *parent = commit->parents->item;
682 if (parse_commit(parent))
683 return error(_("could not parse parent commit %s\n"),
684 oid_to_hex(&parent->object.oid));
685 ptree_sha1 = parent->tree->object.oid.hash;
686 } else {
687 ptree_sha1 = EMPTY_TREE_SHA1_BIN; /* commit is root */
688 }
689
690 return !hashcmp(ptree_sha1, commit->tree->object.oid.hash);
691}
692
693/*
694 * Do we run "git commit" with "--allow-empty"?
695 */
696static int allow_empty(struct replay_opts *opts, struct commit *commit)
697{
698 int index_unchanged, empty_commit;
699
700 /*
701 * Three cases:
702 *
703 * (1) we do not allow empty at all and error out.
704 *
705 * (2) we allow ones that were initially empty, but
706 * forbid the ones that become empty;
707 *
708 * (3) we allow both.
709 */
710 if (!opts->allow_empty)
711 return 0; /* let "git commit" barf as necessary */
712
713 index_unchanged = is_index_unchanged();
714 if (index_unchanged < 0)
715 return index_unchanged;
716 if (!index_unchanged)
717 return 0; /* we do not have to say --allow-empty */
718
719 if (opts->keep_redundant_commits)
720 return 1;
721
722 empty_commit = is_original_commit_empty(commit);
723 if (empty_commit < 0)
724 return empty_commit;
725 if (!empty_commit)
726 return 0;
727 else
728 return 1;
729}
730
731/*
732 * Note that ordering matters in this enum. Not only must it match the mapping
733 * below, it is also divided into several sections that matter. When adding
734 * new commands, make sure you add it in the right section.
735 */
736enum todo_command {
737 /* commands that handle commits */
738 TODO_PICK = 0,
739 TODO_REVERT,
740 TODO_EDIT,
741 TODO_REWORD,
742 TODO_FIXUP,
743 TODO_SQUASH,
744 /* commands that do something else than handling a single commit */
745 TODO_EXEC,
746 /* commands that do nothing but are counted for reporting progress */
747 TODO_NOOP,
748 TODO_DROP,
749 /* comments (not counted for reporting progress) */
750 TODO_COMMENT
751};
752
753static struct {
754 char c;
755 const char *str;
756} todo_command_info[] = {
757 { 'p', "pick" },
758 { 0, "revert" },
759 { 'e', "edit" },
760 { 'r', "reword" },
761 { 'f', "fixup" },
762 { 's', "squash" },
763 { 'x', "exec" },
764 { 0, "noop" },
765 { 'd', "drop" },
766 { 0, NULL }
767};
768
769static const char *command_to_string(const enum todo_command command)
770{
771 if (command < TODO_COMMENT)
772 return todo_command_info[command].str;
773 die("Unknown command: %d", command);
774}
775
776static int is_noop(const enum todo_command command)
777{
778 return TODO_NOOP <= command;
779}
780
781static int is_fixup(enum todo_command command)
782{
783 return command == TODO_FIXUP || command == TODO_SQUASH;
784}
785
786static int update_squash_messages(enum todo_command command,
787 struct commit *commit, struct replay_opts *opts)
788{
789 struct strbuf buf = STRBUF_INIT;
790 int count, res;
791 const char *message, *body;
792
793 if (file_exists(rebase_path_squash_msg())) {
794 struct strbuf header = STRBUF_INIT;
795 char *eol, *p;
796
797 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
798 return error(_("could not read '%s'"),
799 rebase_path_squash_msg());
800
801 p = buf.buf + 1;
802 eol = strchrnul(buf.buf, '\n');
803 if (buf.buf[0] != comment_line_char ||
804 (p += strcspn(p, "0123456789\n")) == eol)
805 return error(_("unexpected 1st line of squash message:"
806 "\n\n\t%.*s"),
807 (int)(eol - buf.buf), buf.buf);
808 count = strtol(p, NULL, 10);
809
810 if (count < 1)
811 return error(_("invalid 1st line of squash message:\n"
812 "\n\t%.*s"),
813 (int)(eol - buf.buf), buf.buf);
814
815 strbuf_addf(&header, "%c ", comment_line_char);
816 strbuf_addf(&header,
817 _("This is a combination of %d commits."), ++count);
818 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
819 strbuf_release(&header);
820 } else {
821 unsigned char head[20];
822 struct commit *head_commit;
823 const char *head_message, *body;
824
825 if (get_sha1("HEAD", head))
826 return error(_("need a HEAD to fixup"));
827 if (!(head_commit = lookup_commit_reference(head)))
828 return error(_("could not read HEAD"));
829 if (!(head_message = get_commit_buffer(head_commit, NULL)))
830 return error(_("could not read HEAD's commit message"));
831
832 find_commit_subject(head_message, &body);
833 if (write_message(body, strlen(body),
834 rebase_path_fixup_msg(), 0)) {
835 unuse_commit_buffer(head_commit, head_message);
836 return error(_("cannot write '%s'"),
837 rebase_path_fixup_msg());
838 }
839
840 count = 2;
841 strbuf_addf(&buf, "%c ", comment_line_char);
842 strbuf_addf(&buf, _("This is a combination of %d commits."),
843 count);
844 strbuf_addf(&buf, "\n%c ", comment_line_char);
845 strbuf_addstr(&buf, _("This is the 1st commit message:"));
846 strbuf_addstr(&buf, "\n\n");
847 strbuf_addstr(&buf, body);
848
849 unuse_commit_buffer(head_commit, head_message);
850 }
851
852 if (!(message = get_commit_buffer(commit, NULL)))
853 return error(_("could not read commit message of %s"),
854 oid_to_hex(&commit->object.oid));
855 find_commit_subject(message, &body);
856
857 if (command == TODO_SQUASH) {
858 unlink(rebase_path_fixup_msg());
859 strbuf_addf(&buf, "\n%c ", comment_line_char);
860 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
861 strbuf_addstr(&buf, "\n\n");
862 strbuf_addstr(&buf, body);
863 } else if (command == TODO_FIXUP) {
864 strbuf_addf(&buf, "\n%c ", comment_line_char);
865 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
866 count);
867 strbuf_addstr(&buf, "\n\n");
868 strbuf_add_commented_lines(&buf, body, strlen(body));
869 } else
870 return error(_("unknown command: %d"), command);
871 unuse_commit_buffer(commit, message);
872
873 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
874 strbuf_release(&buf);
875 return res;
876}
877
878static void flush_rewritten_pending(void) {
879 struct strbuf buf = STRBUF_INIT;
880 unsigned char newsha1[20];
881 FILE *out;
882
883 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), 82) > 0 &&
884 !get_sha1("HEAD", newsha1) &&
885 (out = fopen(rebase_path_rewritten_list(), "a"))) {
886 char *bol = buf.buf, *eol;
887
888 while (*bol) {
889 eol = strchrnul(bol, '\n');
890 fprintf(out, "%.*s %s\n", (int)(eol - bol),
891 bol, sha1_to_hex(newsha1));
892 if (!*eol)
893 break;
894 bol = eol + 1;
895 }
896 fclose(out);
897 unlink(rebase_path_rewritten_pending());
898 }
899 strbuf_release(&buf);
900}
901
902static void record_in_rewritten(struct object_id *oid,
903 enum todo_command next_command) {
904 FILE *out = fopen(rebase_path_rewritten_pending(), "a");
905
906 if (!out)
907 return;
908
909 fprintf(out, "%s\n", oid_to_hex(oid));
910 fclose(out);
911
912 if (!is_fixup(next_command))
913 flush_rewritten_pending();
914}
915
916static int do_pick_commit(enum todo_command command, struct commit *commit,
917 struct replay_opts *opts, int final_fixup)
918{
919 int edit = opts->edit, cleanup_commit_message = 0;
920 const char *msg_file = edit ? NULL : git_path_merge_msg();
921 unsigned char head[20];
922 struct commit *base, *next, *parent;
923 const char *base_label, *next_label;
924 struct commit_message msg = { NULL, NULL, NULL, NULL };
925 struct strbuf msgbuf = STRBUF_INIT;
926 int res, unborn = 0, amend = 0, allow = 0;
927
928 if (opts->no_commit) {
929 /*
930 * We do not intend to commit immediately. We just want to
931 * merge the differences in, so let's compute the tree
932 * that represents the "current" state for merge-recursive
933 * to work on.
934 */
935 if (write_cache_as_tree(head, 0, NULL))
936 return error(_("your index file is unmerged."));
937 } else {
938 unborn = get_sha1("HEAD", head);
939 if (unborn)
940 hashcpy(head, EMPTY_TREE_SHA1_BIN);
941 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD", 0, 0))
942 return error_dirty_index(opts);
943 }
944 discard_cache();
945
946 if (!commit->parents)
947 parent = NULL;
948 else if (commit->parents->next) {
949 /* Reverting or cherry-picking a merge commit */
950 int cnt;
951 struct commit_list *p;
952
953 if (!opts->mainline)
954 return error(_("commit %s is a merge but no -m option was given."),
955 oid_to_hex(&commit->object.oid));
956
957 for (cnt = 1, p = commit->parents;
958 cnt != opts->mainline && p;
959 cnt++)
960 p = p->next;
961 if (cnt != opts->mainline || !p)
962 return error(_("commit %s does not have parent %d"),
963 oid_to_hex(&commit->object.oid), opts->mainline);
964 parent = p->item;
965 } else if (0 < opts->mainline)
966 return error(_("mainline was specified but commit %s is not a merge."),
967 oid_to_hex(&commit->object.oid));
968 else
969 parent = commit->parents->item;
970
971 if (get_message(commit, &msg) != 0)
972 return error(_("cannot get commit message for %s"),
973 oid_to_hex(&commit->object.oid));
974
975 if (opts->allow_ff && !is_fixup(command) &&
976 ((parent && !hashcmp(parent->object.oid.hash, head)) ||
977 (!parent && unborn))) {
978 if (is_rebase_i(opts))
979 write_author_script(msg.message);
980 res = fast_forward_to(commit->object.oid.hash, head, unborn,
981 opts);
982 if (res || command != TODO_REWORD)
983 goto leave;
984 edit = amend = 1;
985 msg_file = NULL;
986 goto fast_forward_edit;
987 }
988 if (parent && parse_commit(parent) < 0)
989 /* TRANSLATORS: The first %s will be a "todo" command like
990 "revert" or "pick", the second %s a SHA1. */
991 return error(_("%s: cannot parse parent commit %s"),
992 command_to_string(command),
993 oid_to_hex(&parent->object.oid));
994
995 /*
996 * "commit" is an existing commit. We would want to apply
997 * the difference it introduces since its first parent "prev"
998 * on top of the current HEAD if we are cherry-pick. Or the
999 * reverse of it if we are revert.
1000 */
1001
1002 if (command == TODO_REVERT) {
1003 base = commit;
1004 base_label = msg.label;
1005 next = parent;
1006 next_label = msg.parent_label;
1007 strbuf_addstr(&msgbuf, "Revert \"");
1008 strbuf_addstr(&msgbuf, msg.subject);
1009 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1010 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1011
1012 if (commit->parents && commit->parents->next) {
1013 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1014 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1015 }
1016 strbuf_addstr(&msgbuf, ".\n");
1017 } else {
1018 const char *p;
1019
1020 base = parent;
1021 base_label = msg.parent_label;
1022 next = commit;
1023 next_label = msg.label;
1024
1025 /* Append the commit log message to msgbuf. */
1026 if (find_commit_subject(msg.message, &p))
1027 strbuf_addstr(&msgbuf, p);
1028
1029 if (opts->record_origin) {
1030 if (!has_conforming_footer(&msgbuf, NULL, 0))
1031 strbuf_addch(&msgbuf, '\n');
1032 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1033 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1034 strbuf_addstr(&msgbuf, ")\n");
1035 }
1036 }
1037
1038 if (command == TODO_REWORD)
1039 edit = 1;
1040 else if (is_fixup(command)) {
1041 if (update_squash_messages(command, commit, opts))
1042 return -1;
1043 amend = 1;
1044 if (!final_fixup)
1045 msg_file = rebase_path_squash_msg();
1046 else if (file_exists(rebase_path_fixup_msg())) {
1047 cleanup_commit_message = 1;
1048 msg_file = rebase_path_fixup_msg();
1049 } else {
1050 const char *dest = git_path("SQUASH_MSG");
1051 unlink(dest);
1052 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1053 return error(_("could not rename '%s' to '%s'"),
1054 rebase_path_squash_msg(), dest);
1055 unlink(git_path("MERGE_MSG"));
1056 msg_file = dest;
1057 edit = 1;
1058 }
1059 }
1060
1061 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1062 res = -1;
1063 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1064 res = do_recursive_merge(base, next, base_label, next_label,
1065 head, &msgbuf, opts);
1066 if (res < 0)
1067 return res;
1068 res |= write_message(msgbuf.buf, msgbuf.len,
1069 git_path_merge_msg(), 0);
1070 } else {
1071 struct commit_list *common = NULL;
1072 struct commit_list *remotes = NULL;
1073
1074 res = write_message(msgbuf.buf, msgbuf.len,
1075 git_path_merge_msg(), 0);
1076
1077 commit_list_insert(base, &common);
1078 commit_list_insert(next, &remotes);
1079 res |= try_merge_command(opts->strategy,
1080 opts->xopts_nr, (const char **)opts->xopts,
1081 common, sha1_to_hex(head), remotes);
1082 free_commit_list(common);
1083 free_commit_list(remotes);
1084 }
1085 strbuf_release(&msgbuf);
1086
1087 /*
1088 * If the merge was clean or if it failed due to conflict, we write
1089 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1090 * However, if the merge did not even start, then we don't want to
1091 * write it at all.
1092 */
1093 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1094 update_ref(NULL, "CHERRY_PICK_HEAD", commit->object.oid.hash, NULL,
1095 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1096 res = -1;
1097 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1098 update_ref(NULL, "REVERT_HEAD", commit->object.oid.hash, NULL,
1099 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR))
1100 res = -1;
1101
1102 if (res) {
1103 error(command == TODO_REVERT
1104 ? _("could not revert %s... %s")
1105 : _("could not apply %s... %s"),
1106 short_commit_name(commit), msg.subject);
1107 print_advice(res == 1, opts);
1108 rerere(opts->allow_rerere_auto);
1109 goto leave;
1110 }
1111
1112 allow = allow_empty(opts, commit);
1113 if (allow < 0) {
1114 res = allow;
1115 goto leave;
1116 }
1117 if (!opts->no_commit)
1118fast_forward_edit:
1119 res = run_git_commit(msg_file, opts, allow, edit, amend,
1120 cleanup_commit_message);
1121
1122 if (!res && final_fixup) {
1123 unlink(rebase_path_fixup_msg());
1124 unlink(rebase_path_squash_msg());
1125 }
1126
1127leave:
1128 free_message(commit, &msg);
1129 update_abort_safety_file();
1130
1131 return res;
1132}
1133
1134static int prepare_revs(struct replay_opts *opts)
1135{
1136 /*
1137 * picking (but not reverting) ranges (but not individual revisions)
1138 * should be done in reverse
1139 */
1140 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1141 opts->revs->reverse ^= 1;
1142
1143 if (prepare_revision_walk(opts->revs))
1144 return error(_("revision walk setup failed"));
1145
1146 if (!opts->revs->commits)
1147 return error(_("empty commit set passed"));
1148 return 0;
1149}
1150
1151static int read_and_refresh_cache(struct replay_opts *opts)
1152{
1153 static struct lock_file index_lock;
1154 int index_fd = hold_locked_index(&index_lock, 0);
1155 if (read_index_preload(&the_index, NULL) < 0) {
1156 rollback_lock_file(&index_lock);
1157 return error(_("git %s: failed to read the index"),
1158 _(action_name(opts)));
1159 }
1160 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1161 if (the_index.cache_changed && index_fd >= 0) {
1162 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1163 rollback_lock_file(&index_lock);
1164 return error(_("git %s: failed to refresh the index"),
1165 _(action_name(opts)));
1166 }
1167 }
1168 rollback_lock_file(&index_lock);
1169 return 0;
1170}
1171
1172struct todo_item {
1173 enum todo_command command;
1174 struct commit *commit;
1175 const char *arg;
1176 int arg_len;
1177 size_t offset_in_buf;
1178};
1179
1180struct todo_list {
1181 struct strbuf buf;
1182 struct todo_item *items;
1183 int nr, alloc, current;
1184 int done_nr, total_nr;
1185};
1186
1187#define TODO_LIST_INIT { STRBUF_INIT }
1188
1189static void todo_list_release(struct todo_list *todo_list)
1190{
1191 strbuf_release(&todo_list->buf);
1192 free(todo_list->items);
1193 todo_list->items = NULL;
1194 todo_list->nr = todo_list->alloc = 0;
1195}
1196
1197static struct todo_item *append_new_todo(struct todo_list *todo_list)
1198{
1199 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1200 return todo_list->items + todo_list->nr++;
1201}
1202
1203static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1204{
1205 unsigned char commit_sha1[20];
1206 char *end_of_object_name;
1207 int i, saved, status, padding;
1208
1209 /* left-trim */
1210 bol += strspn(bol, " \t");
1211
1212 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1213 item->command = TODO_COMMENT;
1214 item->commit = NULL;
1215 item->arg = bol;
1216 item->arg_len = eol - bol;
1217 return 0;
1218 }
1219
1220 for (i = 0; i < TODO_COMMENT; i++)
1221 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1222 item->command = i;
1223 break;
1224 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1225 bol++;
1226 item->command = i;
1227 break;
1228 }
1229 if (i >= TODO_COMMENT)
1230 return -1;
1231
1232 if (item->command == TODO_NOOP) {
1233 item->commit = NULL;
1234 item->arg = bol;
1235 item->arg_len = eol - bol;
1236 return 0;
1237 }
1238
1239 /* Eat up extra spaces/ tabs before object name */
1240 padding = strspn(bol, " \t");
1241 if (!padding)
1242 return -1;
1243 bol += padding;
1244
1245 if (item->command == TODO_EXEC) {
1246 item->arg = bol;
1247 item->arg_len = (int)(eol - bol);
1248 return 0;
1249 }
1250
1251 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1252 saved = *end_of_object_name;
1253 *end_of_object_name = '\0';
1254 status = get_sha1(bol, commit_sha1);
1255 *end_of_object_name = saved;
1256
1257 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1258 item->arg_len = (int)(eol - item->arg);
1259
1260 if (status < 0)
1261 return -1;
1262
1263 item->commit = lookup_commit_reference(commit_sha1);
1264 return !item->commit;
1265}
1266
1267static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1268{
1269 struct todo_item *item;
1270 char *p = buf, *next_p;
1271 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1272
1273 for (i = 1; *p; i++, p = next_p) {
1274 char *eol = strchrnul(p, '\n');
1275
1276 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1277
1278 if (p != eol && eol[-1] == '\r')
1279 eol--; /* strip Carriage Return */
1280
1281 item = append_new_todo(todo_list);
1282 item->offset_in_buf = p - todo_list->buf.buf;
1283 if (parse_insn_line(item, p, eol)) {
1284 res = error(_("invalid line %d: %.*s"),
1285 i, (int)(eol - p), p);
1286 item->command = TODO_NOOP;
1287 }
1288
1289 if (fixup_okay)
1290 ; /* do nothing */
1291 else if (is_fixup(item->command))
1292 return error(_("cannot '%s' without a previous commit"),
1293 command_to_string(item->command));
1294 else if (!is_noop(item->command))
1295 fixup_okay = 1;
1296 }
1297
1298 return res;
1299}
1300
1301static int count_commands(struct todo_list *todo_list)
1302{
1303 int count = 0, i;
1304
1305 for (i = 0; i < todo_list->nr; i++)
1306 if (todo_list->items[i].command != TODO_COMMENT)
1307 count++;
1308
1309 return count;
1310}
1311
1312static int read_populate_todo(struct todo_list *todo_list,
1313 struct replay_opts *opts)
1314{
1315 const char *todo_file = get_todo_path(opts);
1316 int fd, res;
1317
1318 strbuf_reset(&todo_list->buf);
1319 fd = open(todo_file, O_RDONLY);
1320 if (fd < 0)
1321 return error_errno(_("could not open '%s'"), todo_file);
1322 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1323 close(fd);
1324 return error(_("could not read '%s'."), todo_file);
1325 }
1326 close(fd);
1327
1328 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1329 if (res) {
1330 if (is_rebase_i(opts))
1331 return error(_("please fix this using "
1332 "'git rebase --edit-todo'."));
1333 return error(_("unusable instruction sheet: '%s'"), todo_file);
1334 }
1335
1336 if (!todo_list->nr &&
1337 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1338 return error(_("no commits parsed."));
1339
1340 if (!is_rebase_i(opts)) {
1341 enum todo_command valid =
1342 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1343 int i;
1344
1345 for (i = 0; i < todo_list->nr; i++)
1346 if (valid == todo_list->items[i].command)
1347 continue;
1348 else if (valid == TODO_PICK)
1349 return error(_("cannot cherry-pick during a revert."));
1350 else
1351 return error(_("cannot revert during a cherry-pick."));
1352 }
1353
1354 if (is_rebase_i(opts)) {
1355 struct todo_list done = TODO_LIST_INIT;
1356
1357 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1358 !parse_insn_buffer(done.buf.buf, &done))
1359 todo_list->done_nr = count_commands(&done);
1360 else
1361 todo_list->done_nr = 0;
1362
1363 todo_list->total_nr = todo_list->done_nr
1364 + count_commands(todo_list);
1365
1366 todo_list_release(&done);
1367 }
1368
1369 return 0;
1370}
1371
1372static int git_config_string_dup(char **dest,
1373 const char *var, const char *value)
1374{
1375 if (!value)
1376 return config_error_nonbool(var);
1377 free(*dest);
1378 *dest = xstrdup(value);
1379 return 0;
1380}
1381
1382static int populate_opts_cb(const char *key, const char *value, void *data)
1383{
1384 struct replay_opts *opts = data;
1385 int error_flag = 1;
1386
1387 if (!value)
1388 error_flag = 0;
1389 else if (!strcmp(key, "options.no-commit"))
1390 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1391 else if (!strcmp(key, "options.edit"))
1392 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1393 else if (!strcmp(key, "options.signoff"))
1394 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1395 else if (!strcmp(key, "options.record-origin"))
1396 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1397 else if (!strcmp(key, "options.allow-ff"))
1398 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1399 else if (!strcmp(key, "options.mainline"))
1400 opts->mainline = git_config_int(key, value);
1401 else if (!strcmp(key, "options.strategy"))
1402 git_config_string_dup(&opts->strategy, key, value);
1403 else if (!strcmp(key, "options.gpg-sign"))
1404 git_config_string_dup(&opts->gpg_sign, key, value);
1405 else if (!strcmp(key, "options.strategy-option")) {
1406 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1407 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1408 } else
1409 return error(_("invalid key: %s"), key);
1410
1411 if (!error_flag)
1412 return error(_("invalid value for %s: %s"), key, value);
1413
1414 return 0;
1415}
1416
1417static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1418{
1419 int i;
1420
1421 strbuf_reset(buf);
1422 if (!read_oneliner(buf, rebase_path_strategy(), 0))
1423 return;
1424 opts->strategy = strbuf_detach(buf, NULL);
1425 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
1426 return;
1427
1428 opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
1429 for (i = 0; i < opts->xopts_nr; i++) {
1430 const char *arg = opts->xopts[i];
1431
1432 skip_prefix(arg, "--", &arg);
1433 opts->xopts[i] = xstrdup(arg);
1434 }
1435}
1436
1437static int read_populate_opts(struct replay_opts *opts)
1438{
1439 if (is_rebase_i(opts)) {
1440 struct strbuf buf = STRBUF_INIT;
1441
1442 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1443 if (!starts_with(buf.buf, "-S"))
1444 strbuf_reset(&buf);
1445 else {
1446 free(opts->gpg_sign);
1447 opts->gpg_sign = xstrdup(buf.buf + 2);
1448 }
1449 }
1450
1451 if (file_exists(rebase_path_verbose()))
1452 opts->verbose = 1;
1453
1454 read_strategy_opts(opts, &buf);
1455 strbuf_release(&buf);
1456
1457 return 0;
1458 }
1459
1460 if (!file_exists(git_path_opts_file()))
1461 return 0;
1462 /*
1463 * The function git_parse_source(), called from git_config_from_file(),
1464 * may die() in case of a syntactically incorrect file. We do not care
1465 * about this case, though, because we wrote that file ourselves, so we
1466 * are pretty certain that it is syntactically correct.
1467 */
1468 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1469 return error(_("malformed options sheet: '%s'"),
1470 git_path_opts_file());
1471 return 0;
1472}
1473
1474static int walk_revs_populate_todo(struct todo_list *todo_list,
1475 struct replay_opts *opts)
1476{
1477 enum todo_command command = opts->action == REPLAY_PICK ?
1478 TODO_PICK : TODO_REVERT;
1479 const char *command_string = todo_command_info[command].str;
1480 struct commit *commit;
1481
1482 if (prepare_revs(opts))
1483 return -1;
1484
1485 while ((commit = get_revision(opts->revs))) {
1486 struct todo_item *item = append_new_todo(todo_list);
1487 const char *commit_buffer = get_commit_buffer(commit, NULL);
1488 const char *subject;
1489 int subject_len;
1490
1491 item->command = command;
1492 item->commit = commit;
1493 item->arg = NULL;
1494 item->arg_len = 0;
1495 item->offset_in_buf = todo_list->buf.len;
1496 subject_len = find_commit_subject(commit_buffer, &subject);
1497 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1498 short_commit_name(commit), subject_len, subject);
1499 unuse_commit_buffer(commit, commit_buffer);
1500 }
1501 return 0;
1502}
1503
1504static int create_seq_dir(void)
1505{
1506 if (file_exists(git_path_seq_dir())) {
1507 error(_("a cherry-pick or revert is already in progress"));
1508 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1509 return -1;
1510 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1511 return error_errno(_("could not create sequencer directory '%s'"),
1512 git_path_seq_dir());
1513 return 0;
1514}
1515
1516static int save_head(const char *head)
1517{
1518 static struct lock_file head_lock;
1519 struct strbuf buf = STRBUF_INIT;
1520 int fd;
1521
1522 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1523 if (fd < 0) {
1524 rollback_lock_file(&head_lock);
1525 return error_errno(_("could not lock HEAD"));
1526 }
1527 strbuf_addf(&buf, "%s\n", head);
1528 if (write_in_full(fd, buf.buf, buf.len) < 0) {
1529 rollback_lock_file(&head_lock);
1530 return error_errno(_("could not write to '%s'"),
1531 git_path_head_file());
1532 }
1533 if (commit_lock_file(&head_lock) < 0) {
1534 rollback_lock_file(&head_lock);
1535 return error(_("failed to finalize '%s'."), git_path_head_file());
1536 }
1537 return 0;
1538}
1539
1540static int rollback_is_safe(void)
1541{
1542 struct strbuf sb = STRBUF_INIT;
1543 struct object_id expected_head, actual_head;
1544
1545 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1546 strbuf_trim(&sb);
1547 if (get_oid_hex(sb.buf, &expected_head)) {
1548 strbuf_release(&sb);
1549 die(_("could not parse %s"), git_path_abort_safety_file());
1550 }
1551 strbuf_release(&sb);
1552 }
1553 else if (errno == ENOENT)
1554 oidclr(&expected_head);
1555 else
1556 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1557
1558 if (get_oid("HEAD", &actual_head))
1559 oidclr(&actual_head);
1560
1561 return !oidcmp(&actual_head, &expected_head);
1562}
1563
1564static int reset_for_rollback(const unsigned char *sha1)
1565{
1566 const char *argv[4]; /* reset --merge <arg> + NULL */
1567
1568 argv[0] = "reset";
1569 argv[1] = "--merge";
1570 argv[2] = sha1_to_hex(sha1);
1571 argv[3] = NULL;
1572 return run_command_v_opt(argv, RUN_GIT_CMD);
1573}
1574
1575static int rollback_single_pick(void)
1576{
1577 unsigned char head_sha1[20];
1578
1579 if (!file_exists(git_path_cherry_pick_head()) &&
1580 !file_exists(git_path_revert_head()))
1581 return error(_("no cherry-pick or revert in progress"));
1582 if (read_ref_full("HEAD", 0, head_sha1, NULL))
1583 return error(_("cannot resolve HEAD"));
1584 if (is_null_sha1(head_sha1))
1585 return error(_("cannot abort from a branch yet to be born"));
1586 return reset_for_rollback(head_sha1);
1587}
1588
1589int sequencer_rollback(struct replay_opts *opts)
1590{
1591 FILE *f;
1592 unsigned char sha1[20];
1593 struct strbuf buf = STRBUF_INIT;
1594
1595 f = fopen(git_path_head_file(), "r");
1596 if (!f && errno == ENOENT) {
1597 /*
1598 * There is no multiple-cherry-pick in progress.
1599 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1600 * a single-cherry-pick in progress, abort that.
1601 */
1602 return rollback_single_pick();
1603 }
1604 if (!f)
1605 return error_errno(_("cannot open '%s'"), git_path_head_file());
1606 if (strbuf_getline_lf(&buf, f)) {
1607 error(_("cannot read '%s': %s"), git_path_head_file(),
1608 ferror(f) ? strerror(errno) : _("unexpected end of file"));
1609 fclose(f);
1610 goto fail;
1611 }
1612 fclose(f);
1613 if (get_sha1_hex(buf.buf, sha1) || buf.buf[40] != '\0') {
1614 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1615 git_path_head_file());
1616 goto fail;
1617 }
1618 if (is_null_sha1(sha1)) {
1619 error(_("cannot abort from a branch yet to be born"));
1620 goto fail;
1621 }
1622
1623 if (!rollback_is_safe()) {
1624 /* Do not error, just do not rollback */
1625 warning(_("You seem to have moved HEAD. "
1626 "Not rewinding, check your HEAD!"));
1627 } else
1628 if (reset_for_rollback(sha1))
1629 goto fail;
1630 strbuf_release(&buf);
1631 return sequencer_remove_state(opts);
1632fail:
1633 strbuf_release(&buf);
1634 return -1;
1635}
1636
1637static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1638{
1639 static struct lock_file todo_lock;
1640 const char *todo_path = get_todo_path(opts);
1641 int next = todo_list->current, offset, fd;
1642
1643 /*
1644 * rebase -i writes "git-rebase-todo" without the currently executing
1645 * command, appending it to "done" instead.
1646 */
1647 if (is_rebase_i(opts))
1648 next++;
1649
1650 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1651 if (fd < 0)
1652 return error_errno(_("could not lock '%s'"), todo_path);
1653 offset = next < todo_list->nr ?
1654 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1655 if (write_in_full(fd, todo_list->buf.buf + offset,
1656 todo_list->buf.len - offset) < 0)
1657 return error_errno(_("could not write to '%s'"), todo_path);
1658 if (commit_lock_file(&todo_lock) < 0)
1659 return error(_("failed to finalize '%s'."), todo_path);
1660
1661 if (is_rebase_i(opts)) {
1662 const char *done_path = rebase_path_done();
1663 int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
1664 int prev_offset = !next ? 0 :
1665 todo_list->items[next - 1].offset_in_buf;
1666
1667 if (fd >= 0 && offset > prev_offset &&
1668 write_in_full(fd, todo_list->buf.buf + prev_offset,
1669 offset - prev_offset) < 0) {
1670 close(fd);
1671 return error_errno(_("could not write to '%s'"),
1672 done_path);
1673 }
1674 if (fd >= 0)
1675 close(fd);
1676 }
1677 return 0;
1678}
1679
1680static int save_opts(struct replay_opts *opts)
1681{
1682 const char *opts_file = git_path_opts_file();
1683 int res = 0;
1684
1685 if (opts->no_commit)
1686 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1687 if (opts->edit)
1688 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1689 if (opts->signoff)
1690 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1691 if (opts->record_origin)
1692 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1693 if (opts->allow_ff)
1694 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1695 if (opts->mainline) {
1696 struct strbuf buf = STRBUF_INIT;
1697 strbuf_addf(&buf, "%d", opts->mainline);
1698 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1699 strbuf_release(&buf);
1700 }
1701 if (opts->strategy)
1702 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1703 if (opts->gpg_sign)
1704 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1705 if (opts->xopts) {
1706 int i;
1707 for (i = 0; i < opts->xopts_nr; i++)
1708 res |= git_config_set_multivar_in_file_gently(opts_file,
1709 "options.strategy-option",
1710 opts->xopts[i], "^$", 0);
1711 }
1712 return res;
1713}
1714
1715static int make_patch(struct commit *commit, struct replay_opts *opts)
1716{
1717 struct strbuf buf = STRBUF_INIT;
1718 struct rev_info log_tree_opt;
1719 const char *subject, *p;
1720 int res = 0;
1721
1722 p = short_commit_name(commit);
1723 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
1724 return -1;
1725
1726 strbuf_addf(&buf, "%s/patch", get_dir(opts));
1727 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1728 init_revisions(&log_tree_opt, NULL);
1729 log_tree_opt.abbrev = 0;
1730 log_tree_opt.diff = 1;
1731 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
1732 log_tree_opt.disable_stdin = 1;
1733 log_tree_opt.no_commit_id = 1;
1734 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
1735 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
1736 if (!log_tree_opt.diffopt.file)
1737 res |= error_errno(_("could not open '%s'"), buf.buf);
1738 else {
1739 res |= log_tree_commit(&log_tree_opt, commit);
1740 fclose(log_tree_opt.diffopt.file);
1741 }
1742 strbuf_reset(&buf);
1743
1744 strbuf_addf(&buf, "%s/message", get_dir(opts));
1745 if (!file_exists(buf.buf)) {
1746 const char *commit_buffer = get_commit_buffer(commit, NULL);
1747 find_commit_subject(commit_buffer, &subject);
1748 res |= write_message(subject, strlen(subject), buf.buf, 1);
1749 unuse_commit_buffer(commit, commit_buffer);
1750 }
1751 strbuf_release(&buf);
1752
1753 return res;
1754}
1755
1756static int intend_to_amend(void)
1757{
1758 unsigned char head[20];
1759 char *p;
1760
1761 if (get_sha1("HEAD", head))
1762 return error(_("cannot read HEAD"));
1763
1764 p = sha1_to_hex(head);
1765 return write_message(p, strlen(p), rebase_path_amend(), 1);
1766}
1767
1768static int error_with_patch(struct commit *commit,
1769 const char *subject, int subject_len,
1770 struct replay_opts *opts, int exit_code, int to_amend)
1771{
1772 if (make_patch(commit, opts))
1773 return -1;
1774
1775 if (to_amend) {
1776 if (intend_to_amend())
1777 return -1;
1778
1779 fprintf(stderr, "You can amend the commit now, with\n"
1780 "\n"
1781 " git commit --amend %s\n"
1782 "\n"
1783 "Once you are satisfied with your changes, run\n"
1784 "\n"
1785 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
1786 } else if (exit_code)
1787 fprintf(stderr, "Could not apply %s... %.*s\n",
1788 short_commit_name(commit), subject_len, subject);
1789
1790 return exit_code;
1791}
1792
1793static int error_failed_squash(struct commit *commit,
1794 struct replay_opts *opts, int subject_len, const char *subject)
1795{
1796 if (rename(rebase_path_squash_msg(), rebase_path_message()))
1797 return error(_("could not rename '%s' to '%s'"),
1798 rebase_path_squash_msg(), rebase_path_message());
1799 unlink(rebase_path_fixup_msg());
1800 unlink(git_path("MERGE_MSG"));
1801 if (copy_file(git_path("MERGE_MSG"), rebase_path_message(), 0666))
1802 return error(_("could not copy '%s' to '%s'"),
1803 rebase_path_message(), git_path("MERGE_MSG"));
1804 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
1805}
1806
1807static int do_exec(const char *command_line)
1808{
1809 const char *child_argv[] = { NULL, NULL };
1810 int dirty, status;
1811
1812 fprintf(stderr, "Executing: %s\n", command_line);
1813 child_argv[0] = command_line;
1814 status = run_command_v_opt(child_argv, RUN_USING_SHELL);
1815
1816 /* force re-reading of the cache */
1817 if (discard_cache() < 0 || read_cache() < 0)
1818 return error(_("could not read index"));
1819
1820 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
1821
1822 if (status) {
1823 warning(_("execution failed: %s\n%s"
1824 "You can fix the problem, and then run\n"
1825 "\n"
1826 " git rebase --continue\n"
1827 "\n"),
1828 command_line,
1829 dirty ? N_("and made changes to the index and/or the "
1830 "working tree\n") : "");
1831 if (status == 127)
1832 /* command not found */
1833 status = 1;
1834 } else if (dirty) {
1835 warning(_("execution succeeded: %s\nbut "
1836 "left changes to the index and/or the working tree\n"
1837 "Commit or stash your changes, and then run\n"
1838 "\n"
1839 " git rebase --continue\n"
1840 "\n"), command_line);
1841 status = 1;
1842 }
1843
1844 return status;
1845}
1846
1847static int is_final_fixup(struct todo_list *todo_list)
1848{
1849 int i = todo_list->current;
1850
1851 if (!is_fixup(todo_list->items[i].command))
1852 return 0;
1853
1854 while (++i < todo_list->nr)
1855 if (is_fixup(todo_list->items[i].command))
1856 return 0;
1857 else if (!is_noop(todo_list->items[i].command))
1858 break;
1859 return 1;
1860}
1861
1862static enum todo_command peek_command(struct todo_list *todo_list, int offset)
1863{
1864 int i;
1865
1866 for (i = todo_list->current + offset; i < todo_list->nr; i++)
1867 if (!is_noop(todo_list->items[i].command))
1868 return todo_list->items[i].command;
1869
1870 return -1;
1871}
1872
1873static int apply_autostash(struct replay_opts *opts)
1874{
1875 struct strbuf stash_sha1 = STRBUF_INIT;
1876 struct child_process child = CHILD_PROCESS_INIT;
1877 int ret = 0;
1878
1879 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
1880 strbuf_release(&stash_sha1);
1881 return 0;
1882 }
1883 strbuf_trim(&stash_sha1);
1884
1885 child.git_cmd = 1;
1886 argv_array_push(&child.args, "stash");
1887 argv_array_push(&child.args, "apply");
1888 argv_array_push(&child.args, stash_sha1.buf);
1889 if (!run_command(&child))
1890 printf(_("Applied autostash."));
1891 else {
1892 struct child_process store = CHILD_PROCESS_INIT;
1893
1894 store.git_cmd = 1;
1895 argv_array_push(&store.args, "stash");
1896 argv_array_push(&store.args, "store");
1897 argv_array_push(&store.args, "-m");
1898 argv_array_push(&store.args, "autostash");
1899 argv_array_push(&store.args, "-q");
1900 argv_array_push(&store.args, stash_sha1.buf);
1901 if (run_command(&store))
1902 ret = error(_("cannot store %s"), stash_sha1.buf);
1903 else
1904 printf(_("Applying autostash resulted in conflicts.\n"
1905 "Your changes are safe in the stash.\n"
1906 "You can run \"git stash pop\" or"
1907 " \"git stash drop\" at any time.\n"));
1908 }
1909
1910 strbuf_release(&stash_sha1);
1911 return ret;
1912}
1913
1914static const char *reflog_message(struct replay_opts *opts,
1915 const char *sub_action, const char *fmt, ...)
1916{
1917 va_list ap;
1918 static struct strbuf buf = STRBUF_INIT;
1919
1920 va_start(ap, fmt);
1921 strbuf_reset(&buf);
1922 strbuf_addstr(&buf, action_name(opts));
1923 if (sub_action)
1924 strbuf_addf(&buf, " (%s)", sub_action);
1925 if (fmt) {
1926 strbuf_addstr(&buf, ": ");
1927 strbuf_vaddf(&buf, fmt, ap);
1928 }
1929 va_end(ap);
1930
1931 return buf.buf;
1932}
1933
1934static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
1935{
1936 int res = 0;
1937
1938 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1939 if (opts->allow_ff)
1940 assert(!(opts->signoff || opts->no_commit ||
1941 opts->record_origin || opts->edit));
1942 if (read_and_refresh_cache(opts))
1943 return -1;
1944
1945 while (todo_list->current < todo_list->nr) {
1946 struct todo_item *item = todo_list->items + todo_list->current;
1947 if (save_todo(todo_list, opts))
1948 return -1;
1949 if (is_rebase_i(opts)) {
1950 if (item->command != TODO_COMMENT)
1951 fprintf(stderr, "Rebasing (%d/%d)%s",
1952 ++(todo_list->done_nr),
1953 todo_list->total_nr,
1954 opts->verbose ? "\n" : "\r");
1955 unlink(rebase_path_message());
1956 unlink(rebase_path_author_script());
1957 unlink(rebase_path_stopped_sha());
1958 unlink(rebase_path_amend());
1959 }
1960 if (item->command <= TODO_SQUASH) {
1961 if (is_rebase_i(opts))
1962 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
1963 command_to_string(item->command), NULL),
1964 1);
1965 res = do_pick_commit(item->command, item->commit,
1966 opts, is_final_fixup(todo_list));
1967 if (is_rebase_i(opts) && res < 0) {
1968 /* Reschedule */
1969 todo_list->current--;
1970 if (save_todo(todo_list, opts))
1971 return -1;
1972 }
1973 if (item->command == TODO_EDIT) {
1974 struct commit *commit = item->commit;
1975 if (!res)
1976 warning(_("stopped at %s... %.*s"),
1977 short_commit_name(commit),
1978 item->arg_len, item->arg);
1979 return error_with_patch(commit,
1980 item->arg, item->arg_len, opts, res,
1981 !res);
1982 }
1983 if (is_rebase_i(opts) && !res)
1984 record_in_rewritten(&item->commit->object.oid,
1985 peek_command(todo_list, 1));
1986 if (res && is_fixup(item->command)) {
1987 if (res == 1)
1988 intend_to_amend();
1989 return error_failed_squash(item->commit, opts,
1990 item->arg_len, item->arg);
1991 } else if (res && is_rebase_i(opts))
1992 return res | error_with_patch(item->commit,
1993 item->arg, item->arg_len, opts, res,
1994 item->command == TODO_REWORD);
1995 } else if (item->command == TODO_EXEC) {
1996 char *end_of_arg = (char *)(item->arg + item->arg_len);
1997 int saved = *end_of_arg;
1998
1999 *end_of_arg = '\0';
2000 res = do_exec(item->arg);
2001 *end_of_arg = saved;
2002 } else if (!is_noop(item->command))
2003 return error(_("unknown command %d"), item->command);
2004
2005 todo_list->current++;
2006 if (res)
2007 return res;
2008 }
2009
2010 if (is_rebase_i(opts)) {
2011 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2012 struct stat st;
2013
2014 /* Stopped in the middle, as planned? */
2015 if (todo_list->current < todo_list->nr)
2016 return 0;
2017
2018 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2019 starts_with(head_ref.buf, "refs/")) {
2020 const char *msg;
2021 unsigned char head[20], orig[20];
2022 int res;
2023
2024 if (get_sha1("HEAD", head)) {
2025 res = error(_("cannot read HEAD"));
2026cleanup_head_ref:
2027 strbuf_release(&head_ref);
2028 strbuf_release(&buf);
2029 return res;
2030 }
2031 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2032 get_sha1_hex(buf.buf, orig)) {
2033 res = error(_("could not read orig-head"));
2034 goto cleanup_head_ref;
2035 }
2036 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2037 res = error(_("could not read 'onto'"));
2038 goto cleanup_head_ref;
2039 }
2040 msg = reflog_message(opts, "finish", "%s onto %s",
2041 head_ref.buf, buf.buf);
2042 if (update_ref(msg, head_ref.buf, head, orig,
2043 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR)) {
2044 res = error(_("could not update %s"),
2045 head_ref.buf);
2046 goto cleanup_head_ref;
2047 }
2048 msg = reflog_message(opts, "finish", "returning to %s",
2049 head_ref.buf);
2050 if (create_symref("HEAD", head_ref.buf, msg)) {
2051 res = error(_("could not update HEAD to %s"),
2052 head_ref.buf);
2053 goto cleanup_head_ref;
2054 }
2055 strbuf_reset(&buf);
2056 }
2057
2058 if (opts->verbose) {
2059 struct rev_info log_tree_opt;
2060 struct object_id orig, head;
2061
2062 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2063 init_revisions(&log_tree_opt, NULL);
2064 log_tree_opt.diff = 1;
2065 log_tree_opt.diffopt.output_format =
2066 DIFF_FORMAT_DIFFSTAT;
2067 log_tree_opt.disable_stdin = 1;
2068
2069 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2070 !get_sha1(buf.buf, orig.hash) &&
2071 !get_sha1("HEAD", head.hash)) {
2072 diff_tree_sha1(orig.hash, head.hash,
2073 "", &log_tree_opt.diffopt);
2074 log_tree_diff_flush(&log_tree_opt);
2075 }
2076 }
2077 flush_rewritten_pending();
2078 if (!stat(rebase_path_rewritten_list(), &st) &&
2079 st.st_size > 0) {
2080 struct child_process child = CHILD_PROCESS_INIT;
2081 const char *post_rewrite_hook =
2082 find_hook("post-rewrite");
2083
2084 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2085 child.git_cmd = 1;
2086 argv_array_push(&child.args, "notes");
2087 argv_array_push(&child.args, "copy");
2088 argv_array_push(&child.args, "--for-rewrite=rebase");
2089 /* we don't care if this copying failed */
2090 run_command(&child);
2091
2092 if (post_rewrite_hook) {
2093 struct child_process hook = CHILD_PROCESS_INIT;
2094
2095 hook.in = open(rebase_path_rewritten_list(),
2096 O_RDONLY);
2097 hook.stdout_to_stderr = 1;
2098 argv_array_push(&hook.args, post_rewrite_hook);
2099 argv_array_push(&hook.args, "rebase");
2100 /* we don't care if this hook failed */
2101 run_command(&hook);
2102 }
2103 }
2104 apply_autostash(opts);
2105
2106 strbuf_release(&buf);
2107 strbuf_release(&head_ref);
2108 }
2109
2110 /*
2111 * Sequence of picks finished successfully; cleanup by
2112 * removing the .git/sequencer directory
2113 */
2114 return sequencer_remove_state(opts);
2115}
2116
2117static int continue_single_pick(void)
2118{
2119 const char *argv[] = { "commit", NULL };
2120
2121 if (!file_exists(git_path_cherry_pick_head()) &&
2122 !file_exists(git_path_revert_head()))
2123 return error(_("no cherry-pick or revert in progress"));
2124 return run_command_v_opt(argv, RUN_GIT_CMD);
2125}
2126
2127static int commit_staged_changes(struct replay_opts *opts)
2128{
2129 int amend = 0;
2130
2131 if (has_unstaged_changes(1))
2132 return error(_("cannot rebase: You have unstaged changes."));
2133 if (!has_uncommitted_changes(0)) {
2134 const char *cherry_pick_head = git_path("CHERRY_PICK_HEAD");
2135
2136 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2137 return error(_("could not remove CHERRY_PICK_HEAD"));
2138 return 0;
2139 }
2140
2141 if (file_exists(rebase_path_amend())) {
2142 struct strbuf rev = STRBUF_INIT;
2143 unsigned char head[20], to_amend[20];
2144
2145 if (get_sha1("HEAD", head))
2146 return error(_("cannot amend non-existing commit"));
2147 if (!read_oneliner(&rev, rebase_path_amend(), 0))
2148 return error(_("invalid file: '%s'"), rebase_path_amend());
2149 if (get_sha1_hex(rev.buf, to_amend))
2150 return error(_("invalid contents: '%s'"),
2151 rebase_path_amend());
2152 if (hashcmp(head, to_amend))
2153 return error(_("\nYou have uncommitted changes in your "
2154 "working tree. Please, commit them\n"
2155 "first and then run 'git rebase "
2156 "--continue' again."));
2157
2158 strbuf_release(&rev);
2159 amend = 1;
2160 }
2161
2162 if (run_git_commit(rebase_path_message(), opts, 1, 1, amend, 0))
2163 return error(_("could not commit staged changes."));
2164 unlink(rebase_path_amend());
2165 return 0;
2166}
2167
2168int sequencer_continue(struct replay_opts *opts)
2169{
2170 struct todo_list todo_list = TODO_LIST_INIT;
2171 int res;
2172
2173 if (read_and_refresh_cache(opts))
2174 return -1;
2175
2176 if (is_rebase_i(opts)) {
2177 if (commit_staged_changes(opts))
2178 return -1;
2179 } else if (!file_exists(get_todo_path(opts)))
2180 return continue_single_pick();
2181 if (read_populate_opts(opts))
2182 return -1;
2183 if ((res = read_populate_todo(&todo_list, opts)))
2184 goto release_todo_list;
2185
2186 if (!is_rebase_i(opts)) {
2187 /* Verify that the conflict has been resolved */
2188 if (file_exists(git_path_cherry_pick_head()) ||
2189 file_exists(git_path_revert_head())) {
2190 res = continue_single_pick();
2191 if (res)
2192 goto release_todo_list;
2193 }
2194 if (index_differs_from("HEAD", 0, 0)) {
2195 res = error_dirty_index(opts);
2196 goto release_todo_list;
2197 }
2198 todo_list.current++;
2199 } else if (file_exists(rebase_path_stopped_sha())) {
2200 struct strbuf buf = STRBUF_INIT;
2201 struct object_id oid;
2202
2203 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2204 !get_sha1_committish(buf.buf, oid.hash))
2205 record_in_rewritten(&oid, peek_command(&todo_list, 0));
2206 strbuf_release(&buf);
2207 }
2208
2209 res = pick_commits(&todo_list, opts);
2210release_todo_list:
2211 todo_list_release(&todo_list);
2212 return res;
2213}
2214
2215static int single_pick(struct commit *cmit, struct replay_opts *opts)
2216{
2217 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2218 return do_pick_commit(opts->action == REPLAY_PICK ?
2219 TODO_PICK : TODO_REVERT, cmit, opts, 0);
2220}
2221
2222int sequencer_pick_revisions(struct replay_opts *opts)
2223{
2224 struct todo_list todo_list = TODO_LIST_INIT;
2225 unsigned char sha1[20];
2226 int i, res;
2227
2228 assert(opts->revs);
2229 if (read_and_refresh_cache(opts))
2230 return -1;
2231
2232 for (i = 0; i < opts->revs->pending.nr; i++) {
2233 unsigned char sha1[20];
2234 const char *name = opts->revs->pending.objects[i].name;
2235
2236 /* This happens when using --stdin. */
2237 if (!strlen(name))
2238 continue;
2239
2240 if (!get_sha1(name, sha1)) {
2241 if (!lookup_commit_reference_gently(sha1, 1)) {
2242 enum object_type type = sha1_object_info(sha1, NULL);
2243 return error(_("%s: can't cherry-pick a %s"),
2244 name, typename(type));
2245 }
2246 } else
2247 return error(_("%s: bad revision"), name);
2248 }
2249
2250 /*
2251 * If we were called as "git cherry-pick <commit>", just
2252 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2253 * REVERT_HEAD, and don't touch the sequencer state.
2254 * This means it is possible to cherry-pick in the middle
2255 * of a cherry-pick sequence.
2256 */
2257 if (opts->revs->cmdline.nr == 1 &&
2258 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2259 opts->revs->no_walk &&
2260 !opts->revs->cmdline.rev->flags) {
2261 struct commit *cmit;
2262 if (prepare_revision_walk(opts->revs))
2263 return error(_("revision walk setup failed"));
2264 cmit = get_revision(opts->revs);
2265 if (!cmit || get_revision(opts->revs))
2266 return error("BUG: expected exactly one commit from walk");
2267 return single_pick(cmit, opts);
2268 }
2269
2270 /*
2271 * Start a new cherry-pick/ revert sequence; but
2272 * first, make sure that an existing one isn't in
2273 * progress
2274 */
2275
2276 if (walk_revs_populate_todo(&todo_list, opts) ||
2277 create_seq_dir() < 0)
2278 return -1;
2279 if (get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))
2280 return error(_("can't revert as initial commit"));
2281 if (save_head(sha1_to_hex(sha1)))
2282 return -1;
2283 if (save_opts(opts))
2284 return -1;
2285 update_abort_safety_file();
2286 res = pick_commits(&todo_list, opts);
2287 todo_list_release(&todo_list);
2288 return res;
2289}
2290
2291void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2292{
2293 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2294 struct strbuf sob = STRBUF_INIT;
2295 int has_footer;
2296
2297 strbuf_addstr(&sob, sign_off_header);
2298 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2299 getenv("GIT_COMMITTER_EMAIL")));
2300 strbuf_addch(&sob, '\n');
2301
2302 /*
2303 * If the whole message buffer is equal to the sob, pretend that we
2304 * found a conforming footer with a matching sob
2305 */
2306 if (msgbuf->len - ignore_footer == sob.len &&
2307 !strncmp(msgbuf->buf, sob.buf, sob.len))
2308 has_footer = 3;
2309 else
2310 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2311
2312 if (!has_footer) {
2313 const char *append_newlines = NULL;
2314 size_t len = msgbuf->len - ignore_footer;
2315
2316 if (!len) {
2317 /*
2318 * The buffer is completely empty. Leave foom for
2319 * the title and body to be filled in by the user.
2320 */
2321 append_newlines = "\n\n";
2322 } else if (msgbuf->buf[len - 1] != '\n') {
2323 /*
2324 * Incomplete line. Complete the line and add a
2325 * blank one so that there is an empty line between
2326 * the message body and the sob.
2327 */
2328 append_newlines = "\n\n";
2329 } else if (len == 1) {
2330 /*
2331 * Buffer contains a single newline. Add another
2332 * so that we leave room for the title and body.
2333 */
2334 append_newlines = "\n";
2335 } else if (msgbuf->buf[len - 2] != '\n') {
2336 /*
2337 * Buffer ends with a single newline. Add another
2338 * so that there is an empty line between the message
2339 * body and the sob.
2340 */
2341 append_newlines = "\n";
2342 } /* else, the buffer already ends with two newlines. */
2343
2344 if (append_newlines)
2345 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2346 append_newlines, strlen(append_newlines));
2347 }
2348
2349 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2350 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2351 sob.buf, sob.len);
2352
2353 strbuf_release(&sob);
2354}