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