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