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