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