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