git-gui: fix PATH environment for mingw development environment
[git/dscho.git] / builtin / revert.c
blobbbaa937ab062826c2fb5540874bea4e1d1a30878
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"
16 #include "refs.h"
19 * This implements the builtins revert and cherry-pick.
21 * Copyright (c) 2007 Johannes E. Schindelin
23 * Based on git-revert.sh, which is
25 * Copyright (c) 2005 Linus Torvalds
26 * Copyright (c) 2005 Junio C Hamano
29 static const char * const revert_usage[] = {
30 "git revert [options] <commit-ish>",
31 NULL
34 static const char * const cherry_pick_usage[] = {
35 "git cherry-pick [options] <commit-ish>",
36 NULL
39 static int edit, no_replay, no_commit, mainline, signoff, allow_ff;
40 static enum { REVERT, CHERRY_PICK } action;
41 static struct commit *commit;
42 static const char *commit_name;
43 static int allow_rerere_auto;
45 static const char *me;
46 static const char *strategy;
48 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
50 static char *get_encoding(const char *message);
52 static void parse_args(int argc, const char **argv)
54 const char * const * usage_str =
55 action == REVERT ? revert_usage : cherry_pick_usage;
56 unsigned char sha1[20];
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"),
61 OPT_BOOLEAN('x', NULL, &no_replay, "append commit name when cherry-picking"),
62 OPT_BOOLEAN('r', NULL, &noop, "no-op (backward compatibility)"),
63 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
64 OPT_INTEGER('m', "mainline", &mainline, "parent number"),
65 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
66 OPT_STRING(0, "strategy", &strategy, "strategy", "merge strategy"),
67 OPT_END(),
68 OPT_END(),
69 OPT_END(),
72 if (action == CHERRY_PICK) {
73 struct option cp_extra[] = {
74 OPT_BOOLEAN(0, "ff", &allow_ff, "allow fast-forward"),
75 OPT_END(),
77 if (parse_options_concat(options, ARRAY_SIZE(options), cp_extra))
78 die("program error");
81 if (parse_options(argc, argv, NULL, options, usage_str, 0) != 1)
82 usage_with_options(usage_str, options);
84 commit_name = argv[0];
85 if (get_sha1(commit_name, sha1))
86 die ("Cannot find '%s'", commit_name);
87 commit = lookup_commit_reference(sha1);
88 if (!commit)
89 exit(1);
92 struct commit_message {
93 char *parent_label;
94 const char *label;
95 const char *subject;
96 char *reencoded_message;
97 const char *message;
100 static int get_message(const char *raw_message, struct commit_message *out)
102 const char *encoding;
103 const char *p, *abbrev, *eol;
104 char *q;
105 int abbrev_len, oneline_len;
107 if (!raw_message)
108 return -1;
109 encoding = get_encoding(raw_message);
110 if (!encoding)
111 encoding = "UTF-8";
112 if (!git_commit_encoding)
113 git_commit_encoding = "UTF-8";
114 if ((out->reencoded_message = reencode_string(raw_message,
115 git_commit_encoding, encoding)))
116 out->message = out->reencoded_message;
118 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
119 abbrev_len = strlen(abbrev);
121 /* Find beginning and end of commit subject. */
122 p = out->message;
123 while (*p && (*p != '\n' || p[1] != '\n'))
124 p++;
125 if (*p) {
126 p += 2;
127 for (eol = p + 1; *eol && *eol != '\n'; eol++)
128 ; /* do nothing */
129 } else
130 eol = p;
131 oneline_len = eol - p;
133 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
134 strlen("... ") + oneline_len + 1);
135 q = out->parent_label;
136 q = mempcpy(q, "parent of ", strlen("parent of "));
137 out->label = q;
138 q = mempcpy(q, abbrev, abbrev_len);
139 q = mempcpy(q, "... ", strlen("... "));
140 out->subject = q;
141 q = mempcpy(q, p, oneline_len);
142 *q = '\0';
143 return 0;
146 static void free_message(struct commit_message *msg)
148 free(msg->parent_label);
149 free(msg->reencoded_message);
152 static char *get_encoding(const char *message)
154 const char *p = message, *eol;
156 if (!p)
157 die ("Could not read commit message of %s",
158 sha1_to_hex(commit->object.sha1));
159 while (*p && *p != '\n') {
160 for (eol = p + 1; *eol && *eol != '\n'; eol++)
161 ; /* do nothing */
162 if (!prefixcmp(p, "encoding ")) {
163 char *result = xmalloc(eol - 8 - p);
164 strlcpy(result, p + 9, eol - 8 - p);
165 return result;
167 p = eol;
168 if (*p == '\n')
169 p++;
171 return NULL;
174 static void add_message_to_msg(struct strbuf *msgbuf, const char *message)
176 const char *p = message;
177 while (*p && (*p != '\n' || p[1] != '\n'))
178 p++;
180 if (!*p)
181 strbuf_addstr(msgbuf, sha1_to_hex(commit->object.sha1));
183 p += 2;
184 strbuf_addstr(msgbuf, p);
187 static void set_author_ident_env(const char *message)
189 const char *p = message;
190 if (!p)
191 die ("Could not read commit message of %s",
192 sha1_to_hex(commit->object.sha1));
193 while (*p && *p != '\n') {
194 const char *eol;
196 for (eol = p; *eol && *eol != '\n'; eol++)
197 ; /* do nothing */
198 if (!prefixcmp(p, "author ")) {
199 char *line, *pend, *email, *timestamp;
201 p += 7;
202 line = xmemdupz(p, eol - p);
203 email = strchr(line, '<');
204 if (!email)
205 die ("Could not extract author email from %s",
206 sha1_to_hex(commit->object.sha1));
207 if (email == line)
208 pend = line;
209 else
210 for (pend = email; pend != line + 1 &&
211 isspace(pend[-1]); pend--);
212 ; /* do nothing */
213 *pend = '\0';
214 email++;
215 timestamp = strchr(email, '>');
216 if (!timestamp)
217 die ("Could not extract author time from %s",
218 sha1_to_hex(commit->object.sha1));
219 *timestamp = '\0';
220 for (timestamp++; *timestamp && isspace(*timestamp);
221 timestamp++)
222 ; /* do nothing */
223 setenv("GIT_AUTHOR_NAME", line, 1);
224 setenv("GIT_AUTHOR_EMAIL", email, 1);
225 setenv("GIT_AUTHOR_DATE", timestamp, 1);
226 free(line);
227 return;
229 p = eol;
230 if (*p == '\n')
231 p++;
233 die ("No author information found in %s",
234 sha1_to_hex(commit->object.sha1));
237 static char *help_msg(const char *name)
239 struct strbuf helpbuf = STRBUF_INIT;
240 char *msg = getenv("GIT_CHERRY_PICK_HELP");
242 if (msg)
243 return msg;
245 strbuf_addstr(&helpbuf, " After resolving the conflicts,\n"
246 "mark the corrected paths with 'git add <paths>' or 'git rm <paths>'\n"
247 "and commit the result");
249 if (action == CHERRY_PICK) {
250 strbuf_addf(&helpbuf, " with: \n"
251 "\n"
252 " git commit -c %s\n",
253 name);
255 else
256 strbuf_addch(&helpbuf, '.');
257 return strbuf_detach(&helpbuf, NULL);
260 static void write_message(struct strbuf *msgbuf, const char *filename)
262 static struct lock_file msg_file;
264 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
265 LOCK_DIE_ON_ERROR);
266 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
267 die_errno("Could not write to %s.", filename);
268 strbuf_release(msgbuf);
269 if (commit_lock_file(&msg_file) < 0)
270 die("Error wrapping up %s", filename);
273 static struct tree *empty_tree(void)
275 struct tree *tree = xcalloc(1, sizeof(struct tree));
277 tree->object.parsed = 1;
278 tree->object.type = OBJ_TREE;
279 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
280 return tree;
283 static NORETURN void die_dirty_index(const char *me)
285 if (read_cache_unmerged()) {
286 die_resolve_conflict(me);
287 } else {
288 if (advice_commit_before_merge)
289 die("Your local changes would be overwritten by %s.\n"
290 "Please, commit your changes or stash them to proceed.", me);
291 else
292 die("Your local changes would be overwritten by %s.\n", me);
296 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
298 struct ref_lock *ref_lock;
300 read_cache();
301 if (checkout_fast_forward(from, to))
302 exit(1); /* the callee should have complained already */
303 ref_lock = lock_any_ref_for_update("HEAD", from, 0);
304 return write_ref_sha1(ref_lock, to, "cherry-pick");
307 static void do_recursive_merge(struct commit *base, struct commit *next,
308 const char *base_label, const char *next_label,
309 unsigned char *head, struct strbuf *msgbuf,
310 char *defmsg)
312 struct merge_options o;
313 struct tree *result, *next_tree, *base_tree, *head_tree;
314 int clean, index_fd;
315 static struct lock_file index_lock;
317 index_fd = hold_locked_index(&index_lock, 1);
319 read_cache();
320 init_merge_options(&o);
321 o.ancestor = base ? base_label : "(empty tree)";
322 o.branch1 = "HEAD";
323 o.branch2 = next ? next_label : "(empty tree)";
325 head_tree = parse_tree_indirect(head);
326 next_tree = next ? next->tree : empty_tree();
327 base_tree = base ? base->tree : empty_tree();
329 clean = merge_trees(&o,
330 head_tree,
331 next_tree, base_tree, &result);
333 if (active_cache_changed &&
334 (write_cache(index_fd, active_cache, active_nr) ||
335 commit_locked_index(&index_lock)))
336 die("%s: Unable to write new index file", me);
337 rollback_lock_file(&index_lock);
339 if (!clean) {
340 int i;
341 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
342 for (i = 0; i < active_nr;) {
343 struct cache_entry *ce = active_cache[i++];
344 if (ce_stage(ce)) {
345 strbuf_addch(msgbuf, '\t');
346 strbuf_addstr(msgbuf, ce->name);
347 strbuf_addch(msgbuf, '\n');
348 while (i < active_nr && !strcmp(ce->name,
349 active_cache[i]->name))
350 i++;
353 write_message(msgbuf, defmsg);
354 fprintf(stderr, "Automatic %s failed.%s\n",
355 me, help_msg(commit_name));
356 rerere(allow_rerere_auto);
357 exit(1);
359 write_message(msgbuf, defmsg);
360 fprintf(stderr, "Finished one %s.\n", me);
363 static int revert_or_cherry_pick(int argc, const char **argv)
365 unsigned char head[20];
366 struct commit *base, *next, *parent;
367 const char *base_label, *next_label;
368 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
369 char *defmsg = NULL;
370 struct strbuf msgbuf = STRBUF_INIT;
372 git_config(git_default_config, NULL);
373 me = action == REVERT ? "revert" : "cherry-pick";
374 setenv(GIT_REFLOG_ACTION, me, 0);
375 parse_args(argc, argv);
377 /* this is copied from the shell script, but it's never triggered... */
378 if (action == REVERT && !no_replay)
379 die("revert is incompatible with replay");
381 if (allow_ff) {
382 if (signoff)
383 die("cherry-pick --ff cannot be used with --signoff");
384 if (no_commit)
385 die("cherry-pick --ff cannot be used with --no-commit");
386 if (no_replay)
387 die("cherry-pick --ff cannot be used with -x");
388 if (edit)
389 die("cherry-pick --ff cannot be used with --edit");
392 if (read_cache() < 0)
393 die("git %s: failed to read the index", me);
394 if (no_commit) {
396 * We do not intend to commit immediately. We just want to
397 * merge the differences in, so let's compute the tree
398 * that represents the "current" state for merge-recursive
399 * to work on.
401 if (write_cache_as_tree(head, 0, NULL))
402 die ("Your index file is unmerged.");
403 } else {
404 if (get_sha1("HEAD", head))
405 die ("You do not have a valid HEAD");
406 if (index_differs_from("HEAD", 0))
407 die_dirty_index(me);
409 discard_cache();
411 if (!commit->parents) {
412 if (action == REVERT)
413 die ("Cannot revert a root commit");
414 parent = NULL;
416 else if (commit->parents->next) {
417 /* Reverting or cherry-picking a merge commit */
418 int cnt;
419 struct commit_list *p;
421 if (!mainline)
422 die("Commit %s is a merge but no -m option was given.",
423 sha1_to_hex(commit->object.sha1));
425 for (cnt = 1, p = commit->parents;
426 cnt != mainline && p;
427 cnt++)
428 p = p->next;
429 if (cnt != mainline || !p)
430 die("Commit %s does not have parent %d",
431 sha1_to_hex(commit->object.sha1), mainline);
432 parent = p->item;
433 } else if (0 < mainline)
434 die("Mainline was specified but commit %s is not a merge.",
435 sha1_to_hex(commit->object.sha1));
436 else
437 parent = commit->parents->item;
439 if (allow_ff && !hashcmp(parent->object.sha1, head))
440 return fast_forward_to(commit->object.sha1, head);
442 if (parent && parse_commit(parent) < 0)
443 die("%s: cannot parse parent commit %s",
444 me, sha1_to_hex(parent->object.sha1));
446 if (get_message(commit->buffer, &msg) != 0)
447 die("Cannot get commit message for %s",
448 sha1_to_hex(commit->object.sha1));
451 * "commit" is an existing commit. We would want to apply
452 * the difference it introduces since its first parent "prev"
453 * on top of the current HEAD if we are cherry-pick. Or the
454 * reverse of it if we are revert.
457 defmsg = git_pathdup("MERGE_MSG");
459 if (action == REVERT) {
460 base = commit;
461 base_label = msg.label;
462 next = parent;
463 next_label = msg.parent_label;
464 strbuf_addstr(&msgbuf, "Revert \"");
465 strbuf_addstr(&msgbuf, msg.subject);
466 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
467 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
469 if (commit->parents->next) {
470 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
471 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
473 strbuf_addstr(&msgbuf, ".\n");
474 } else {
475 base = parent;
476 base_label = msg.parent_label;
477 next = commit;
478 next_label = msg.label;
479 set_author_ident_env(msg.message);
480 add_message_to_msg(&msgbuf, msg.message);
481 if (no_replay) {
482 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
483 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
484 strbuf_addstr(&msgbuf, ")\n");
488 if (!strategy || !strcmp(strategy, "recursive") || action == REVERT)
489 do_recursive_merge(base, next, base_label, next_label,
490 head, &msgbuf, defmsg);
491 else {
492 int res;
493 struct commit_list *common = NULL;
494 struct commit_list *remotes = NULL;
495 write_message(&msgbuf, defmsg);
496 commit_list_insert(base, &common);
497 commit_list_insert(next, &remotes);
498 res = try_merge_command(strategy, common,
499 sha1_to_hex(head), remotes);
500 free_commit_list(common);
501 free_commit_list(remotes);
502 if (res) {
503 fprintf(stderr, "Automatic %s with strategy %s failed.%s\n",
504 me, strategy, help_msg(commit_name));
505 rerere(allow_rerere_auto);
506 exit(1);
512 * If we are cherry-pick, and if the merge did not result in
513 * hand-editing, we will hit this commit and inherit the original
514 * author date and name.
515 * If we are revert, or if our cherry-pick results in a hand merge,
516 * we had better say that the current user is responsible for that.
519 if (!no_commit) {
520 /* 6 is max possible length of our args array including NULL */
521 const char *args[6];
522 int i = 0;
523 args[i++] = "commit";
524 args[i++] = "-n";
525 if (signoff)
526 args[i++] = "-s";
527 if (!edit) {
528 args[i++] = "-F";
529 args[i++] = defmsg;
531 args[i] = NULL;
532 return execv_git_cmd(args);
534 free_message(&msg);
535 free(defmsg);
537 return 0;
540 int cmd_revert(int argc, const char **argv, const char *prefix)
542 if (isatty(0))
543 edit = 1;
544 no_replay = 1;
545 action = REVERT;
546 return revert_or_cherry_pick(argc, argv);
549 int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
551 no_replay = 0;
552 action = CHERRY_PICK;
553 return revert_or_cherry_pick(argc, argv);