6 #include "run-command.h"
9 #include "parse-options.h"
10 #include "cache-tree.h"
14 #include "merge-recursive.h"
19 * This implements the builtins revert and cherry-pick.
21 * Copyright (c) 2007 Johannes E. Schindelin
23 * Based on git-revert.sh, which is
25 * Copyright (c) 2005 Linus Torvalds
26 * Copyright (c) 2005 Junio C Hamano
29 static const char * const revert_usage
[] = {
30 "git revert [options] <commit-ish>",
34 static const char * const cherry_pick_usage
[] = {
35 "git cherry-pick [options] <commit-ish>",
39 enum replay_action
{ REVERT
, CHERRY_PICK
};
42 enum replay_action action
;
50 int allow_rerere_auto
;
54 const char **commit_argv
;
59 size_t xopts_nr
, xopts_alloc
;
62 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
64 #define SEQ_DIR "sequencer"
65 #define SEQ_HEAD_FILE "sequencer/head"
66 #define SEQ_TODO_FILE "sequencer/todo"
67 #define SEQ_OPTS_FILE "sequencer/opts"
69 static const char *action_name(const struct replay_opts
*opts
)
71 return opts
->action
== REVERT
? "revert" : "cherry-pick";
74 static char *get_encoding(const char *message
);
76 static const char * const *revert_or_cherry_pick_usage(struct replay_opts
*opts
)
78 return opts
->action
== REVERT
? revert_usage
: cherry_pick_usage
;
81 static int option_parse_x(const struct option
*opt
,
82 const char *arg
, int unset
)
84 struct replay_opts
**opts_ptr
= opt
->value
;
85 struct replay_opts
*opts
= *opts_ptr
;
90 ALLOC_GROW(opts
->xopts
, opts
->xopts_nr
+ 1, opts
->xopts_alloc
);
91 opts
->xopts
[opts
->xopts_nr
++] = xstrdup(arg
);
95 static void verify_opt_compatible(const char *me
, const char *base_opt
, ...)
100 va_start(ap
, base_opt
);
101 while ((this_opt
= va_arg(ap
, const char *))) {
108 die(_("%s: %s cannot be used with %s"), me
, this_opt
, base_opt
);
111 static void parse_args(int argc
, const char **argv
, struct replay_opts
*opts
)
113 const char * const * usage_str
= revert_or_cherry_pick_usage(opts
);
114 const char *me
= action_name(opts
);
116 struct option options
[] = {
117 OPT_BOOLEAN('n', "no-commit", &opts
->no_commit
, "don't automatically commit"),
118 OPT_BOOLEAN('e', "edit", &opts
->edit
, "edit the commit message"),
119 { OPTION_BOOLEAN
, 'r', NULL
, &noop
, NULL
, "no-op (backward compatibility)",
120 PARSE_OPT_NOARG
| PARSE_OPT_HIDDEN
, NULL
, 0 },
121 OPT_BOOLEAN('s', "signoff", &opts
->signoff
, "add Signed-off-by:"),
122 OPT_INTEGER('m', "mainline", &opts
->mainline
, "parent number"),
123 OPT_RERERE_AUTOUPDATE(&opts
->allow_rerere_auto
),
124 OPT_STRING(0, "strategy", &opts
->strategy
, "strategy", "merge strategy"),
125 OPT_CALLBACK('X', "strategy-option", &opts
, "option",
126 "option for merge strategy", option_parse_x
),
132 if (opts
->action
== CHERRY_PICK
) {
133 struct option cp_extra
[] = {
134 OPT_BOOLEAN('x', NULL
, &opts
->record_origin
, "append commit name"),
135 OPT_BOOLEAN(0, "ff", &opts
->allow_ff
, "allow fast-forward"),
138 if (parse_options_concat(options
, ARRAY_SIZE(options
), cp_extra
))
139 die(_("program error"));
142 opts
->commit_argc
= parse_options(argc
, argv
, NULL
, options
, usage_str
,
143 PARSE_OPT_KEEP_ARGV0
|
144 PARSE_OPT_KEEP_UNKNOWN
);
145 if (opts
->commit_argc
< 2)
146 usage_with_options(usage_str
, options
);
149 verify_opt_compatible(me
, "--ff",
150 "--signoff", opts
->signoff
,
151 "--no-commit", opts
->no_commit
,
152 "-x", opts
->record_origin
,
153 "--edit", opts
->edit
,
155 opts
->commit_argv
= argv
;
158 struct commit_message
{
162 char *reencoded_message
;
166 static int get_message(struct commit
*commit
, struct commit_message
*out
)
168 const char *encoding
;
169 const char *abbrev
, *subject
;
170 int abbrev_len
, subject_len
;
175 encoding
= get_encoding(commit
->buffer
);
178 if (!git_commit_encoding
)
179 git_commit_encoding
= "UTF-8";
181 out
->reencoded_message
= NULL
;
182 out
->message
= commit
->buffer
;
183 if (strcmp(encoding
, git_commit_encoding
))
184 out
->reencoded_message
= reencode_string(commit
->buffer
,
185 git_commit_encoding
, encoding
);
186 if (out
->reencoded_message
)
187 out
->message
= out
->reencoded_message
;
189 abbrev
= find_unique_abbrev(commit
->object
.sha1
, DEFAULT_ABBREV
);
190 abbrev_len
= strlen(abbrev
);
192 subject_len
= find_commit_subject(out
->message
, &subject
);
194 out
->parent_label
= xmalloc(strlen("parent of ") + abbrev_len
+
195 strlen("... ") + subject_len
+ 1);
196 q
= out
->parent_label
;
197 q
= mempcpy(q
, "parent of ", strlen("parent of "));
199 q
= mempcpy(q
, abbrev
, abbrev_len
);
200 q
= mempcpy(q
, "... ", strlen("... "));
202 q
= mempcpy(q
, subject
, subject_len
);
207 static void free_message(struct commit_message
*msg
)
209 free(msg
->parent_label
);
210 free(msg
->reencoded_message
);
213 static char *get_encoding(const char *message
)
215 const char *p
= message
, *eol
;
217 while (*p
&& *p
!= '\n') {
218 for (eol
= p
+ 1; *eol
&& *eol
!= '\n'; eol
++)
220 if (!prefixcmp(p
, "encoding ")) {
221 char *result
= xmalloc(eol
- 8 - p
);
222 strlcpy(result
, p
+ 9, eol
- 8 - p
);
232 static void write_cherry_pick_head(struct commit
*commit
)
235 struct strbuf buf
= STRBUF_INIT
;
237 strbuf_addf(&buf
, "%s\n", sha1_to_hex(commit
->object
.sha1
));
239 fd
= open(git_path("CHERRY_PICK_HEAD"), O_WRONLY
| O_CREAT
, 0666);
241 die_errno(_("Could not open '%s' for writing"),
242 git_path("CHERRY_PICK_HEAD"));
243 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
|| close(fd
))
244 die_errno(_("Could not write to '%s'"), git_path("CHERRY_PICK_HEAD"));
245 strbuf_release(&buf
);
248 static void print_advice(void)
250 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
253 fprintf(stderr
, "%s\n", msg
);
255 * A conflict has occured but the porcelain
256 * (typically rebase --interactive) wants to take care
257 * of the commit itself so remove CHERRY_PICK_HEAD
259 unlink(git_path("CHERRY_PICK_HEAD"));
263 advise("after resolving the conflicts, mark the corrected paths");
264 advise("with 'git add <paths>' or 'git rm <paths>'");
265 advise("and commit the result with 'git commit'");
268 static void write_message(struct strbuf
*msgbuf
, const char *filename
)
270 static struct lock_file msg_file
;
272 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
,
274 if (write_in_full(msg_fd
, msgbuf
->buf
, msgbuf
->len
) < 0)
275 die_errno(_("Could not write to %s."), filename
);
276 strbuf_release(msgbuf
);
277 if (commit_lock_file(&msg_file
) < 0)
278 die(_("Error wrapping up %s"), filename
);
281 static struct tree
*empty_tree(void)
283 struct tree
*tree
= xcalloc(1, sizeof(struct tree
));
285 tree
->object
.parsed
= 1;
286 tree
->object
.type
= OBJ_TREE
;
287 pretend_sha1_file(NULL
, 0, OBJ_TREE
, tree
->object
.sha1
);
291 static NORETURN
void die_dirty_index(struct replay_opts
*opts
)
293 if (read_cache_unmerged()) {
294 die_resolve_conflict(action_name(opts
));
296 if (advice_commit_before_merge
) {
297 if (opts
->action
== REVERT
)
298 die(_("Your local changes would be overwritten by revert.\n"
299 "Please, commit your changes or stash them to proceed."));
301 die(_("Your local changes would be overwritten by cherry-pick.\n"
302 "Please, commit your changes or stash them to proceed."));
304 if (opts
->action
== REVERT
)
305 die(_("Your local changes would be overwritten by revert.\n"));
307 die(_("Your local changes would be overwritten by cherry-pick.\n"));
312 static int fast_forward_to(const unsigned char *to
, const unsigned char *from
)
314 struct ref_lock
*ref_lock
;
317 if (checkout_fast_forward(from
, to
))
318 exit(1); /* the callee should have complained already */
319 ref_lock
= lock_any_ref_for_update("HEAD", from
, 0);
320 return write_ref_sha1(ref_lock
, to
, "cherry-pick");
323 static int do_recursive_merge(struct commit
*base
, struct commit
*next
,
324 const char *base_label
, const char *next_label
,
325 unsigned char *head
, struct strbuf
*msgbuf
,
326 struct replay_opts
*opts
)
328 struct merge_options o
;
329 struct tree
*result
, *next_tree
, *base_tree
, *head_tree
;
332 static struct lock_file index_lock
;
334 index_fd
= hold_locked_index(&index_lock
, 1);
338 init_merge_options(&o
);
339 o
.ancestor
= base
? base_label
: "(empty tree)";
341 o
.branch2
= next
? next_label
: "(empty tree)";
343 head_tree
= parse_tree_indirect(head
);
344 next_tree
= next
? next
->tree
: empty_tree();
345 base_tree
= base
? base
->tree
: empty_tree();
347 for (xopt
= opts
->xopts
; xopt
!= opts
->xopts
+ opts
->xopts_nr
; xopt
++)
348 parse_merge_opt(&o
, *xopt
);
350 clean
= merge_trees(&o
,
352 next_tree
, base_tree
, &result
);
354 if (active_cache_changed
&&
355 (write_cache(index_fd
, active_cache
, active_nr
) ||
356 commit_locked_index(&index_lock
)))
357 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
358 die(_("%s: Unable to write new index file"), action_name(opts
));
359 rollback_lock_file(&index_lock
);
363 strbuf_addstr(msgbuf
, "\nConflicts:\n\n");
364 for (i
= 0; i
< active_nr
;) {
365 struct cache_entry
*ce
= active_cache
[i
++];
367 strbuf_addch(msgbuf
, '\t');
368 strbuf_addstr(msgbuf
, ce
->name
);
369 strbuf_addch(msgbuf
, '\n');
370 while (i
< active_nr
&& !strcmp(ce
->name
,
371 active_cache
[i
]->name
))
381 * If we are cherry-pick, and if the merge did not result in
382 * hand-editing, we will hit this commit and inherit the original
383 * author date and name.
384 * If we are revert, or if our cherry-pick results in a hand merge,
385 * we had better say that the current user is responsible for that.
387 static int run_git_commit(const char *defmsg
, struct replay_opts
*opts
)
389 /* 6 is max possible length of our args array including NULL */
393 args
[i
++] = "commit";
403 return run_command_v_opt(args
, RUN_GIT_CMD
);
406 static int do_pick_commit(struct commit
*commit
, struct replay_opts
*opts
)
408 unsigned char head
[20];
409 struct commit
*base
, *next
, *parent
;
410 const char *base_label
, *next_label
;
411 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
, NULL
};
413 struct strbuf msgbuf
= STRBUF_INIT
;
416 if (opts
->no_commit
) {
418 * We do not intend to commit immediately. We just want to
419 * merge the differences in, so let's compute the tree
420 * that represents the "current" state for merge-recursive
423 if (write_cache_as_tree(head
, 0, NULL
))
424 die (_("Your index file is unmerged."));
426 if (get_sha1("HEAD", head
))
427 die (_("You do not have a valid HEAD"));
428 if (index_differs_from("HEAD", 0))
429 die_dirty_index(opts
);
433 if (!commit
->parents
) {
436 else if (commit
->parents
->next
) {
437 /* Reverting or cherry-picking a merge commit */
439 struct commit_list
*p
;
442 die(_("Commit %s is a merge but no -m option was given."),
443 sha1_to_hex(commit
->object
.sha1
));
445 for (cnt
= 1, p
= commit
->parents
;
446 cnt
!= opts
->mainline
&& p
;
449 if (cnt
!= opts
->mainline
|| !p
)
450 die(_("Commit %s does not have parent %d"),
451 sha1_to_hex(commit
->object
.sha1
), opts
->mainline
);
453 } else if (0 < opts
->mainline
)
454 die(_("Mainline was specified but commit %s is not a merge."),
455 sha1_to_hex(commit
->object
.sha1
));
457 parent
= commit
->parents
->item
;
459 if (opts
->allow_ff
&& parent
&& !hashcmp(parent
->object
.sha1
, head
))
460 return fast_forward_to(commit
->object
.sha1
, head
);
462 if (parent
&& parse_commit(parent
) < 0)
463 /* TRANSLATORS: The first %s will be "revert" or
464 "cherry-pick", the second %s a SHA1 */
465 die(_("%s: cannot parse parent commit %s"),
466 action_name(opts
), sha1_to_hex(parent
->object
.sha1
));
468 if (get_message(commit
, &msg
) != 0)
469 die(_("Cannot get commit message for %s"),
470 sha1_to_hex(commit
->object
.sha1
));
473 * "commit" is an existing commit. We would want to apply
474 * the difference it introduces since its first parent "prev"
475 * on top of the current HEAD if we are cherry-pick. Or the
476 * reverse of it if we are revert.
479 defmsg
= git_pathdup("MERGE_MSG");
481 if (opts
->action
== REVERT
) {
483 base_label
= msg
.label
;
485 next_label
= msg
.parent_label
;
486 strbuf_addstr(&msgbuf
, "Revert \"");
487 strbuf_addstr(&msgbuf
, msg
.subject
);
488 strbuf_addstr(&msgbuf
, "\"\n\nThis reverts commit ");
489 strbuf_addstr(&msgbuf
, sha1_to_hex(commit
->object
.sha1
));
491 if (commit
->parents
&& commit
->parents
->next
) {
492 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
493 strbuf_addstr(&msgbuf
, sha1_to_hex(parent
->object
.sha1
));
495 strbuf_addstr(&msgbuf
, ".\n");
500 base_label
= msg
.parent_label
;
502 next_label
= msg
.label
;
505 * Append the commit log message to msgbuf; it starts
506 * after the tree, parent, author, committer
507 * information followed by "\n\n".
509 p
= strstr(msg
.message
, "\n\n");
512 strbuf_addstr(&msgbuf
, p
);
515 if (opts
->record_origin
) {
516 strbuf_addstr(&msgbuf
, "(cherry picked from commit ");
517 strbuf_addstr(&msgbuf
, sha1_to_hex(commit
->object
.sha1
));
518 strbuf_addstr(&msgbuf
, ")\n");
520 if (!opts
->no_commit
)
521 write_cherry_pick_head(commit
);
524 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "recursive") || opts
->action
== REVERT
) {
525 res
= do_recursive_merge(base
, next
, base_label
, next_label
,
526 head
, &msgbuf
, opts
);
527 write_message(&msgbuf
, defmsg
);
529 struct commit_list
*common
= NULL
;
530 struct commit_list
*remotes
= NULL
;
532 write_message(&msgbuf
, defmsg
);
534 commit_list_insert(base
, &common
);
535 commit_list_insert(next
, &remotes
);
536 res
= try_merge_command(opts
->strategy
, opts
->xopts_nr
, opts
->xopts
,
537 common
, sha1_to_hex(head
), remotes
);
538 free_commit_list(common
);
539 free_commit_list(remotes
);
543 error(opts
->action
== REVERT
544 ? _("could not revert %s... %s")
545 : _("could not apply %s... %s"),
546 find_unique_abbrev(commit
->object
.sha1
, DEFAULT_ABBREV
),
549 rerere(opts
->allow_rerere_auto
);
551 if (!opts
->no_commit
)
552 res
= run_git_commit(defmsg
, opts
);
561 static void prepare_revs(struct rev_info
*revs
, struct replay_opts
*opts
)
565 init_revisions(revs
, NULL
);
567 if (opts
->action
!= REVERT
)
570 argc
= setup_revisions(opts
->commit_argc
, opts
->commit_argv
, revs
, NULL
);
572 usage(*revert_or_cherry_pick_usage(opts
));
574 if (prepare_revision_walk(revs
))
575 die(_("revision walk setup failed"));
578 die(_("empty commit set passed"));
581 static void read_and_refresh_cache(struct replay_opts
*opts
)
583 static struct lock_file index_lock
;
584 int index_fd
= hold_locked_index(&index_lock
, 0);
585 if (read_index_preload(&the_index
, NULL
) < 0)
586 die(_("git %s: failed to read the index"), action_name(opts
));
587 refresh_index(&the_index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
588 if (the_index
.cache_changed
) {
589 if (write_index(&the_index
, index_fd
) ||
590 commit_locked_index(&index_lock
))
591 die(_("git %s: failed to refresh the index"), action_name(opts
));
593 rollback_lock_file(&index_lock
);
597 * Append a commit to the end of the commit_list.
599 * next starts by pointing to the variable that holds the head of an
600 * empty commit_list, and is updated to point to the "next" field of
601 * the last item on the list as new commits are appended.
605 * struct commit_list *list;
606 * struct commit_list **next = &list;
608 * next = commit_list_append(c1, next);
609 * next = commit_list_append(c2, next);
610 * assert(commit_list_count(list) == 2);
613 struct commit_list
**commit_list_append(struct commit
*commit
,
614 struct commit_list
**next
)
616 struct commit_list
*new = xmalloc(sizeof(struct commit_list
));
623 static int format_todo(struct strbuf
*buf
, struct commit_list
*todo_list
,
624 struct replay_opts
*opts
)
626 struct commit_list
*cur
= NULL
;
627 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
, NULL
};
628 const char *sha1_abbrev
= NULL
;
629 const char *action_str
= opts
->action
== REVERT
? "revert" : "pick";
631 for (cur
= todo_list
; cur
; cur
= cur
->next
) {
632 sha1_abbrev
= find_unique_abbrev(cur
->item
->object
.sha1
, DEFAULT_ABBREV
);
633 if (get_message(cur
->item
, &msg
))
634 return error(_("Cannot get commit message for %s"), sha1_abbrev
);
635 strbuf_addf(buf
, "%s %s %s\n", action_str
, sha1_abbrev
, msg
.subject
);
640 static void walk_revs_populate_todo(struct commit_list
**todo_list
,
641 struct replay_opts
*opts
)
643 struct rev_info revs
;
644 struct commit
*commit
;
645 struct commit_list
**next
;
647 prepare_revs(&revs
, opts
);
650 while ((commit
= get_revision(&revs
)))
651 next
= commit_list_append(commit
, next
);
654 static void create_seq_dir(void)
656 const char *seq_dir
= git_path(SEQ_DIR
);
658 if (!(file_exists(seq_dir
) && is_directory(seq_dir
))
659 && mkdir(seq_dir
, 0777) < 0)
660 die_errno(_("Could not create sequencer directory '%s'."), seq_dir
);
663 static void save_head(const char *head
)
665 const char *head_file
= git_path(SEQ_HEAD_FILE
);
666 static struct lock_file head_lock
;
667 struct strbuf buf
= STRBUF_INIT
;
670 fd
= hold_lock_file_for_update(&head_lock
, head_file
, LOCK_DIE_ON_ERROR
);
671 strbuf_addf(&buf
, "%s\n", head
);
672 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0)
673 die_errno(_("Could not write to %s."), head_file
);
674 if (commit_lock_file(&head_lock
) < 0)
675 die(_("Error wrapping up %s."), head_file
);
678 static void save_todo(struct commit_list
*todo_list
, struct replay_opts
*opts
)
680 const char *todo_file
= git_path(SEQ_TODO_FILE
);
681 static struct lock_file todo_lock
;
682 struct strbuf buf
= STRBUF_INIT
;
685 fd
= hold_lock_file_for_update(&todo_lock
, todo_file
, LOCK_DIE_ON_ERROR
);
686 if (format_todo(&buf
, todo_list
, opts
) < 0)
687 die(_("Could not format %s."), todo_file
);
688 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
689 strbuf_release(&buf
);
690 die_errno(_("Could not write to %s."), todo_file
);
692 if (commit_lock_file(&todo_lock
) < 0) {
693 strbuf_release(&buf
);
694 die(_("Error wrapping up %s."), todo_file
);
696 strbuf_release(&buf
);
699 static void save_opts(struct replay_opts
*opts
)
701 const char *opts_file
= git_path(SEQ_OPTS_FILE
);
704 git_config_set_in_file(opts_file
, "options.no-commit", "true");
706 git_config_set_in_file(opts_file
, "options.edit", "true");
708 git_config_set_in_file(opts_file
, "options.signoff", "true");
709 if (opts
->record_origin
)
710 git_config_set_in_file(opts_file
, "options.record-origin", "true");
712 git_config_set_in_file(opts_file
, "options.allow-ff", "true");
713 if (opts
->mainline
) {
714 struct strbuf buf
= STRBUF_INIT
;
715 strbuf_addf(&buf
, "%d", opts
->mainline
);
716 git_config_set_in_file(opts_file
, "options.mainline", buf
.buf
);
717 strbuf_release(&buf
);
720 git_config_set_in_file(opts_file
, "options.strategy", opts
->strategy
);
723 for (i
= 0; i
< opts
->xopts_nr
; i
++)
724 git_config_set_multivar_in_file(opts_file
,
725 "options.strategy-option",
726 opts
->xopts
[i
], "^$", 0);
730 static int pick_commits(struct replay_opts
*opts
)
732 struct commit_list
*todo_list
= NULL
;
733 struct strbuf buf
= STRBUF_INIT
;
734 unsigned char sha1
[20];
735 struct commit_list
*cur
;
738 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
740 assert(!(opts
->signoff
|| opts
->no_commit
||
741 opts
->record_origin
|| opts
->edit
));
742 read_and_refresh_cache(opts
);
744 walk_revs_populate_todo(&todo_list
, opts
);
746 if (get_sha1("HEAD", sha1
)) {
747 if (opts
->action
== REVERT
)
748 die(_("Can't revert as initial commit"));
749 die(_("Can't cherry-pick into empty head"));
751 save_head(sha1_to_hex(sha1
));
754 for (cur
= todo_list
; cur
; cur
= cur
->next
) {
755 save_todo(cur
, opts
);
756 res
= do_pick_commit(cur
->item
, opts
);
762 * Sequence of picks finished successfully; cleanup by
763 * removing the .git/sequencer directory
765 strbuf_addf(&buf
, "%s", git_path(SEQ_DIR
));
766 remove_dir_recursively(&buf
, 0);
767 strbuf_release(&buf
);
771 int cmd_revert(int argc
, const char **argv
, const char *prefix
)
773 struct replay_opts opts
;
775 memset(&opts
, 0, sizeof(opts
));
778 opts
.action
= REVERT
;
779 git_config(git_default_config
, NULL
);
780 parse_args(argc
, argv
, &opts
);
781 return pick_commits(&opts
);
784 int cmd_cherry_pick(int argc
, const char **argv
, const char *prefix
)
786 struct replay_opts opts
;
788 memset(&opts
, 0, sizeof(opts
));
789 opts
.action
= CHERRY_PICK
;
790 git_config(git_default_config
, NULL
);
791 parse_args(argc
, argv
, &opts
);
792 return pick_commits(&opts
);