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