1#include "cache.h"
2#include "builtin.h"
3#include "object.h"
4#include "commit.h"
5#include "tag.h"
6#include "run-command.h"
7#include "exec_cmd.h"
8#include "utf8.h"
9#include "parse-options.h"
10#include "cache-tree.h"
11#include "diff.h"
12#include "revision.h"
13#include "rerere.h"
14#include "merge-recursive.h"
15#include "refs.h"
16#include "dir.h"
17#include "sequencer.h"
18
19/*
20 * This implements the builtins revert and cherry-pick.
21 *
22 * Copyright (c) 2007 Johannes E. Schindelin
23 *
24 * Based on git-revert.sh, which is
25 *
26 * Copyright (c) 2005 Linus Torvalds
27 * Copyright (c) 2005 Junio C Hamano
28 */
29
30static const char * const revert_usage[] = {
31 "git revert [options] <commit-ish>",
32 "git revert <subcommand>",
33 NULL
34};
35
36static const char * const cherry_pick_usage[] = {
37 "git cherry-pick [options] <commit-ish>",
38 "git cherry-pick <subcommand>",
39 NULL
40};
41
42enum replay_action { REVERT, CHERRY_PICK };
43enum replay_subcommand { REPLAY_NONE, REPLAY_RESET, REPLAY_CONTINUE };
44
45struct replay_opts {
46 enum replay_action action;
47 enum replay_subcommand subcommand;
48
49 /* Boolean options */
50 int edit;
51 int record_origin;
52 int no_commit;
53 int signoff;
54 int allow_ff;
55 int allow_rerere_auto;
56
57 int mainline;
58 int commit_argc;
59 const char **commit_argv;
60
61 /* Merge strategy */
62 const char *strategy;
63 const char **xopts;
64 size_t xopts_nr, xopts_alloc;
65};
66
67#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
68
69static const char *action_name(const struct replay_opts *opts)
70{
71 return opts->action == REVERT ? "revert" : "cherry-pick";
72}
73
74static char *get_encoding(const char *message);
75
76static const char * const *revert_or_cherry_pick_usage(struct replay_opts *opts)
77{
78 return opts->action == REVERT ? revert_usage : cherry_pick_usage;
79}
80
81static int option_parse_x(const struct option *opt,
82 const char *arg, int unset)
83{
84 struct replay_opts **opts_ptr = opt->value;
85 struct replay_opts *opts = *opts_ptr;
86
87 if (unset)
88 return 0;
89
90 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
91 opts->xopts[opts->xopts_nr++] = xstrdup(arg);
92 return 0;
93}
94
95static void verify_opt_compatible(const char *me, const char *base_opt, ...)
96{
97 const char *this_opt;
98 va_list ap;
99
100 va_start(ap, base_opt);
101 while ((this_opt = va_arg(ap, const char *))) {
102 if (va_arg(ap, int))
103 break;
104 }
105 va_end(ap);
106
107 if (this_opt)
108 die(_("%s: %s cannot be used with %s"), me, this_opt, base_opt);
109}
110
111static void verify_opt_mutually_compatible(const char *me, ...)
112{
113 const char *opt1, *opt2 = NULL;
114 va_list ap;
115
116 va_start(ap, me);
117 while ((opt1 = va_arg(ap, const char *))) {
118 if (va_arg(ap, int))
119 break;
120 }
121 if (opt1) {
122 while ((opt2 = va_arg(ap, const char *))) {
123 if (va_arg(ap, int))
124 break;
125 }
126 }
127
128 if (opt1 && opt2)
129 die(_("%s: %s cannot be used with %s"), me, opt1, opt2);
130}
131
132static void parse_args(int argc, const char **argv, struct replay_opts *opts)
133{
134 const char * const * usage_str = revert_or_cherry_pick_usage(opts);
135 const char *me = action_name(opts);
136 int reset = 0;
137 int contin = 0;
138 struct option options[] = {
139 OPT_BOOLEAN(0, "reset", &reset, "forget the current operation"),
140 OPT_BOOLEAN(0, "continue", &contin, "continue the current operation"),
141 OPT_BOOLEAN('n', "no-commit", &opts->no_commit, "don't automatically commit"),
142 OPT_BOOLEAN('e', "edit", &opts->edit, "edit the commit message"),
143 OPT_NOOP_NOARG('r', NULL),
144 OPT_BOOLEAN('s', "signoff", &opts->signoff, "add Signed-off-by:"),
145 OPT_INTEGER('m', "mainline", &opts->mainline, "parent number"),
146 OPT_RERERE_AUTOUPDATE(&opts->allow_rerere_auto),
147 OPT_STRING(0, "strategy", &opts->strategy, "strategy", "merge strategy"),
148 OPT_CALLBACK('X', "strategy-option", &opts, "option",
149 "option for merge strategy", option_parse_x),
150 OPT_END(),
151 OPT_END(),
152 OPT_END(),
153 };
154
155 if (opts->action == CHERRY_PICK) {
156 struct option cp_extra[] = {
157 OPT_BOOLEAN('x', NULL, &opts->record_origin, "append commit name"),
158 OPT_BOOLEAN(0, "ff", &opts->allow_ff, "allow fast-forward"),
159 OPT_END(),
160 };
161 if (parse_options_concat(options, ARRAY_SIZE(options), cp_extra))
162 die(_("program error"));
163 }
164
165 opts->commit_argc = parse_options(argc, argv, NULL, options, usage_str,
166 PARSE_OPT_KEEP_ARGV0 |
167 PARSE_OPT_KEEP_UNKNOWN);
168
169 /* Check for incompatible subcommands */
170 verify_opt_mutually_compatible(me,
171 "--reset", reset,
172 "--continue", contin,
173 NULL);
174
175 /* Set the subcommand */
176 if (reset)
177 opts->subcommand = REPLAY_RESET;
178 else if (contin)
179 opts->subcommand = REPLAY_CONTINUE;
180 else
181 opts->subcommand = REPLAY_NONE;
182
183 /* Check for incompatible command line arguments */
184 if (opts->subcommand != REPLAY_NONE) {
185 char *this_operation;
186 if (opts->subcommand == REPLAY_RESET)
187 this_operation = "--reset";
188 else
189 this_operation = "--continue";
190
191 verify_opt_compatible(me, this_operation,
192 "--no-commit", opts->no_commit,
193 "--signoff", opts->signoff,
194 "--mainline", opts->mainline,
195 "--strategy", opts->strategy ? 1 : 0,
196 "--strategy-option", opts->xopts ? 1 : 0,
197 "-x", opts->record_origin,
198 "--ff", opts->allow_ff,
199 NULL);
200 }
201
202 else if (opts->commit_argc < 2)
203 usage_with_options(usage_str, options);
204
205 if (opts->allow_ff)
206 verify_opt_compatible(me, "--ff",
207 "--signoff", opts->signoff,
208 "--no-commit", opts->no_commit,
209 "-x", opts->record_origin,
210 "--edit", opts->edit,
211 NULL);
212 opts->commit_argv = argv;
213}
214
215struct commit_message {
216 char *parent_label;
217 const char *label;
218 const char *subject;
219 char *reencoded_message;
220 const char *message;
221};
222
223static int get_message(struct commit *commit, struct commit_message *out)
224{
225 const char *encoding;
226 const char *abbrev, *subject;
227 int abbrev_len, subject_len;
228 char *q;
229
230 if (!commit->buffer)
231 return -1;
232 encoding = get_encoding(commit->buffer);
233 if (!encoding)
234 encoding = "UTF-8";
235 if (!git_commit_encoding)
236 git_commit_encoding = "UTF-8";
237
238 out->reencoded_message = NULL;
239 out->message = commit->buffer;
240 if (strcmp(encoding, git_commit_encoding))
241 out->reencoded_message = reencode_string(commit->buffer,
242 git_commit_encoding, encoding);
243 if (out->reencoded_message)
244 out->message = out->reencoded_message;
245
246 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
247 abbrev_len = strlen(abbrev);
248
249 subject_len = find_commit_subject(out->message, &subject);
250
251 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
252 strlen("... ") + subject_len + 1);
253 q = out->parent_label;
254 q = mempcpy(q, "parent of ", strlen("parent of "));
255 out->label = q;
256 q = mempcpy(q, abbrev, abbrev_len);
257 q = mempcpy(q, "... ", strlen("... "));
258 out->subject = q;
259 q = mempcpy(q, subject, subject_len);
260 *q = '\0';
261 return 0;
262}
263
264static void free_message(struct commit_message *msg)
265{
266 free(msg->parent_label);
267 free(msg->reencoded_message);
268}
269
270static char *get_encoding(const char *message)
271{
272 const char *p = message, *eol;
273
274 while (*p && *p != '\n') {
275 for (eol = p + 1; *eol && *eol != '\n'; eol++)
276 ; /* do nothing */
277 if (!prefixcmp(p, "encoding ")) {
278 char *result = xmalloc(eol - 8 - p);
279 strlcpy(result, p + 9, eol - 8 - p);
280 return result;
281 }
282 p = eol;
283 if (*p == '\n')
284 p++;
285 }
286 return NULL;
287}
288
289static void write_cherry_pick_head(struct commit *commit)
290{
291 const char *filename;
292 int fd;
293 struct strbuf buf = STRBUF_INIT;
294
295 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
296
297 filename = git_path("CHERRY_PICK_HEAD");
298 fd = open(filename, O_WRONLY | O_CREAT, 0666);
299 if (fd < 0)
300 die_errno(_("Could not open '%s' for writing"), filename);
301 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
302 die_errno(_("Could not write to '%s'"), filename);
303 strbuf_release(&buf);
304}
305
306static void print_advice(int show_hint)
307{
308 char *msg = getenv("GIT_CHERRY_PICK_HELP");
309
310 if (msg) {
311 fprintf(stderr, "%s\n", msg);
312 /*
313 * A conflict has occured but the porcelain
314 * (typically rebase --interactive) wants to take care
315 * of the commit itself so remove CHERRY_PICK_HEAD
316 */
317 unlink(git_path("CHERRY_PICK_HEAD"));
318 return;
319 }
320
321 if (show_hint) {
322 advise("after resolving the conflicts, mark the corrected paths");
323 advise("with 'git add <paths>' or 'git rm <paths>'");
324 advise("and commit the result with 'git commit'");
325 }
326}
327
328static void write_message(struct strbuf *msgbuf, const char *filename)
329{
330 static struct lock_file msg_file;
331
332 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
333 LOCK_DIE_ON_ERROR);
334 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
335 die_errno(_("Could not write to %s"), filename);
336 strbuf_release(msgbuf);
337 if (commit_lock_file(&msg_file) < 0)
338 die(_("Error wrapping up %s"), filename);
339}
340
341static struct tree *empty_tree(void)
342{
343 return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
344}
345
346static int error_dirty_index(struct replay_opts *opts)
347{
348 if (read_cache_unmerged())
349 return error_resolve_conflict(action_name(opts));
350
351 /* Different translation strings for cherry-pick and revert */
352 if (opts->action == CHERRY_PICK)
353 error(_("Your local changes would be overwritten by cherry-pick."));
354 else
355 error(_("Your local changes would be overwritten by revert."));
356
357 if (advice_commit_before_merge)
358 advise(_("Commit your changes or stash them to proceed."));
359 return -1;
360}
361
362static int fast_forward_to(const unsigned char *to, const unsigned char *from)
363{
364 struct ref_lock *ref_lock;
365
366 read_cache();
367 if (checkout_fast_forward(from, to))
368 exit(1); /* the callee should have complained already */
369 ref_lock = lock_any_ref_for_update("HEAD", from, 0);
370 return write_ref_sha1(ref_lock, to, "cherry-pick");
371}
372
373static int do_recursive_merge(struct commit *base, struct commit *next,
374 const char *base_label, const char *next_label,
375 unsigned char *head, struct strbuf *msgbuf,
376 struct replay_opts *opts)
377{
378 struct merge_options o;
379 struct tree *result, *next_tree, *base_tree, *head_tree;
380 int clean, index_fd;
381 const char **xopt;
382 static struct lock_file index_lock;
383
384 index_fd = hold_locked_index(&index_lock, 1);
385
386 read_cache();
387
388 init_merge_options(&o);
389 o.ancestor = base ? base_label : "(empty tree)";
390 o.branch1 = "HEAD";
391 o.branch2 = next ? next_label : "(empty tree)";
392
393 head_tree = parse_tree_indirect(head);
394 next_tree = next ? next->tree : empty_tree();
395 base_tree = base ? base->tree : empty_tree();
396
397 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
398 parse_merge_opt(&o, *xopt);
399
400 clean = merge_trees(&o,
401 head_tree,
402 next_tree, base_tree, &result);
403
404 if (active_cache_changed &&
405 (write_cache(index_fd, active_cache, active_nr) ||
406 commit_locked_index(&index_lock)))
407 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
408 die(_("%s: Unable to write new index file"), action_name(opts));
409 rollback_lock_file(&index_lock);
410
411 if (!clean) {
412 int i;
413 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
414 for (i = 0; i < active_nr;) {
415 struct cache_entry *ce = active_cache[i++];
416 if (ce_stage(ce)) {
417 strbuf_addch(msgbuf, '\t');
418 strbuf_addstr(msgbuf, ce->name);
419 strbuf_addch(msgbuf, '\n');
420 while (i < active_nr && !strcmp(ce->name,
421 active_cache[i]->name))
422 i++;
423 }
424 }
425 }
426
427 return !clean;
428}
429
430/*
431 * If we are cherry-pick, and if the merge did not result in
432 * hand-editing, we will hit this commit and inherit the original
433 * author date and name.
434 * If we are revert, or if our cherry-pick results in a hand merge,
435 * we had better say that the current user is responsible for that.
436 */
437static int run_git_commit(const char *defmsg, struct replay_opts *opts)
438{
439 /* 6 is max possible length of our args array including NULL */
440 const char *args[6];
441 int i = 0;
442
443 args[i++] = "commit";
444 args[i++] = "-n";
445 if (opts->signoff)
446 args[i++] = "-s";
447 if (!opts->edit) {
448 args[i++] = "-F";
449 args[i++] = defmsg;
450 }
451 args[i] = NULL;
452
453 return run_command_v_opt(args, RUN_GIT_CMD);
454}
455
456static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
457{
458 unsigned char head[20];
459 struct commit *base, *next, *parent;
460 const char *base_label, *next_label;
461 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
462 char *defmsg = NULL;
463 struct strbuf msgbuf = STRBUF_INIT;
464 int res;
465
466 if (opts->no_commit) {
467 /*
468 * We do not intend to commit immediately. We just want to
469 * merge the differences in, so let's compute the tree
470 * that represents the "current" state for merge-recursive
471 * to work on.
472 */
473 if (write_cache_as_tree(head, 0, NULL))
474 die (_("Your index file is unmerged."));
475 } else {
476 if (get_sha1("HEAD", head))
477 return error(_("You do not have a valid HEAD"));
478 if (index_differs_from("HEAD", 0))
479 return error_dirty_index(opts);
480 }
481 discard_cache();
482
483 if (!commit->parents) {
484 parent = NULL;
485 }
486 else if (commit->parents->next) {
487 /* Reverting or cherry-picking a merge commit */
488 int cnt;
489 struct commit_list *p;
490
491 if (!opts->mainline)
492 return error(_("Commit %s is a merge but no -m option was given."),
493 sha1_to_hex(commit->object.sha1));
494
495 for (cnt = 1, p = commit->parents;
496 cnt != opts->mainline && p;
497 cnt++)
498 p = p->next;
499 if (cnt != opts->mainline || !p)
500 return error(_("Commit %s does not have parent %d"),
501 sha1_to_hex(commit->object.sha1), opts->mainline);
502 parent = p->item;
503 } else if (0 < opts->mainline)
504 return error(_("Mainline was specified but commit %s is not a merge."),
505 sha1_to_hex(commit->object.sha1));
506 else
507 parent = commit->parents->item;
508
509 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
510 return fast_forward_to(commit->object.sha1, head);
511
512 if (parent && parse_commit(parent) < 0)
513 /* TRANSLATORS: The first %s will be "revert" or
514 "cherry-pick", the second %s a SHA1 */
515 return error(_("%s: cannot parse parent commit %s"),
516 action_name(opts), sha1_to_hex(parent->object.sha1));
517
518 if (get_message(commit, &msg) != 0)
519 return error(_("Cannot get commit message for %s"),
520 sha1_to_hex(commit->object.sha1));
521
522 /*
523 * "commit" is an existing commit. We would want to apply
524 * the difference it introduces since its first parent "prev"
525 * on top of the current HEAD if we are cherry-pick. Or the
526 * reverse of it if we are revert.
527 */
528
529 defmsg = git_pathdup("MERGE_MSG");
530
531 if (opts->action == REVERT) {
532 base = commit;
533 base_label = msg.label;
534 next = parent;
535 next_label = msg.parent_label;
536 strbuf_addstr(&msgbuf, "Revert \"");
537 strbuf_addstr(&msgbuf, msg.subject);
538 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
539 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
540
541 if (commit->parents && commit->parents->next) {
542 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
543 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
544 }
545 strbuf_addstr(&msgbuf, ".\n");
546 } else {
547 const char *p;
548
549 base = parent;
550 base_label = msg.parent_label;
551 next = commit;
552 next_label = msg.label;
553
554 /*
555 * Append the commit log message to msgbuf; it starts
556 * after the tree, parent, author, committer
557 * information followed by "\n\n".
558 */
559 p = strstr(msg.message, "\n\n");
560 if (p) {
561 p += 2;
562 strbuf_addstr(&msgbuf, p);
563 }
564
565 if (opts->record_origin) {
566 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
567 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
568 strbuf_addstr(&msgbuf, ")\n");
569 }
570 }
571
572 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REVERT) {
573 res = do_recursive_merge(base, next, base_label, next_label,
574 head, &msgbuf, opts);
575 write_message(&msgbuf, defmsg);
576 } else {
577 struct commit_list *common = NULL;
578 struct commit_list *remotes = NULL;
579
580 write_message(&msgbuf, defmsg);
581
582 commit_list_insert(base, &common);
583 commit_list_insert(next, &remotes);
584 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
585 common, sha1_to_hex(head), remotes);
586 free_commit_list(common);
587 free_commit_list(remotes);
588 }
589
590 /*
591 * If the merge was clean or if it failed due to conflict, we write
592 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
593 * However, if the merge did not even start, then we don't want to
594 * write it at all.
595 */
596 if (opts->action == CHERRY_PICK && !opts->no_commit && (res == 0 || res == 1))
597 write_cherry_pick_head(commit);
598
599 if (res) {
600 error(opts->action == REVERT
601 ? _("could not revert %s... %s")
602 : _("could not apply %s... %s"),
603 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
604 msg.subject);
605 print_advice(res == 1);
606 rerere(opts->allow_rerere_auto);
607 } else {
608 if (!opts->no_commit)
609 res = run_git_commit(defmsg, opts);
610 }
611
612 free_message(&msg);
613 free(defmsg);
614
615 return res;
616}
617
618static void prepare_revs(struct rev_info *revs, struct replay_opts *opts)
619{
620 int argc;
621
622 init_revisions(revs, NULL);
623 revs->no_walk = 1;
624 if (opts->action != REVERT)
625 revs->reverse = 1;
626
627 argc = setup_revisions(opts->commit_argc, opts->commit_argv, revs, NULL);
628 if (argc > 1)
629 usage(*revert_or_cherry_pick_usage(opts));
630
631 if (prepare_revision_walk(revs))
632 die(_("revision walk setup failed"));
633
634 if (!revs->commits)
635 die(_("empty commit set passed"));
636}
637
638static void read_and_refresh_cache(struct replay_opts *opts)
639{
640 static struct lock_file index_lock;
641 int index_fd = hold_locked_index(&index_lock, 0);
642 if (read_index_preload(&the_index, NULL) < 0)
643 die(_("git %s: failed to read the index"), action_name(opts));
644 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
645 if (the_index.cache_changed) {
646 if (write_index(&the_index, index_fd) ||
647 commit_locked_index(&index_lock))
648 die(_("git %s: failed to refresh the index"), action_name(opts));
649 }
650 rollback_lock_file(&index_lock);
651}
652
653/*
654 * Append a commit to the end of the commit_list.
655 *
656 * next starts by pointing to the variable that holds the head of an
657 * empty commit_list, and is updated to point to the "next" field of
658 * the last item on the list as new commits are appended.
659 *
660 * Usage example:
661 *
662 * struct commit_list *list;
663 * struct commit_list **next = &list;
664 *
665 * next = commit_list_append(c1, next);
666 * next = commit_list_append(c2, next);
667 * assert(commit_list_count(list) == 2);
668 * return list;
669 */
670static struct commit_list **commit_list_append(struct commit *commit,
671 struct commit_list **next)
672{
673 struct commit_list *new = xmalloc(sizeof(struct commit_list));
674 new->item = commit;
675 *next = new;
676 new->next = NULL;
677 return &new->next;
678}
679
680static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
681 struct replay_opts *opts)
682{
683 struct commit_list *cur = NULL;
684 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
685 const char *sha1_abbrev = NULL;
686 const char *action_str = opts->action == REVERT ? "revert" : "pick";
687
688 for (cur = todo_list; cur; cur = cur->next) {
689 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
690 if (get_message(cur->item, &msg))
691 return error(_("Cannot get commit message for %s"), sha1_abbrev);
692 strbuf_addf(buf, "%s %s %s\n", action_str, sha1_abbrev, msg.subject);
693 }
694 return 0;
695}
696
697static struct commit *parse_insn_line(char *start, struct replay_opts *opts)
698{
699 unsigned char commit_sha1[20];
700 char sha1_abbrev[40];
701 enum replay_action action;
702 int insn_len = 0;
703 char *p, *q;
704
705 if (!prefixcmp(start, "pick ")) {
706 action = CHERRY_PICK;
707 insn_len = strlen("pick");
708 p = start + insn_len + 1;
709 } else if (!prefixcmp(start, "revert ")) {
710 action = REVERT;
711 insn_len = strlen("revert");
712 p = start + insn_len + 1;
713 } else
714 return NULL;
715
716 q = strchr(p, ' ');
717 if (!q)
718 return NULL;
719 q++;
720
721 strlcpy(sha1_abbrev, p, q - p);
722
723 /*
724 * Verify that the action matches up with the one in
725 * opts; we don't support arbitrary instructions
726 */
727 if (action != opts->action) {
728 const char *action_str;
729 action_str = action == REVERT ? "revert" : "cherry-pick";
730 error(_("Cannot %s during a %s"), action_str, action_name(opts));
731 return NULL;
732 }
733
734 if (get_sha1(sha1_abbrev, commit_sha1) < 0)
735 return NULL;
736
737 return lookup_commit_reference(commit_sha1);
738}
739
740static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
741 struct replay_opts *opts)
742{
743 struct commit_list **next = todo_list;
744 struct commit *commit;
745 char *p = buf;
746 int i;
747
748 for (i = 1; *p; i++) {
749 commit = parse_insn_line(p, opts);
750 if (!commit)
751 return error(_("Could not parse line %d."), i);
752 next = commit_list_append(commit, next);
753 p = strchrnul(p, '\n');
754 if (*p)
755 p++;
756 }
757 if (!*todo_list)
758 return error(_("No commits parsed."));
759 return 0;
760}
761
762static void read_populate_todo(struct commit_list **todo_list,
763 struct replay_opts *opts)
764{
765 const char *todo_file = git_path(SEQ_TODO_FILE);
766 struct strbuf buf = STRBUF_INIT;
767 int fd, res;
768
769 fd = open(todo_file, O_RDONLY);
770 if (fd < 0)
771 die_errno(_("Could not open %s"), todo_file);
772 if (strbuf_read(&buf, fd, 0) < 0) {
773 close(fd);
774 strbuf_release(&buf);
775 die(_("Could not read %s."), todo_file);
776 }
777 close(fd);
778
779 res = parse_insn_buffer(buf.buf, todo_list, opts);
780 strbuf_release(&buf);
781 if (res)
782 die(_("Unusable instruction sheet: %s"), todo_file);
783}
784
785static int populate_opts_cb(const char *key, const char *value, void *data)
786{
787 struct replay_opts *opts = data;
788 int error_flag = 1;
789
790 if (!value)
791 error_flag = 0;
792 else if (!strcmp(key, "options.no-commit"))
793 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
794 else if (!strcmp(key, "options.edit"))
795 opts->edit = git_config_bool_or_int(key, value, &error_flag);
796 else if (!strcmp(key, "options.signoff"))
797 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
798 else if (!strcmp(key, "options.record-origin"))
799 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
800 else if (!strcmp(key, "options.allow-ff"))
801 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
802 else if (!strcmp(key, "options.mainline"))
803 opts->mainline = git_config_int(key, value);
804 else if (!strcmp(key, "options.strategy"))
805 git_config_string(&opts->strategy, key, value);
806 else if (!strcmp(key, "options.strategy-option")) {
807 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
808 opts->xopts[opts->xopts_nr++] = xstrdup(value);
809 } else
810 return error(_("Invalid key: %s"), key);
811
812 if (!error_flag)
813 return error(_("Invalid value for %s: %s"), key, value);
814
815 return 0;
816}
817
818static void read_populate_opts(struct replay_opts **opts_ptr)
819{
820 const char *opts_file = git_path(SEQ_OPTS_FILE);
821
822 if (!file_exists(opts_file))
823 return;
824 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
825 die(_("Malformed options sheet: %s"), opts_file);
826}
827
828static void walk_revs_populate_todo(struct commit_list **todo_list,
829 struct replay_opts *opts)
830{
831 struct rev_info revs;
832 struct commit *commit;
833 struct commit_list **next;
834
835 prepare_revs(&revs, opts);
836
837 next = todo_list;
838 while ((commit = get_revision(&revs)))
839 next = commit_list_append(commit, next);
840}
841
842static int create_seq_dir(void)
843{
844 const char *seq_dir = git_path(SEQ_DIR);
845
846 if (file_exists(seq_dir))
847 return error(_("%s already exists."), seq_dir);
848 else if (mkdir(seq_dir, 0777) < 0)
849 die_errno(_("Could not create sequencer directory %s"), seq_dir);
850 return 0;
851}
852
853static void save_head(const char *head)
854{
855 const char *head_file = git_path(SEQ_HEAD_FILE);
856 static struct lock_file head_lock;
857 struct strbuf buf = STRBUF_INIT;
858 int fd;
859
860 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
861 strbuf_addf(&buf, "%s\n", head);
862 if (write_in_full(fd, buf.buf, buf.len) < 0)
863 die_errno(_("Could not write to %s"), head_file);
864 if (commit_lock_file(&head_lock) < 0)
865 die(_("Error wrapping up %s."), head_file);
866}
867
868static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
869{
870 const char *todo_file = git_path(SEQ_TODO_FILE);
871 static struct lock_file todo_lock;
872 struct strbuf buf = STRBUF_INIT;
873 int fd;
874
875 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
876 if (format_todo(&buf, todo_list, opts) < 0)
877 die(_("Could not format %s."), todo_file);
878 if (write_in_full(fd, buf.buf, buf.len) < 0) {
879 strbuf_release(&buf);
880 die_errno(_("Could not write to %s"), todo_file);
881 }
882 if (commit_lock_file(&todo_lock) < 0) {
883 strbuf_release(&buf);
884 die(_("Error wrapping up %s."), todo_file);
885 }
886 strbuf_release(&buf);
887}
888
889static void save_opts(struct replay_opts *opts)
890{
891 const char *opts_file = git_path(SEQ_OPTS_FILE);
892
893 if (opts->no_commit)
894 git_config_set_in_file(opts_file, "options.no-commit", "true");
895 if (opts->edit)
896 git_config_set_in_file(opts_file, "options.edit", "true");
897 if (opts->signoff)
898 git_config_set_in_file(opts_file, "options.signoff", "true");
899 if (opts->record_origin)
900 git_config_set_in_file(opts_file, "options.record-origin", "true");
901 if (opts->allow_ff)
902 git_config_set_in_file(opts_file, "options.allow-ff", "true");
903 if (opts->mainline) {
904 struct strbuf buf = STRBUF_INIT;
905 strbuf_addf(&buf, "%d", opts->mainline);
906 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
907 strbuf_release(&buf);
908 }
909 if (opts->strategy)
910 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
911 if (opts->xopts) {
912 int i;
913 for (i = 0; i < opts->xopts_nr; i++)
914 git_config_set_multivar_in_file(opts_file,
915 "options.strategy-option",
916 opts->xopts[i], "^$", 0);
917 }
918}
919
920static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
921{
922 struct commit_list *cur;
923 int res;
924
925 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
926 if (opts->allow_ff)
927 assert(!(opts->signoff || opts->no_commit ||
928 opts->record_origin || opts->edit));
929 read_and_refresh_cache(opts);
930
931 for (cur = todo_list; cur; cur = cur->next) {
932 save_todo(cur, opts);
933 res = do_pick_commit(cur->item, opts);
934 if (res) {
935 if (!cur->next)
936 /*
937 * An error was encountered while
938 * picking the last commit; the
939 * sequencer state is useless now --
940 * the user simply needs to resolve
941 * the conflict and commit
942 */
943 remove_sequencer_state(0);
944 return res;
945 }
946 }
947
948 /*
949 * Sequence of picks finished successfully; cleanup by
950 * removing the .git/sequencer directory
951 */
952 remove_sequencer_state(1);
953 return 0;
954}
955
956static int pick_revisions(struct replay_opts *opts)
957{
958 struct commit_list *todo_list = NULL;
959 unsigned char sha1[20];
960
961 read_and_refresh_cache(opts);
962
963 /*
964 * Decide what to do depending on the arguments; a fresh
965 * cherry-pick should be handled differently from an existing
966 * one that is being continued
967 */
968 if (opts->subcommand == REPLAY_RESET) {
969 remove_sequencer_state(1);
970 return 0;
971 } else if (opts->subcommand == REPLAY_CONTINUE) {
972 if (!file_exists(git_path(SEQ_TODO_FILE)))
973 goto error;
974 read_populate_opts(&opts);
975 read_populate_todo(&todo_list, opts);
976
977 /* Verify that the conflict has been resolved */
978 if (!index_differs_from("HEAD", 0))
979 todo_list = todo_list->next;
980 } else {
981 /*
982 * Start a new cherry-pick/ revert sequence; but
983 * first, make sure that an existing one isn't in
984 * progress
985 */
986
987 walk_revs_populate_todo(&todo_list, opts);
988 if (create_seq_dir() < 0) {
989 error(_("A cherry-pick or revert is in progress."));
990 advise(_("Use --continue to continue the operation"));
991 advise(_("or --reset to forget about it"));
992 return -1;
993 }
994 if (get_sha1("HEAD", sha1)) {
995 if (opts->action == REVERT)
996 return error(_("Can't revert as initial commit"));
997 return error(_("Can't cherry-pick into empty head"));
998 }
999 save_head(sha1_to_hex(sha1));
1000 save_opts(opts);
1001 }
1002 return pick_commits(todo_list, opts);
1003error:
1004 return error(_("No %s in progress"), action_name(opts));
1005}
1006
1007int cmd_revert(int argc, const char **argv, const char *prefix)
1008{
1009 struct replay_opts opts;
1010 int res;
1011
1012 memset(&opts, 0, sizeof(opts));
1013 if (isatty(0))
1014 opts.edit = 1;
1015 opts.action = REVERT;
1016 git_config(git_default_config, NULL);
1017 parse_args(argc, argv, &opts);
1018 res = pick_revisions(&opts);
1019 if (res < 0)
1020 die(_("revert failed"));
1021 return res;
1022}
1023
1024int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
1025{
1026 struct replay_opts opts;
1027 int res;
1028
1029 memset(&opts, 0, sizeof(opts));
1030 opts.action = CHERRY_PICK;
1031 git_config(git_default_config, NULL);
1032 parse_args(argc, argv, &opts);
1033 res = pick_revisions(&opts);
1034 if (res < 0)
1035 die(_("cherry-pick failed"));
1036 return res;
1037}