]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/revert.c
Merge branch 'tm/completion-push-set-upstream'
[thirdparty/git.git] / builtin / revert.c
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
30 static const char * const revert_usage[] = {
31 "git revert [options] <commit-ish>",
32 "git revert <subcommand>",
33 NULL
34 };
35
36 static const char * const cherry_pick_usage[] = {
37 "git cherry-pick [options] <commit-ish>",
38 "git cherry-pick <subcommand>",
39 NULL
40 };
41
42 enum replay_action { REVERT, CHERRY_PICK };
43 enum replay_subcommand { REPLAY_NONE, REPLAY_RESET, REPLAY_CONTINUE };
44
45 struct 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
69 static const char *action_name(const struct replay_opts *opts)
70 {
71 return opts->action == REVERT ? "revert" : "cherry-pick";
72 }
73
74 static char *get_encoding(const char *message);
75
76 static 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
81 static 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
95 static 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
111 static 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
132 static 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
215 struct commit_message {
216 char *parent_label;
217 const char *label;
218 const char *subject;
219 char *reencoded_message;
220 const char *message;
221 };
222
223 static 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
264 static void free_message(struct commit_message *msg)
265 {
266 free(msg->parent_label);
267 free(msg->reencoded_message);
268 }
269
270 static 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
289 static void write_cherry_pick_head(struct commit *commit)
290 {
291 int fd;
292 struct strbuf buf = STRBUF_INIT;
293
294 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
295
296 fd = open(git_path("CHERRY_PICK_HEAD"), O_WRONLY | O_CREAT, 0666);
297 if (fd < 0)
298 die_errno(_("Could not open '%s' for writing"),
299 git_path("CHERRY_PICK_HEAD"));
300 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
301 die_errno(_("Could not write to '%s'"), git_path("CHERRY_PICK_HEAD"));
302 strbuf_release(&buf);
303 }
304
305 static void print_advice(void)
306 {
307 char *msg = getenv("GIT_CHERRY_PICK_HELP");
308
309 if (msg) {
310 fprintf(stderr, "%s\n", msg);
311 /*
312 * A conflict has occured but the porcelain
313 * (typically rebase --interactive) wants to take care
314 * of the commit itself so remove CHERRY_PICK_HEAD
315 */
316 unlink(git_path("CHERRY_PICK_HEAD"));
317 return;
318 }
319
320 advise("after resolving the conflicts, mark the corrected paths");
321 advise("with 'git add <paths>' or 'git rm <paths>'");
322 advise("and commit the result with 'git commit'");
323 }
324
325 static void write_message(struct strbuf *msgbuf, const char *filename)
326 {
327 static struct lock_file msg_file;
328
329 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
330 LOCK_DIE_ON_ERROR);
331 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
332 die_errno(_("Could not write to %s."), filename);
333 strbuf_release(msgbuf);
334 if (commit_lock_file(&msg_file) < 0)
335 die(_("Error wrapping up %s"), filename);
336 }
337
338 static struct tree *empty_tree(void)
339 {
340 return lookup_tree((const unsigned char *)EMPTY_TREE_SHA1_BIN);
341 }
342
343 static int error_dirty_index(struct replay_opts *opts)
344 {
345 if (read_cache_unmerged())
346 return error_resolve_conflict(action_name(opts));
347
348 /* Different translation strings for cherry-pick and revert */
349 if (opts->action == CHERRY_PICK)
350 error(_("Your local changes would be overwritten by cherry-pick."));
351 else
352 error(_("Your local changes would be overwritten by revert."));
353
354 if (advice_commit_before_merge)
355 advise(_("Commit your changes or stash them to proceed."));
356 return -1;
357 }
358
359 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
360 {
361 struct ref_lock *ref_lock;
362
363 read_cache();
364 if (checkout_fast_forward(from, to))
365 exit(1); /* the callee should have complained already */
366 ref_lock = lock_any_ref_for_update("HEAD", from, 0);
367 return write_ref_sha1(ref_lock, to, "cherry-pick");
368 }
369
370 static int do_recursive_merge(struct commit *base, struct commit *next,
371 const char *base_label, const char *next_label,
372 unsigned char *head, struct strbuf *msgbuf,
373 struct replay_opts *opts)
374 {
375 struct merge_options o;
376 struct tree *result, *next_tree, *base_tree, *head_tree;
377 int clean, index_fd;
378 const char **xopt;
379 static struct lock_file index_lock;
380
381 index_fd = hold_locked_index(&index_lock, 1);
382
383 read_cache();
384
385 init_merge_options(&o);
386 o.ancestor = base ? base_label : "(empty tree)";
387 o.branch1 = "HEAD";
388 o.branch2 = next ? next_label : "(empty tree)";
389
390 head_tree = parse_tree_indirect(head);
391 next_tree = next ? next->tree : empty_tree();
392 base_tree = base ? base->tree : empty_tree();
393
394 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
395 parse_merge_opt(&o, *xopt);
396
397 clean = merge_trees(&o,
398 head_tree,
399 next_tree, base_tree, &result);
400
401 if (active_cache_changed &&
402 (write_cache(index_fd, active_cache, active_nr) ||
403 commit_locked_index(&index_lock)))
404 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
405 die(_("%s: Unable to write new index file"), action_name(opts));
406 rollback_lock_file(&index_lock);
407
408 if (!clean) {
409 int i;
410 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
411 for (i = 0; i < active_nr;) {
412 struct cache_entry *ce = active_cache[i++];
413 if (ce_stage(ce)) {
414 strbuf_addch(msgbuf, '\t');
415 strbuf_addstr(msgbuf, ce->name);
416 strbuf_addch(msgbuf, '\n');
417 while (i < active_nr && !strcmp(ce->name,
418 active_cache[i]->name))
419 i++;
420 }
421 }
422 }
423
424 return !clean;
425 }
426
427 /*
428 * If we are cherry-pick, and if the merge did not result in
429 * hand-editing, we will hit this commit and inherit the original
430 * author date and name.
431 * If we are revert, or if our cherry-pick results in a hand merge,
432 * we had better say that the current user is responsible for that.
433 */
434 static int run_git_commit(const char *defmsg, struct replay_opts *opts)
435 {
436 /* 6 is max possible length of our args array including NULL */
437 const char *args[6];
438 int i = 0;
439
440 args[i++] = "commit";
441 args[i++] = "-n";
442 if (opts->signoff)
443 args[i++] = "-s";
444 if (!opts->edit) {
445 args[i++] = "-F";
446 args[i++] = defmsg;
447 }
448 args[i] = NULL;
449
450 return run_command_v_opt(args, RUN_GIT_CMD);
451 }
452
453 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
454 {
455 unsigned char head[20];
456 struct commit *base, *next, *parent;
457 const char *base_label, *next_label;
458 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
459 char *defmsg = NULL;
460 struct strbuf msgbuf = STRBUF_INIT;
461 int res;
462
463 if (opts->no_commit) {
464 /*
465 * We do not intend to commit immediately. We just want to
466 * merge the differences in, so let's compute the tree
467 * that represents the "current" state for merge-recursive
468 * to work on.
469 */
470 if (write_cache_as_tree(head, 0, NULL))
471 die (_("Your index file is unmerged."));
472 } else {
473 if (get_sha1("HEAD", head))
474 return error(_("You do not have a valid HEAD"));
475 if (index_differs_from("HEAD", 0))
476 return error_dirty_index(opts);
477 }
478 discard_cache();
479
480 if (!commit->parents) {
481 parent = NULL;
482 }
483 else if (commit->parents->next) {
484 /* Reverting or cherry-picking a merge commit */
485 int cnt;
486 struct commit_list *p;
487
488 if (!opts->mainline)
489 return error(_("Commit %s is a merge but no -m option was given."),
490 sha1_to_hex(commit->object.sha1));
491
492 for (cnt = 1, p = commit->parents;
493 cnt != opts->mainline && p;
494 cnt++)
495 p = p->next;
496 if (cnt != opts->mainline || !p)
497 return error(_("Commit %s does not have parent %d"),
498 sha1_to_hex(commit->object.sha1), opts->mainline);
499 parent = p->item;
500 } else if (0 < opts->mainline)
501 return error(_("Mainline was specified but commit %s is not a merge."),
502 sha1_to_hex(commit->object.sha1));
503 else
504 parent = commit->parents->item;
505
506 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
507 return fast_forward_to(commit->object.sha1, head);
508
509 if (parent && parse_commit(parent) < 0)
510 /* TRANSLATORS: The first %s will be "revert" or
511 "cherry-pick", the second %s a SHA1 */
512 return error(_("%s: cannot parse parent commit %s"),
513 action_name(opts), sha1_to_hex(parent->object.sha1));
514
515 if (get_message(commit, &msg) != 0)
516 return error(_("Cannot get commit message for %s"),
517 sha1_to_hex(commit->object.sha1));
518
519 /*
520 * "commit" is an existing commit. We would want to apply
521 * the difference it introduces since its first parent "prev"
522 * on top of the current HEAD if we are cherry-pick. Or the
523 * reverse of it if we are revert.
524 */
525
526 defmsg = git_pathdup("MERGE_MSG");
527
528 if (opts->action == REVERT) {
529 base = commit;
530 base_label = msg.label;
531 next = parent;
532 next_label = msg.parent_label;
533 strbuf_addstr(&msgbuf, "Revert \"");
534 strbuf_addstr(&msgbuf, msg.subject);
535 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
536 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
537
538 if (commit->parents && commit->parents->next) {
539 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
540 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
541 }
542 strbuf_addstr(&msgbuf, ".\n");
543 } else {
544 const char *p;
545
546 base = parent;
547 base_label = msg.parent_label;
548 next = commit;
549 next_label = msg.label;
550
551 /*
552 * Append the commit log message to msgbuf; it starts
553 * after the tree, parent, author, committer
554 * information followed by "\n\n".
555 */
556 p = strstr(msg.message, "\n\n");
557 if (p) {
558 p += 2;
559 strbuf_addstr(&msgbuf, p);
560 }
561
562 if (opts->record_origin) {
563 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
564 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
565 strbuf_addstr(&msgbuf, ")\n");
566 }
567 if (!opts->no_commit)
568 write_cherry_pick_head(commit);
569 }
570
571 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REVERT) {
572 res = do_recursive_merge(base, next, base_label, next_label,
573 head, &msgbuf, opts);
574 write_message(&msgbuf, defmsg);
575 } else {
576 struct commit_list *common = NULL;
577 struct commit_list *remotes = NULL;
578
579 write_message(&msgbuf, defmsg);
580
581 commit_list_insert(base, &common);
582 commit_list_insert(next, &remotes);
583 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
584 common, sha1_to_hex(head), remotes);
585 free_commit_list(common);
586 free_commit_list(remotes);
587 }
588
589 if (res) {
590 error(opts->action == REVERT
591 ? _("could not revert %s... %s")
592 : _("could not apply %s... %s"),
593 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
594 msg.subject);
595 print_advice();
596 rerere(opts->allow_rerere_auto);
597 } else {
598 if (!opts->no_commit)
599 res = run_git_commit(defmsg, opts);
600 }
601
602 free_message(&msg);
603 free(defmsg);
604
605 return res;
606 }
607
608 static void prepare_revs(struct rev_info *revs, struct replay_opts *opts)
609 {
610 int argc;
611
612 init_revisions(revs, NULL);
613 revs->no_walk = 1;
614 if (opts->action != REVERT)
615 revs->reverse = 1;
616
617 argc = setup_revisions(opts->commit_argc, opts->commit_argv, revs, NULL);
618 if (argc > 1)
619 usage(*revert_or_cherry_pick_usage(opts));
620
621 if (prepare_revision_walk(revs))
622 die(_("revision walk setup failed"));
623
624 if (!revs->commits)
625 die(_("empty commit set passed"));
626 }
627
628 static void read_and_refresh_cache(struct replay_opts *opts)
629 {
630 static struct lock_file index_lock;
631 int index_fd = hold_locked_index(&index_lock, 0);
632 if (read_index_preload(&the_index, NULL) < 0)
633 die(_("git %s: failed to read the index"), action_name(opts));
634 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
635 if (the_index.cache_changed) {
636 if (write_index(&the_index, index_fd) ||
637 commit_locked_index(&index_lock))
638 die(_("git %s: failed to refresh the index"), action_name(opts));
639 }
640 rollback_lock_file(&index_lock);
641 }
642
643 /*
644 * Append a commit to the end of the commit_list.
645 *
646 * next starts by pointing to the variable that holds the head of an
647 * empty commit_list, and is updated to point to the "next" field of
648 * the last item on the list as new commits are appended.
649 *
650 * Usage example:
651 *
652 * struct commit_list *list;
653 * struct commit_list **next = &list;
654 *
655 * next = commit_list_append(c1, next);
656 * next = commit_list_append(c2, next);
657 * assert(commit_list_count(list) == 2);
658 * return list;
659 */
660 static struct commit_list **commit_list_append(struct commit *commit,
661 struct commit_list **next)
662 {
663 struct commit_list *new = xmalloc(sizeof(struct commit_list));
664 new->item = commit;
665 *next = new;
666 new->next = NULL;
667 return &new->next;
668 }
669
670 static int format_todo(struct strbuf *buf, struct commit_list *todo_list,
671 struct replay_opts *opts)
672 {
673 struct commit_list *cur = NULL;
674 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
675 const char *sha1_abbrev = NULL;
676 const char *action_str = opts->action == REVERT ? "revert" : "pick";
677
678 for (cur = todo_list; cur; cur = cur->next) {
679 sha1_abbrev = find_unique_abbrev(cur->item->object.sha1, DEFAULT_ABBREV);
680 if (get_message(cur->item, &msg))
681 return error(_("Cannot get commit message for %s"), sha1_abbrev);
682 strbuf_addf(buf, "%s %s %s\n", action_str, sha1_abbrev, msg.subject);
683 }
684 return 0;
685 }
686
687 static struct commit *parse_insn_line(char *start, struct replay_opts *opts)
688 {
689 unsigned char commit_sha1[20];
690 char sha1_abbrev[40];
691 enum replay_action action;
692 int insn_len = 0;
693 char *p, *q;
694
695 if (!prefixcmp(start, "pick ")) {
696 action = CHERRY_PICK;
697 insn_len = strlen("pick");
698 p = start + insn_len + 1;
699 } else if (!prefixcmp(start, "revert ")) {
700 action = REVERT;
701 insn_len = strlen("revert");
702 p = start + insn_len + 1;
703 } else
704 return NULL;
705
706 q = strchr(p, ' ');
707 if (!q)
708 return NULL;
709 q++;
710
711 strlcpy(sha1_abbrev, p, q - p);
712
713 /*
714 * Verify that the action matches up with the one in
715 * opts; we don't support arbitrary instructions
716 */
717 if (action != opts->action) {
718 const char *action_str;
719 action_str = action == REVERT ? "revert" : "cherry-pick";
720 error(_("Cannot %s during a %s"), action_str, action_name(opts));
721 return NULL;
722 }
723
724 if (get_sha1(sha1_abbrev, commit_sha1) < 0)
725 return NULL;
726
727 return lookup_commit_reference(commit_sha1);
728 }
729
730 static int parse_insn_buffer(char *buf, struct commit_list **todo_list,
731 struct replay_opts *opts)
732 {
733 struct commit_list **next = todo_list;
734 struct commit *commit;
735 char *p = buf;
736 int i;
737
738 for (i = 1; *p; i++) {
739 commit = parse_insn_line(p, opts);
740 if (!commit)
741 return error(_("Could not parse line %d."), i);
742 next = commit_list_append(commit, next);
743 p = strchrnul(p, '\n');
744 if (*p)
745 p++;
746 }
747 if (!*todo_list)
748 return error(_("No commits parsed."));
749 return 0;
750 }
751
752 static void read_populate_todo(struct commit_list **todo_list,
753 struct replay_opts *opts)
754 {
755 const char *todo_file = git_path(SEQ_TODO_FILE);
756 struct strbuf buf = STRBUF_INIT;
757 int fd, res;
758
759 fd = open(todo_file, O_RDONLY);
760 if (fd < 0)
761 die_errno(_("Could not open %s."), todo_file);
762 if (strbuf_read(&buf, fd, 0) < 0) {
763 close(fd);
764 strbuf_release(&buf);
765 die(_("Could not read %s."), todo_file);
766 }
767 close(fd);
768
769 res = parse_insn_buffer(buf.buf, todo_list, opts);
770 strbuf_release(&buf);
771 if (res)
772 die(_("Unusable instruction sheet: %s"), todo_file);
773 }
774
775 static int populate_opts_cb(const char *key, const char *value, void *data)
776 {
777 struct replay_opts *opts = data;
778 int error_flag = 1;
779
780 if (!value)
781 error_flag = 0;
782 else if (!strcmp(key, "options.no-commit"))
783 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
784 else if (!strcmp(key, "options.edit"))
785 opts->edit = git_config_bool_or_int(key, value, &error_flag);
786 else if (!strcmp(key, "options.signoff"))
787 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
788 else if (!strcmp(key, "options.record-origin"))
789 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
790 else if (!strcmp(key, "options.allow-ff"))
791 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
792 else if (!strcmp(key, "options.mainline"))
793 opts->mainline = git_config_int(key, value);
794 else if (!strcmp(key, "options.strategy"))
795 git_config_string(&opts->strategy, key, value);
796 else if (!strcmp(key, "options.strategy-option")) {
797 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
798 opts->xopts[opts->xopts_nr++] = xstrdup(value);
799 } else
800 return error(_("Invalid key: %s"), key);
801
802 if (!error_flag)
803 return error(_("Invalid value for %s: %s"), key, value);
804
805 return 0;
806 }
807
808 static void read_populate_opts(struct replay_opts **opts_ptr)
809 {
810 const char *opts_file = git_path(SEQ_OPTS_FILE);
811
812 if (!file_exists(opts_file))
813 return;
814 if (git_config_from_file(populate_opts_cb, opts_file, *opts_ptr) < 0)
815 die(_("Malformed options sheet: %s"), opts_file);
816 }
817
818 static void walk_revs_populate_todo(struct commit_list **todo_list,
819 struct replay_opts *opts)
820 {
821 struct rev_info revs;
822 struct commit *commit;
823 struct commit_list **next;
824
825 prepare_revs(&revs, opts);
826
827 next = todo_list;
828 while ((commit = get_revision(&revs)))
829 next = commit_list_append(commit, next);
830 }
831
832 static int create_seq_dir(void)
833 {
834 const char *seq_dir = git_path(SEQ_DIR);
835
836 if (file_exists(seq_dir))
837 return error(_("%s already exists."), seq_dir);
838 else if (mkdir(seq_dir, 0777) < 0)
839 die_errno(_("Could not create sequencer directory '%s'."), seq_dir);
840 return 0;
841 }
842
843 static void save_head(const char *head)
844 {
845 const char *head_file = git_path(SEQ_HEAD_FILE);
846 static struct lock_file head_lock;
847 struct strbuf buf = STRBUF_INIT;
848 int fd;
849
850 fd = hold_lock_file_for_update(&head_lock, head_file, LOCK_DIE_ON_ERROR);
851 strbuf_addf(&buf, "%s\n", head);
852 if (write_in_full(fd, buf.buf, buf.len) < 0)
853 die_errno(_("Could not write to %s."), head_file);
854 if (commit_lock_file(&head_lock) < 0)
855 die(_("Error wrapping up %s."), head_file);
856 }
857
858 static void save_todo(struct commit_list *todo_list, struct replay_opts *opts)
859 {
860 const char *todo_file = git_path(SEQ_TODO_FILE);
861 static struct lock_file todo_lock;
862 struct strbuf buf = STRBUF_INIT;
863 int fd;
864
865 fd = hold_lock_file_for_update(&todo_lock, todo_file, LOCK_DIE_ON_ERROR);
866 if (format_todo(&buf, todo_list, opts) < 0)
867 die(_("Could not format %s."), todo_file);
868 if (write_in_full(fd, buf.buf, buf.len) < 0) {
869 strbuf_release(&buf);
870 die_errno(_("Could not write to %s."), todo_file);
871 }
872 if (commit_lock_file(&todo_lock) < 0) {
873 strbuf_release(&buf);
874 die(_("Error wrapping up %s."), todo_file);
875 }
876 strbuf_release(&buf);
877 }
878
879 static void save_opts(struct replay_opts *opts)
880 {
881 const char *opts_file = git_path(SEQ_OPTS_FILE);
882
883 if (opts->no_commit)
884 git_config_set_in_file(opts_file, "options.no-commit", "true");
885 if (opts->edit)
886 git_config_set_in_file(opts_file, "options.edit", "true");
887 if (opts->signoff)
888 git_config_set_in_file(opts_file, "options.signoff", "true");
889 if (opts->record_origin)
890 git_config_set_in_file(opts_file, "options.record-origin", "true");
891 if (opts->allow_ff)
892 git_config_set_in_file(opts_file, "options.allow-ff", "true");
893 if (opts->mainline) {
894 struct strbuf buf = STRBUF_INIT;
895 strbuf_addf(&buf, "%d", opts->mainline);
896 git_config_set_in_file(opts_file, "options.mainline", buf.buf);
897 strbuf_release(&buf);
898 }
899 if (opts->strategy)
900 git_config_set_in_file(opts_file, "options.strategy", opts->strategy);
901 if (opts->xopts) {
902 int i;
903 for (i = 0; i < opts->xopts_nr; i++)
904 git_config_set_multivar_in_file(opts_file,
905 "options.strategy-option",
906 opts->xopts[i], "^$", 0);
907 }
908 }
909
910 static int pick_commits(struct commit_list *todo_list, struct replay_opts *opts)
911 {
912 struct commit_list *cur;
913 int res;
914
915 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
916 if (opts->allow_ff)
917 assert(!(opts->signoff || opts->no_commit ||
918 opts->record_origin || opts->edit));
919 read_and_refresh_cache(opts);
920
921 for (cur = todo_list; cur; cur = cur->next) {
922 save_todo(cur, opts);
923 res = do_pick_commit(cur->item, opts);
924 if (res) {
925 if (!cur->next)
926 /*
927 * An error was encountered while
928 * picking the last commit; the
929 * sequencer state is useless now --
930 * the user simply needs to resolve
931 * the conflict and commit
932 */
933 remove_sequencer_state(0);
934 return res;
935 }
936 }
937
938 /*
939 * Sequence of picks finished successfully; cleanup by
940 * removing the .git/sequencer directory
941 */
942 remove_sequencer_state(1);
943 return 0;
944 }
945
946 static int pick_revisions(struct replay_opts *opts)
947 {
948 struct commit_list *todo_list = NULL;
949 unsigned char sha1[20];
950
951 read_and_refresh_cache(opts);
952
953 /*
954 * Decide what to do depending on the arguments; a fresh
955 * cherry-pick should be handled differently from an existing
956 * one that is being continued
957 */
958 if (opts->subcommand == REPLAY_RESET) {
959 remove_sequencer_state(1);
960 return 0;
961 } else if (opts->subcommand == REPLAY_CONTINUE) {
962 if (!file_exists(git_path(SEQ_TODO_FILE)))
963 goto error;
964 read_populate_opts(&opts);
965 read_populate_todo(&todo_list, opts);
966
967 /* Verify that the conflict has been resolved */
968 if (!index_differs_from("HEAD", 0))
969 todo_list = todo_list->next;
970 } else {
971 /*
972 * Start a new cherry-pick/ revert sequence; but
973 * first, make sure that an existing one isn't in
974 * progress
975 */
976
977 walk_revs_populate_todo(&todo_list, opts);
978 if (create_seq_dir() < 0) {
979 error(_("A cherry-pick or revert is in progress."));
980 advise(_("Use --continue to continue the operation"));
981 advise(_("or --reset to forget about it"));
982 return -1;
983 }
984 if (get_sha1("HEAD", sha1)) {
985 if (opts->action == REVERT)
986 return error(_("Can't revert as initial commit"));
987 return error(_("Can't cherry-pick into empty head"));
988 }
989 save_head(sha1_to_hex(sha1));
990 save_opts(opts);
991 }
992 return pick_commits(todo_list, opts);
993 error:
994 return error(_("No %s in progress"), action_name(opts));
995 }
996
997 int cmd_revert(int argc, const char **argv, const char *prefix)
998 {
999 struct replay_opts opts;
1000 int res;
1001
1002 memset(&opts, 0, sizeof(opts));
1003 if (isatty(0))
1004 opts.edit = 1;
1005 opts.action = REVERT;
1006 git_config(git_default_config, NULL);
1007 parse_args(argc, argv, &opts);
1008 res = pick_revisions(&opts);
1009 if (res < 0)
1010 die(_("revert failed"));
1011 return res;
1012 }
1013
1014 int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
1015 {
1016 struct replay_opts opts;
1017 int res;
1018
1019 memset(&opts, 0, sizeof(opts));
1020 opts.action = CHERRY_PICK;
1021 git_config(git_default_config, NULL);
1022 parse_args(argc, argv, &opts);
1023 res = pick_revisions(&opts);
1024 if (res < 0)
1025 die(_("cherry-pick failed"));
1026 return res;
1027 }