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