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"
68 static const char *action_name(const struct replay_opts
*opts
)
70 return opts
->action
== REVERT
? "revert" : "cherry-pick";
73 static char *get_encoding(const char *message
);
75 static const char * const *revert_or_cherry_pick_usage(struct replay_opts
*opts
)
77 return opts
->action
== REVERT
? revert_usage
: cherry_pick_usage
;
80 static int option_parse_x(const struct option
*opt
,
81 const char *arg
, int unset
)
83 struct replay_opts
**opts_ptr
= opt
->value
;
84 struct replay_opts
*opts
= *opts_ptr
;
89 ALLOC_GROW(opts
->xopts
, opts
->xopts_nr
+ 1, opts
->xopts_alloc
);
90 opts
->xopts
[opts
->xopts_nr
++] = xstrdup(arg
);
94 static void verify_opt_compatible(const char *me
, const char *base_opt
, ...)
99 va_start(ap
, base_opt
);
100 while ((this_opt
= va_arg(ap
, const char *))) {
107 die(_("%s: %s cannot be used with %s"), me
, this_opt
, base_opt
);
110 static void parse_args(int argc
, const char **argv
, struct replay_opts
*opts
)
112 const char * const * usage_str
= revert_or_cherry_pick_usage(opts
);
113 const char *me
= action_name(opts
);
115 struct option options
[] = {
116 OPT_BOOLEAN('n', "no-commit", &opts
->no_commit
, "don't automatically commit"),
117 OPT_BOOLEAN('e', "edit", &opts
->edit
, "edit the commit message"),
118 { OPTION_BOOLEAN
, 'r', NULL
, &noop
, NULL
, "no-op (backward compatibility)",
119 PARSE_OPT_NOARG
| PARSE_OPT_HIDDEN
, NULL
, 0 },
120 OPT_BOOLEAN('s', "signoff", &opts
->signoff
, "add Signed-off-by:"),
121 OPT_INTEGER('m', "mainline", &opts
->mainline
, "parent number"),
122 OPT_RERERE_AUTOUPDATE(&opts
->allow_rerere_auto
),
123 OPT_STRING(0, "strategy", &opts
->strategy
, "strategy", "merge strategy"),
124 OPT_CALLBACK('X', "strategy-option", &opts
, "option",
125 "option for merge strategy", option_parse_x
),
131 if (opts
->action
== CHERRY_PICK
) {
132 struct option cp_extra
[] = {
133 OPT_BOOLEAN('x', NULL
, &opts
->record_origin
, "append commit name"),
134 OPT_BOOLEAN(0, "ff", &opts
->allow_ff
, "allow fast-forward"),
137 if (parse_options_concat(options
, ARRAY_SIZE(options
), cp_extra
))
138 die(_("program error"));
141 opts
->commit_argc
= parse_options(argc
, argv
, NULL
, options
, usage_str
,
142 PARSE_OPT_KEEP_ARGV0
|
143 PARSE_OPT_KEEP_UNKNOWN
);
144 if (opts
->commit_argc
< 2)
145 usage_with_options(usage_str
, options
);
148 verify_opt_compatible(me
, "--ff",
149 "--signoff", opts
->signoff
,
150 "--no-commit", opts
->no_commit
,
151 "-x", opts
->record_origin
,
152 "--edit", opts
->edit
,
154 opts
->commit_argv
= argv
;
157 struct commit_message
{
161 char *reencoded_message
;
165 static int get_message(struct commit
*commit
, struct commit_message
*out
)
167 const char *encoding
;
168 const char *abbrev
, *subject
;
169 int abbrev_len
, subject_len
;
174 encoding
= get_encoding(commit
->buffer
);
177 if (!git_commit_encoding
)
178 git_commit_encoding
= "UTF-8";
180 out
->reencoded_message
= NULL
;
181 out
->message
= commit
->buffer
;
182 if (strcmp(encoding
, git_commit_encoding
))
183 out
->reencoded_message
= reencode_string(commit
->buffer
,
184 git_commit_encoding
, encoding
);
185 if (out
->reencoded_message
)
186 out
->message
= out
->reencoded_message
;
188 abbrev
= find_unique_abbrev(commit
->object
.sha1
, DEFAULT_ABBREV
);
189 abbrev_len
= strlen(abbrev
);
191 subject_len
= find_commit_subject(out
->message
, &subject
);
193 out
->parent_label
= xmalloc(strlen("parent of ") + abbrev_len
+
194 strlen("... ") + subject_len
+ 1);
195 q
= out
->parent_label
;
196 q
= mempcpy(q
, "parent of ", strlen("parent of "));
198 q
= mempcpy(q
, abbrev
, abbrev_len
);
199 q
= mempcpy(q
, "... ", strlen("... "));
201 q
= mempcpy(q
, subject
, subject_len
);
206 static void free_message(struct commit_message
*msg
)
208 free(msg
->parent_label
);
209 free(msg
->reencoded_message
);
212 static char *get_encoding(const char *message
)
214 const char *p
= message
, *eol
;
216 while (*p
&& *p
!= '\n') {
217 for (eol
= p
+ 1; *eol
&& *eol
!= '\n'; eol
++)
219 if (!prefixcmp(p
, "encoding ")) {
220 char *result
= xmalloc(eol
- 8 - p
);
221 strlcpy(result
, p
+ 9, eol
- 8 - p
);
231 static void write_cherry_pick_head(struct commit
*commit
)
234 struct strbuf buf
= STRBUF_INIT
;
236 strbuf_addf(&buf
, "%s\n", sha1_to_hex(commit
->object
.sha1
));
238 fd
= open(git_path("CHERRY_PICK_HEAD"), O_WRONLY
| O_CREAT
, 0666);
240 die_errno(_("Could not open '%s' for writing"),
241 git_path("CHERRY_PICK_HEAD"));
242 if (write_in_full(fd
, buf
.buf
, buf
.len
) != buf
.len
|| close(fd
))
243 die_errno(_("Could not write to '%s'"), git_path("CHERRY_PICK_HEAD"));
244 strbuf_release(&buf
);
247 static void print_advice(void)
249 char *msg
= getenv("GIT_CHERRY_PICK_HELP");
252 fprintf(stderr
, "%s\n", msg
);
254 * A conflict has occured but the porcelain
255 * (typically rebase --interactive) wants to take care
256 * of the commit itself so remove CHERRY_PICK_HEAD
258 unlink(git_path("CHERRY_PICK_HEAD"));
262 advise("after resolving the conflicts, mark the corrected paths");
263 advise("with 'git add <paths>' or 'git rm <paths>'");
264 advise("and commit the result with 'git commit'");
267 static void write_message(struct strbuf
*msgbuf
, const char *filename
)
269 static struct lock_file msg_file
;
271 int msg_fd
= hold_lock_file_for_update(&msg_file
, filename
,
273 if (write_in_full(msg_fd
, msgbuf
->buf
, msgbuf
->len
) < 0)
274 die_errno(_("Could not write to %s."), filename
);
275 strbuf_release(msgbuf
);
276 if (commit_lock_file(&msg_file
) < 0)
277 die(_("Error wrapping up %s"), filename
);
280 static struct tree
*empty_tree(void)
282 struct tree
*tree
= xcalloc(1, sizeof(struct tree
));
284 tree
->object
.parsed
= 1;
285 tree
->object
.type
= OBJ_TREE
;
286 pretend_sha1_file(NULL
, 0, OBJ_TREE
, tree
->object
.sha1
);
290 static NORETURN
void die_dirty_index(struct replay_opts
*opts
)
292 if (read_cache_unmerged()) {
293 die_resolve_conflict(action_name(opts
));
295 if (advice_commit_before_merge
) {
296 if (opts
->action
== REVERT
)
297 die(_("Your local changes would be overwritten by revert.\n"
298 "Please, commit your changes or stash them to proceed."));
300 die(_("Your local changes would be overwritten by cherry-pick.\n"
301 "Please, commit your changes or stash them to proceed."));
303 if (opts
->action
== REVERT
)
304 die(_("Your local changes would be overwritten by revert.\n"));
306 die(_("Your local changes would be overwritten by cherry-pick.\n"));
311 static int fast_forward_to(const unsigned char *to
, const unsigned char *from
)
313 struct ref_lock
*ref_lock
;
316 if (checkout_fast_forward(from
, to
))
317 exit(1); /* the callee should have complained already */
318 ref_lock
= lock_any_ref_for_update("HEAD", from
, 0);
319 return write_ref_sha1(ref_lock
, to
, "cherry-pick");
322 static int do_recursive_merge(struct commit
*base
, struct commit
*next
,
323 const char *base_label
, const char *next_label
,
324 unsigned char *head
, struct strbuf
*msgbuf
,
325 struct replay_opts
*opts
)
327 struct merge_options o
;
328 struct tree
*result
, *next_tree
, *base_tree
, *head_tree
;
331 static struct lock_file index_lock
;
333 index_fd
= hold_locked_index(&index_lock
, 1);
337 init_merge_options(&o
);
338 o
.ancestor
= base
? base_label
: "(empty tree)";
340 o
.branch2
= next
? next_label
: "(empty tree)";
342 head_tree
= parse_tree_indirect(head
);
343 next_tree
= next
? next
->tree
: empty_tree();
344 base_tree
= base
? base
->tree
: empty_tree();
346 for (xopt
= opts
->xopts
; xopt
!= opts
->xopts
+ opts
->xopts_nr
; xopt
++)
347 parse_merge_opt(&o
, *xopt
);
349 clean
= merge_trees(&o
,
351 next_tree
, base_tree
, &result
);
353 if (active_cache_changed
&&
354 (write_cache(index_fd
, active_cache
, active_nr
) ||
355 commit_locked_index(&index_lock
)))
356 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
357 die(_("%s: Unable to write new index file"), action_name(opts
));
358 rollback_lock_file(&index_lock
);
362 strbuf_addstr(msgbuf
, "\nConflicts:\n\n");
363 for (i
= 0; i
< active_nr
;) {
364 struct cache_entry
*ce
= active_cache
[i
++];
366 strbuf_addch(msgbuf
, '\t');
367 strbuf_addstr(msgbuf
, ce
->name
);
368 strbuf_addch(msgbuf
, '\n');
369 while (i
< active_nr
&& !strcmp(ce
->name
,
370 active_cache
[i
]->name
))
380 * If we are cherry-pick, and if the merge did not result in
381 * hand-editing, we will hit this commit and inherit the original
382 * author date and name.
383 * If we are revert, or if our cherry-pick results in a hand merge,
384 * we had better say that the current user is responsible for that.
386 static int run_git_commit(const char *defmsg
, struct replay_opts
*opts
)
388 /* 6 is max possible length of our args array including NULL */
392 args
[i
++] = "commit";
402 return run_command_v_opt(args
, RUN_GIT_CMD
);
405 static int do_pick_commit(struct commit
*commit
, struct replay_opts
*opts
)
407 unsigned char head
[20];
408 struct commit
*base
, *next
, *parent
;
409 const char *base_label
, *next_label
;
410 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
, NULL
};
412 struct strbuf msgbuf
= STRBUF_INIT
;
415 if (opts
->no_commit
) {
417 * We do not intend to commit immediately. We just want to
418 * merge the differences in, so let's compute the tree
419 * that represents the "current" state for merge-recursive
422 if (write_cache_as_tree(head
, 0, NULL
))
423 die (_("Your index file is unmerged."));
425 if (get_sha1("HEAD", head
))
426 die (_("You do not have a valid HEAD"));
427 if (index_differs_from("HEAD", 0))
428 die_dirty_index(opts
);
432 if (!commit
->parents
) {
435 else if (commit
->parents
->next
) {
436 /* Reverting or cherry-picking a merge commit */
438 struct commit_list
*p
;
441 die(_("Commit %s is a merge but no -m option was given."),
442 sha1_to_hex(commit
->object
.sha1
));
444 for (cnt
= 1, p
= commit
->parents
;
445 cnt
!= opts
->mainline
&& p
;
448 if (cnt
!= opts
->mainline
|| !p
)
449 die(_("Commit %s does not have parent %d"),
450 sha1_to_hex(commit
->object
.sha1
), opts
->mainline
);
452 } else if (0 < opts
->mainline
)
453 die(_("Mainline was specified but commit %s is not a merge."),
454 sha1_to_hex(commit
->object
.sha1
));
456 parent
= commit
->parents
->item
;
458 if (opts
->allow_ff
&& parent
&& !hashcmp(parent
->object
.sha1
, head
))
459 return fast_forward_to(commit
->object
.sha1
, head
);
461 if (parent
&& parse_commit(parent
) < 0)
462 /* TRANSLATORS: The first %s will be "revert" or
463 "cherry-pick", the second %s a SHA1 */
464 die(_("%s: cannot parse parent commit %s"),
465 action_name(opts
), sha1_to_hex(parent
->object
.sha1
));
467 if (get_message(commit
, &msg
) != 0)
468 die(_("Cannot get commit message for %s"),
469 sha1_to_hex(commit
->object
.sha1
));
472 * "commit" is an existing commit. We would want to apply
473 * the difference it introduces since its first parent "prev"
474 * on top of the current HEAD if we are cherry-pick. Or the
475 * reverse of it if we are revert.
478 defmsg
= git_pathdup("MERGE_MSG");
480 if (opts
->action
== REVERT
) {
482 base_label
= msg
.label
;
484 next_label
= msg
.parent_label
;
485 strbuf_addstr(&msgbuf
, "Revert \"");
486 strbuf_addstr(&msgbuf
, msg
.subject
);
487 strbuf_addstr(&msgbuf
, "\"\n\nThis reverts commit ");
488 strbuf_addstr(&msgbuf
, sha1_to_hex(commit
->object
.sha1
));
490 if (commit
->parents
&& commit
->parents
->next
) {
491 strbuf_addstr(&msgbuf
, ", reversing\nchanges made to ");
492 strbuf_addstr(&msgbuf
, sha1_to_hex(parent
->object
.sha1
));
494 strbuf_addstr(&msgbuf
, ".\n");
499 base_label
= msg
.parent_label
;
501 next_label
= msg
.label
;
504 * Append the commit log message to msgbuf; it starts
505 * after the tree, parent, author, committer
506 * information followed by "\n\n".
508 p
= strstr(msg
.message
, "\n\n");
511 strbuf_addstr(&msgbuf
, p
);
514 if (opts
->record_origin
) {
515 strbuf_addstr(&msgbuf
, "(cherry picked from commit ");
516 strbuf_addstr(&msgbuf
, sha1_to_hex(commit
->object
.sha1
));
517 strbuf_addstr(&msgbuf
, ")\n");
519 if (!opts
->no_commit
)
520 write_cherry_pick_head(commit
);
523 if (!opts
->strategy
|| !strcmp(opts
->strategy
, "recursive") || opts
->action
== REVERT
) {
524 res
= do_recursive_merge(base
, next
, base_label
, next_label
,
525 head
, &msgbuf
, opts
);
526 write_message(&msgbuf
, defmsg
);
528 struct commit_list
*common
= NULL
;
529 struct commit_list
*remotes
= NULL
;
531 write_message(&msgbuf
, defmsg
);
533 commit_list_insert(base
, &common
);
534 commit_list_insert(next
, &remotes
);
535 res
= try_merge_command(opts
->strategy
, opts
->xopts_nr
, opts
->xopts
,
536 common
, sha1_to_hex(head
), remotes
);
537 free_commit_list(common
);
538 free_commit_list(remotes
);
542 error(opts
->action
== REVERT
543 ? _("could not revert %s... %s")
544 : _("could not apply %s... %s"),
545 find_unique_abbrev(commit
->object
.sha1
, DEFAULT_ABBREV
),
548 rerere(opts
->allow_rerere_auto
);
550 if (!opts
->no_commit
)
551 res
= run_git_commit(defmsg
, opts
);
560 static void prepare_revs(struct rev_info
*revs
, struct replay_opts
*opts
)
564 init_revisions(revs
, NULL
);
566 if (opts
->action
!= REVERT
)
569 argc
= setup_revisions(opts
->commit_argc
, opts
->commit_argv
, revs
, NULL
);
571 usage(*revert_or_cherry_pick_usage(opts
));
573 if (prepare_revision_walk(revs
))
574 die(_("revision walk setup failed"));
577 die(_("empty commit set passed"));
580 static void read_and_refresh_cache(struct replay_opts
*opts
)
582 static struct lock_file index_lock
;
583 int index_fd
= hold_locked_index(&index_lock
, 0);
584 if (read_index_preload(&the_index
, NULL
) < 0)
585 die(_("git %s: failed to read the index"), action_name(opts
));
586 refresh_index(&the_index
, REFRESH_QUIET
|REFRESH_UNMERGED
, NULL
, NULL
, NULL
);
587 if (the_index
.cache_changed
) {
588 if (write_index(&the_index
, index_fd
) ||
589 commit_locked_index(&index_lock
))
590 die(_("git %s: failed to refresh the index"), action_name(opts
));
592 rollback_lock_file(&index_lock
);
596 * Append a commit to the end of the commit_list.
598 * next starts by pointing to the variable that holds the head of an
599 * empty commit_list, and is updated to point to the "next" field of
600 * the last item on the list as new commits are appended.
604 * struct commit_list *list;
605 * struct commit_list **next = &list;
607 * next = commit_list_append(c1, next);
608 * next = commit_list_append(c2, next);
609 * assert(commit_list_count(list) == 2);
612 struct commit_list
**commit_list_append(struct commit
*commit
,
613 struct commit_list
**next
)
615 struct commit_list
*new = xmalloc(sizeof(struct commit_list
));
622 static int format_todo(struct strbuf
*buf
, struct commit_list
*todo_list
,
623 struct replay_opts
*opts
)
625 struct commit_list
*cur
= NULL
;
626 struct commit_message msg
= { NULL
, NULL
, NULL
, NULL
, NULL
};
627 const char *sha1_abbrev
= NULL
;
628 const char *action_str
= opts
->action
== REVERT
? "revert" : "pick";
630 for (cur
= todo_list
; cur
; cur
= cur
->next
) {
631 sha1_abbrev
= find_unique_abbrev(cur
->item
->object
.sha1
, DEFAULT_ABBREV
);
632 if (get_message(cur
->item
, &msg
))
633 return error(_("Cannot get commit message for %s"), sha1_abbrev
);
634 strbuf_addf(buf
, "%s %s %s\n", action_str
, sha1_abbrev
, msg
.subject
);
639 static void walk_revs_populate_todo(struct commit_list
**todo_list
,
640 struct replay_opts
*opts
)
642 struct rev_info revs
;
643 struct commit
*commit
;
644 struct commit_list
**next
;
646 prepare_revs(&revs
, opts
);
649 while ((commit
= get_revision(&revs
)))
650 next
= commit_list_append(commit
, next
);
653 static void create_seq_dir(void)
655 const char *seq_dir
= git_path(SEQ_DIR
);
657 if (!(file_exists(seq_dir
) && is_directory(seq_dir
))
658 && mkdir(seq_dir
, 0777) < 0)
659 die_errno(_("Could not create sequencer directory '%s'."), seq_dir
);
662 static void save_head(const char *head
)
664 const char *head_file
= git_path(SEQ_HEAD_FILE
);
665 static struct lock_file head_lock
;
666 struct strbuf buf
= STRBUF_INIT
;
669 fd
= hold_lock_file_for_update(&head_lock
, head_file
, LOCK_DIE_ON_ERROR
);
670 strbuf_addf(&buf
, "%s\n", head
);
671 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0)
672 die_errno(_("Could not write to %s."), head_file
);
673 if (commit_lock_file(&head_lock
) < 0)
674 die(_("Error wrapping up %s."), head_file
);
677 static void save_todo(struct commit_list
*todo_list
, struct replay_opts
*opts
)
679 const char *todo_file
= git_path(SEQ_TODO_FILE
);
680 static struct lock_file todo_lock
;
681 struct strbuf buf
= STRBUF_INIT
;
684 fd
= hold_lock_file_for_update(&todo_lock
, todo_file
, LOCK_DIE_ON_ERROR
);
685 if (format_todo(&buf
, todo_list
, opts
) < 0)
686 die(_("Could not format %s."), todo_file
);
687 if (write_in_full(fd
, buf
.buf
, buf
.len
) < 0) {
688 strbuf_release(&buf
);
689 die_errno(_("Could not write to %s."), todo_file
);
691 if (commit_lock_file(&todo_lock
) < 0) {
692 strbuf_release(&buf
);
693 die(_("Error wrapping up %s."), todo_file
);
695 strbuf_release(&buf
);
698 static int pick_commits(struct replay_opts
*opts
)
700 struct commit_list
*todo_list
= NULL
;
701 struct strbuf buf
= STRBUF_INIT
;
702 unsigned char sha1
[20];
703 struct commit_list
*cur
;
706 setenv(GIT_REFLOG_ACTION
, action_name(opts
), 0);
708 assert(!(opts
->signoff
|| opts
->no_commit
||
709 opts
->record_origin
|| opts
->edit
));
710 read_and_refresh_cache(opts
);
712 walk_revs_populate_todo(&todo_list
, opts
);
714 if (get_sha1("HEAD", sha1
)) {
715 if (opts
->action
== REVERT
)
716 die(_("Can't revert as initial commit"));
717 die(_("Can't cherry-pick into empty head"));
719 save_head(sha1_to_hex(sha1
));
721 for (cur
= todo_list
; cur
; cur
= cur
->next
) {
722 save_todo(cur
, opts
);
723 res
= do_pick_commit(cur
->item
, opts
);
729 * Sequence of picks finished successfully; cleanup by
730 * removing the .git/sequencer directory
732 strbuf_addf(&buf
, "%s", git_path(SEQ_DIR
));
733 remove_dir_recursively(&buf
, 0);
734 strbuf_release(&buf
);
738 int cmd_revert(int argc
, const char **argv
, const char *prefix
)
740 struct replay_opts opts
;
742 memset(&opts
, 0, sizeof(opts
));
745 opts
.action
= REVERT
;
746 git_config(git_default_config
, NULL
);
747 parse_args(argc
, argv
, &opts
);
748 return pick_commits(&opts
);
751 int cmd_cherry_pick(int argc
, const char **argv
, const char *prefix
)
753 struct replay_opts opts
;
755 memset(&opts
, 0, sizeof(opts
));
756 opts
.action
= CHERRY_PICK
;
757 git_config(git_default_config
, NULL
);
758 parse_args(argc
, argv
, &opts
);
759 return pick_commits(&opts
);