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