revert: add "--strategy" option to choose merge strategy
[git.git] / builtin / revert.c
blobb70f4b0af364caa597ab24630fc43fb41438ca2c
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"
10 #include "parse-options.h"
11 #include "cache-tree.h"
12 #include "diff.h"
13 #include "revision.h"
14 #include "rerere.h"
15 #include "merge-recursive.h"
18 * This implements the builtins revert and cherry-pick.
20 * Copyright (c) 2007 Johannes E. Schindelin
22 * Based on git-revert.sh, which is
24 * Copyright (c) 2005 Linus Torvalds
25 * Copyright (c) 2005 Junio C Hamano
28 static const char * const revert_usage[] = {
29 "git revert [options] <commit-ish>",
30 NULL
33 static const char * const cherry_pick_usage[] = {
34 "git cherry-pick [options] <commit-ish>",
35 NULL
38 static int edit, no_replay, no_commit, mainline, signoff;
39 static enum { REVERT, CHERRY_PICK } action;
40 static struct commit *commit;
41 static const char *commit_name;
42 static int allow_rerere_auto;
44 static const char *me;
45 static const char *strategy;
47 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
49 static char *get_encoding(const char *message);
51 static void parse_args(int argc, const char **argv)
53 const char * const * usage_str =
54 action == REVERT ? revert_usage : cherry_pick_usage;
55 unsigned char sha1[20];
56 int noop;
57 struct option options[] = {
58 OPT_BOOLEAN('n', "no-commit", &no_commit, "don't automatically commit"),
59 OPT_BOOLEAN('e', "edit", &edit, "edit the commit message"),
60 OPT_BOOLEAN('x', NULL, &no_replay, "append commit name when cherry-picking"),
61 OPT_BOOLEAN('r', NULL, &noop, "no-op (backward compatibility)"),
62 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
63 OPT_INTEGER('m', "mainline", &mainline, "parent number"),
64 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
65 OPT_STRING(0, "strategy", &strategy, "strategy", "merge strategy"),
66 OPT_END(),
69 if (parse_options(argc, argv, NULL, options, usage_str, 0) != 1)
70 usage_with_options(usage_str, options);
72 commit_name = argv[0];
73 if (get_sha1(commit_name, sha1))
74 die ("Cannot find '%s'", commit_name);
75 commit = lookup_commit_reference(sha1);
76 if (!commit)
77 exit(1);
80 struct commit_message {
81 char *parent_label;
82 const char *label;
83 const char *subject;
84 char *reencoded_message;
85 const char *message;
88 static int get_message(const char *raw_message, struct commit_message *out)
90 const char *encoding;
91 const char *p, *abbrev, *eol;
92 char *q;
93 int abbrev_len, oneline_len;
95 if (!raw_message)
96 return -1;
97 encoding = get_encoding(raw_message);
98 if (!encoding)
99 encoding = "UTF-8";
100 if (!git_commit_encoding)
101 git_commit_encoding = "UTF-8";
102 if ((out->reencoded_message = reencode_string(raw_message,
103 git_commit_encoding, encoding)))
104 out->message = out->reencoded_message;
106 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
107 abbrev_len = strlen(abbrev);
109 /* Find beginning and end of commit subject. */
110 p = out->message;
111 while (*p && (*p != '\n' || p[1] != '\n'))
112 p++;
113 if (*p) {
114 p += 2;
115 for (eol = p + 1; *eol && *eol != '\n'; eol++)
116 ; /* do nothing */
117 } else
118 eol = p;
119 oneline_len = eol - p;
121 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
122 strlen("... ") + oneline_len + 1);
123 q = out->parent_label;
124 q = mempcpy(q, "parent of ", strlen("parent of "));
125 out->label = q;
126 q = mempcpy(q, abbrev, abbrev_len);
127 q = mempcpy(q, "... ", strlen("... "));
128 out->subject = q;
129 q = mempcpy(q, p, oneline_len);
130 *q = '\0';
131 return 0;
134 static void free_message(struct commit_message *msg)
136 free(msg->parent_label);
137 free(msg->reencoded_message);
140 static char *get_encoding(const char *message)
142 const char *p = message, *eol;
144 if (!p)
145 die ("Could not read commit message of %s",
146 sha1_to_hex(commit->object.sha1));
147 while (*p && *p != '\n') {
148 for (eol = p + 1; *eol && *eol != '\n'; eol++)
149 ; /* do nothing */
150 if (!prefixcmp(p, "encoding ")) {
151 char *result = xmalloc(eol - 8 - p);
152 strlcpy(result, p + 9, eol - 8 - p);
153 return result;
155 p = eol;
156 if (*p == '\n')
157 p++;
159 return NULL;
162 static void add_message_to_msg(struct strbuf *msgbuf, const char *message)
164 const char *p = message;
165 while (*p && (*p != '\n' || p[1] != '\n'))
166 p++;
168 if (!*p)
169 strbuf_addstr(msgbuf, sha1_to_hex(commit->object.sha1));
171 p += 2;
172 strbuf_addstr(msgbuf, p);
175 static void set_author_ident_env(const char *message)
177 const char *p = message;
178 if (!p)
179 die ("Could not read commit message of %s",
180 sha1_to_hex(commit->object.sha1));
181 while (*p && *p != '\n') {
182 const char *eol;
184 for (eol = p; *eol && *eol != '\n'; eol++)
185 ; /* do nothing */
186 if (!prefixcmp(p, "author ")) {
187 char *line, *pend, *email, *timestamp;
189 p += 7;
190 line = xmemdupz(p, eol - p);
191 email = strchr(line, '<');
192 if (!email)
193 die ("Could not extract author email from %s",
194 sha1_to_hex(commit->object.sha1));
195 if (email == line)
196 pend = line;
197 else
198 for (pend = email; pend != line + 1 &&
199 isspace(pend[-1]); pend--);
200 ; /* do nothing */
201 *pend = '\0';
202 email++;
203 timestamp = strchr(email, '>');
204 if (!timestamp)
205 die ("Could not extract author time from %s",
206 sha1_to_hex(commit->object.sha1));
207 *timestamp = '\0';
208 for (timestamp++; *timestamp && isspace(*timestamp);
209 timestamp++)
210 ; /* do nothing */
211 setenv("GIT_AUTHOR_NAME", line, 1);
212 setenv("GIT_AUTHOR_EMAIL", email, 1);
213 setenv("GIT_AUTHOR_DATE", timestamp, 1);
214 free(line);
215 return;
217 p = eol;
218 if (*p == '\n')
219 p++;
221 die ("No author information found in %s",
222 sha1_to_hex(commit->object.sha1));
225 static char *help_msg(const char *name)
227 struct strbuf helpbuf = STRBUF_INIT;
228 char *msg = getenv("GIT_CHERRY_PICK_HELP");
230 if (msg)
231 return msg;
233 strbuf_addstr(&helpbuf, " After resolving the conflicts,\n"
234 "mark the corrected paths with 'git add <paths>' or 'git rm <paths>'\n"
235 "and commit the result");
237 if (action == CHERRY_PICK) {
238 strbuf_addf(&helpbuf, " with: \n"
239 "\n"
240 " git commit -c %s\n",
241 name);
243 else
244 strbuf_addch(&helpbuf, '.');
245 return strbuf_detach(&helpbuf, NULL);
248 static void write_message(struct strbuf *msgbuf, const char *filename)
250 static struct lock_file msg_file;
252 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
253 LOCK_DIE_ON_ERROR);
254 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
255 die_errno("Could not write to %s.", filename);
256 strbuf_release(msgbuf);
257 if (commit_lock_file(&msg_file) < 0)
258 die("Error wrapping up %s", filename);
261 static struct tree *empty_tree(void)
263 struct tree *tree = xcalloc(1, sizeof(struct tree));
265 tree->object.parsed = 1;
266 tree->object.type = OBJ_TREE;
267 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
268 return tree;
271 static NORETURN void die_dirty_index(const char *me)
273 if (read_cache_unmerged()) {
274 die_resolve_conflict(me);
275 } else {
276 if (advice_commit_before_merge)
277 die("Your local changes would be overwritten by %s.\n"
278 "Please, commit your changes or stash them to proceed.", me);
279 else
280 die("Your local changes would be overwritten by %s.\n", me);
284 static void do_recursive_merge(struct commit *base, struct commit *next,
285 const char *base_label, const char *next_label,
286 unsigned char *head, struct strbuf *msgbuf,
287 char *defmsg)
289 struct merge_options o;
290 struct tree *result, *next_tree, *base_tree, *head_tree;
291 int clean, index_fd;
292 static struct lock_file index_lock;
294 index_fd = hold_locked_index(&index_lock, 1);
296 read_cache();
297 init_merge_options(&o);
298 o.ancestor = base ? base_label : "(empty tree)";
299 o.branch1 = "HEAD";
300 o.branch2 = next ? next_label : "(empty tree)";
302 head_tree = parse_tree_indirect(head);
303 next_tree = next ? next->tree : empty_tree();
304 base_tree = base ? base->tree : empty_tree();
306 clean = merge_trees(&o,
307 head_tree,
308 next_tree, base_tree, &result);
310 if (active_cache_changed &&
311 (write_cache(index_fd, active_cache, active_nr) ||
312 commit_locked_index(&index_lock)))
313 die("%s: Unable to write new index file", me);
314 rollback_lock_file(&index_lock);
316 if (!clean) {
317 int i;
318 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
319 for (i = 0; i < active_nr;) {
320 struct cache_entry *ce = active_cache[i++];
321 if (ce_stage(ce)) {
322 strbuf_addch(msgbuf, '\t');
323 strbuf_addstr(msgbuf, ce->name);
324 strbuf_addch(msgbuf, '\n');
325 while (i < active_nr && !strcmp(ce->name,
326 active_cache[i]->name))
327 i++;
330 write_message(msgbuf, defmsg);
331 fprintf(stderr, "Automatic %s failed.%s\n",
332 me, help_msg(commit_name));
333 rerere(allow_rerere_auto);
334 exit(1);
336 write_message(msgbuf, defmsg);
337 fprintf(stderr, "Finished one %s.\n", me);
340 static int revert_or_cherry_pick(int argc, const char **argv)
342 unsigned char head[20];
343 struct commit *base, *next, *parent;
344 const char *base_label, *next_label;
345 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
346 char *defmsg = git_pathdup("MERGE_MSG");
347 struct strbuf msgbuf = STRBUF_INIT;
349 git_config(git_default_config, NULL);
350 me = action == REVERT ? "revert" : "cherry-pick";
351 setenv(GIT_REFLOG_ACTION, me, 0);
352 parse_args(argc, argv);
354 /* this is copied from the shell script, but it's never triggered... */
355 if (action == REVERT && !no_replay)
356 die("revert is incompatible with replay");
358 if (read_cache() < 0)
359 die("git %s: failed to read the index", me);
360 if (no_commit) {
362 * We do not intend to commit immediately. We just want to
363 * merge the differences in, so let's compute the tree
364 * that represents the "current" state for merge-recursive
365 * to work on.
367 if (write_cache_as_tree(head, 0, NULL))
368 die ("Your index file is unmerged.");
369 } else {
370 if (get_sha1("HEAD", head))
371 die ("You do not have a valid HEAD");
372 if (index_differs_from("HEAD", 0))
373 die_dirty_index(me);
375 discard_cache();
377 if (!commit->parents) {
378 if (action == REVERT)
379 die ("Cannot revert a root commit");
380 parent = NULL;
382 else if (commit->parents->next) {
383 /* Reverting or cherry-picking a merge commit */
384 int cnt;
385 struct commit_list *p;
387 if (!mainline)
388 die("Commit %s is a merge but no -m option was given.",
389 sha1_to_hex(commit->object.sha1));
391 for (cnt = 1, p = commit->parents;
392 cnt != mainline && p;
393 cnt++)
394 p = p->next;
395 if (cnt != mainline || !p)
396 die("Commit %s does not have parent %d",
397 sha1_to_hex(commit->object.sha1), mainline);
398 parent = p->item;
399 } else if (0 < mainline)
400 die("Mainline was specified but commit %s is not a merge.",
401 sha1_to_hex(commit->object.sha1));
402 else
403 parent = commit->parents->item;
405 if (parent && parse_commit(parent) < 0)
406 die("%s: cannot parse parent commit %s",
407 me, sha1_to_hex(parent->object.sha1));
409 if (get_message(commit->buffer, &msg) != 0)
410 die("Cannot get commit message for %s",
411 sha1_to_hex(commit->object.sha1));
414 * "commit" is an existing commit. We would want to apply
415 * the difference it introduces since its first parent "prev"
416 * on top of the current HEAD if we are cherry-pick. Or the
417 * reverse of it if we are revert.
420 if (action == REVERT) {
421 base = commit;
422 base_label = msg.label;
423 next = parent;
424 next_label = msg.parent_label;
425 strbuf_addstr(&msgbuf, "Revert \"");
426 strbuf_addstr(&msgbuf, msg.subject);
427 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
428 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
430 if (commit->parents->next) {
431 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
432 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
434 strbuf_addstr(&msgbuf, ".\n");
435 } else {
436 base = parent;
437 base_label = msg.parent_label;
438 next = commit;
439 next_label = msg.label;
440 set_author_ident_env(msg.message);
441 add_message_to_msg(&msgbuf, msg.message);
442 if (no_replay) {
443 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
444 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
445 strbuf_addstr(&msgbuf, ")\n");
449 if (!strategy || !strcmp(strategy, "recursive") || action == REVERT)
450 do_recursive_merge(base, next, base_label, next_label,
451 head, &msgbuf, defmsg);
452 else {
453 int res;
454 struct commit_list *common = NULL;
455 struct commit_list *remotes = NULL;
456 write_message(&msgbuf, defmsg);
457 commit_list_insert(base, &common);
458 commit_list_insert(next, &remotes);
459 res = try_merge_command(strategy, common,
460 sha1_to_hex(head), remotes);
461 free_commit_list(common);
462 free_commit_list(remotes);
463 if (res) {
464 fprintf(stderr, "Automatic %s with strategy %s failed.%s\n",
465 me, strategy, help_msg(commit_name));
466 rerere(allow_rerere_auto);
467 exit(1);
473 * If we are cherry-pick, and if the merge did not result in
474 * hand-editing, we will hit this commit and inherit the original
475 * author date and name.
476 * If we are revert, or if our cherry-pick results in a hand merge,
477 * we had better say that the current user is responsible for that.
480 if (!no_commit) {
481 /* 6 is max possible length of our args array including NULL */
482 const char *args[6];
483 int i = 0;
484 args[i++] = "commit";
485 args[i++] = "-n";
486 if (signoff)
487 args[i++] = "-s";
488 if (!edit) {
489 args[i++] = "-F";
490 args[i++] = defmsg;
492 args[i] = NULL;
493 return execv_git_cmd(args);
495 free_message(&msg);
496 free(defmsg);
498 return 0;
501 int cmd_revert(int argc, const char **argv, const char *prefix)
503 if (isatty(0))
504 edit = 1;
505 no_replay = 1;
506 action = REVERT;
507 return revert_or_cherry_pick(argc, argv);
510 int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
512 no_replay = 0;
513 action = CHERRY_PICK;
514 return revert_or_cherry_pick(argc, argv);