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