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