revert: Separate cmdline parsing from functional code
[git/jnareb-git.git] / builtin / revert.c
blob90fe2efe94874638e7a7998efa9b4e75d6d28943
1 #include "cache.h"
2 #include "builtin.h"
3 #include "object.h"
4 #include "commit.h"
5 #include "tag.h"
6 #include "run-command.h"
7 #include "exec_cmd.h"
8 #include "utf8.h"
9 #include "parse-options.h"
10 #include "cache-tree.h"
11 #include "diff.h"
12 #include "revision.h"
13 #include "rerere.h"
14 #include "merge-recursive.h"
15 #include "refs.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 enum replay_action { REVERT, CHERRY_PICK };
40 struct replay_opts {
41 enum replay_action action;
43 /* Boolean options */
44 int edit;
45 int record_origin;
46 int no_commit;
47 int signoff;
48 int allow_ff;
49 int allow_rerere_auto;
51 int mainline;
52 int commit_argc;
53 const char **commit_argv;
55 /* Merge strategy */
56 const char *strategy;
57 const char **xopts;
58 size_t xopts_nr, xopts_alloc;
61 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
63 static const char *action_name(const struct replay_opts *opts)
65 return opts->action == REVERT ? "revert" : "cherry-pick";
68 static char *get_encoding(const char *message);
70 static const char * const *revert_or_cherry_pick_usage(struct replay_opts *opts)
72 return opts->action == REVERT ? revert_usage : cherry_pick_usage;
75 static int option_parse_x(const struct option *opt,
76 const char *arg, int unset)
78 struct replay_opts **opts_ptr = opt->value;
79 struct replay_opts *opts = *opts_ptr;
81 if (unset)
82 return 0;
84 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
85 opts->xopts[opts->xopts_nr++] = xstrdup(arg);
86 return 0;
89 static void parse_args(int argc, const char **argv, struct replay_opts *opts)
91 const char * const * usage_str = revert_or_cherry_pick_usage(opts);
92 int noop;
93 struct option options[] = {
94 OPT_BOOLEAN('n', "no-commit", &opts->no_commit, "don't automatically commit"),
95 OPT_BOOLEAN('e', "edit", &opts->edit, "edit the commit message"),
96 { OPTION_BOOLEAN, 'r', NULL, &noop, NULL, "no-op (backward compatibility)",
97 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 0 },
98 OPT_BOOLEAN('s', "signoff", &opts->signoff, "add Signed-off-by:"),
99 OPT_INTEGER('m', "mainline", &opts->mainline, "parent number"),
100 OPT_RERERE_AUTOUPDATE(&opts->allow_rerere_auto),
101 OPT_STRING(0, "strategy", &opts->strategy, "strategy", "merge strategy"),
102 OPT_CALLBACK('X', "strategy-option", &opts, "option",
103 "option for merge strategy", option_parse_x),
104 OPT_END(),
105 OPT_END(),
106 OPT_END(),
109 if (opts->action == CHERRY_PICK) {
110 struct option cp_extra[] = {
111 OPT_BOOLEAN('x', NULL, &opts->record_origin, "append commit name"),
112 OPT_BOOLEAN(0, "ff", &opts->allow_ff, "allow fast-forward"),
113 OPT_END(),
115 if (parse_options_concat(options, ARRAY_SIZE(options), cp_extra))
116 die(_("program error"));
119 opts->commit_argc = parse_options(argc, argv, NULL, options, usage_str,
120 PARSE_OPT_KEEP_ARGV0 |
121 PARSE_OPT_KEEP_UNKNOWN);
122 if (opts->commit_argc < 2)
123 usage_with_options(usage_str, options);
125 opts->commit_argv = argv;
128 struct commit_message {
129 char *parent_label;
130 const char *label;
131 const char *subject;
132 char *reencoded_message;
133 const char *message;
136 static int get_message(struct commit *commit, struct commit_message *out)
138 const char *encoding;
139 const char *abbrev, *subject;
140 int abbrev_len, subject_len;
141 char *q;
143 if (!commit->buffer)
144 return -1;
145 encoding = get_encoding(commit->buffer);
146 if (!encoding)
147 encoding = "UTF-8";
148 if (!git_commit_encoding)
149 git_commit_encoding = "UTF-8";
151 out->reencoded_message = NULL;
152 out->message = commit->buffer;
153 if (strcmp(encoding, git_commit_encoding))
154 out->reencoded_message = reencode_string(commit->buffer,
155 git_commit_encoding, encoding);
156 if (out->reencoded_message)
157 out->message = out->reencoded_message;
159 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
160 abbrev_len = strlen(abbrev);
162 subject_len = find_commit_subject(out->message, &subject);
164 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
165 strlen("... ") + subject_len + 1);
166 q = out->parent_label;
167 q = mempcpy(q, "parent of ", strlen("parent of "));
168 out->label = q;
169 q = mempcpy(q, abbrev, abbrev_len);
170 q = mempcpy(q, "... ", strlen("... "));
171 out->subject = q;
172 q = mempcpy(q, subject, subject_len);
173 *q = '\0';
174 return 0;
177 static void free_message(struct commit_message *msg)
179 free(msg->parent_label);
180 free(msg->reencoded_message);
183 static char *get_encoding(const char *message)
185 const char *p = message, *eol;
187 while (*p && *p != '\n') {
188 for (eol = p + 1; *eol && *eol != '\n'; eol++)
189 ; /* do nothing */
190 if (!prefixcmp(p, "encoding ")) {
191 char *result = xmalloc(eol - 8 - p);
192 strlcpy(result, p + 9, eol - 8 - p);
193 return result;
195 p = eol;
196 if (*p == '\n')
197 p++;
199 return NULL;
202 static void write_cherry_pick_head(struct commit *commit)
204 int fd;
205 struct strbuf buf = STRBUF_INIT;
207 strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
209 fd = open(git_path("CHERRY_PICK_HEAD"), O_WRONLY | O_CREAT, 0666);
210 if (fd < 0)
211 die_errno(_("Could not open '%s' for writing"),
212 git_path("CHERRY_PICK_HEAD"));
213 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
214 die_errno(_("Could not write to '%s'"), git_path("CHERRY_PICK_HEAD"));
215 strbuf_release(&buf);
218 static void print_advice(void)
220 char *msg = getenv("GIT_CHERRY_PICK_HELP");
222 if (msg) {
223 fprintf(stderr, "%s\n", msg);
225 * A conflict has occured but the porcelain
226 * (typically rebase --interactive) wants to take care
227 * of the commit itself so remove CHERRY_PICK_HEAD
229 unlink(git_path("CHERRY_PICK_HEAD"));
230 return;
233 advise("after resolving the conflicts, mark the corrected paths");
234 advise("with 'git add <paths>' or 'git rm <paths>'");
235 advise("and commit the result with 'git commit'");
238 static void write_message(struct strbuf *msgbuf, const char *filename)
240 static struct lock_file msg_file;
242 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
243 LOCK_DIE_ON_ERROR);
244 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
245 die_errno(_("Could not write to %s."), filename);
246 strbuf_release(msgbuf);
247 if (commit_lock_file(&msg_file) < 0)
248 die(_("Error wrapping up %s"), filename);
251 static struct tree *empty_tree(void)
253 struct tree *tree = xcalloc(1, sizeof(struct tree));
255 tree->object.parsed = 1;
256 tree->object.type = OBJ_TREE;
257 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
258 return tree;
261 static NORETURN void die_dirty_index(struct replay_opts *opts)
263 if (read_cache_unmerged()) {
264 die_resolve_conflict(action_name(opts));
265 } else {
266 if (advice_commit_before_merge) {
267 if (opts->action == REVERT)
268 die(_("Your local changes would be overwritten by revert.\n"
269 "Please, commit your changes or stash them to proceed."));
270 else
271 die(_("Your local changes would be overwritten by cherry-pick.\n"
272 "Please, commit your changes or stash them to proceed."));
273 } else {
274 if (opts->action == REVERT)
275 die(_("Your local changes would be overwritten by revert.\n"));
276 else
277 die(_("Your local changes would be overwritten by cherry-pick.\n"));
282 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
284 struct ref_lock *ref_lock;
286 read_cache();
287 if (checkout_fast_forward(from, to))
288 exit(1); /* the callee should have complained already */
289 ref_lock = lock_any_ref_for_update("HEAD", from, 0);
290 return write_ref_sha1(ref_lock, to, "cherry-pick");
293 static int do_recursive_merge(struct commit *base, struct commit *next,
294 const char *base_label, const char *next_label,
295 unsigned char *head, struct strbuf *msgbuf,
296 struct replay_opts *opts)
298 struct merge_options o;
299 struct tree *result, *next_tree, *base_tree, *head_tree;
300 int clean, index_fd;
301 const char **xopt;
302 static struct lock_file index_lock;
304 index_fd = hold_locked_index(&index_lock, 1);
306 read_cache();
308 init_merge_options(&o);
309 o.ancestor = base ? base_label : "(empty tree)";
310 o.branch1 = "HEAD";
311 o.branch2 = next ? next_label : "(empty tree)";
313 head_tree = parse_tree_indirect(head);
314 next_tree = next ? next->tree : empty_tree();
315 base_tree = base ? base->tree : empty_tree();
317 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
318 parse_merge_opt(&o, *xopt);
320 clean = merge_trees(&o,
321 head_tree,
322 next_tree, base_tree, &result);
324 if (active_cache_changed &&
325 (write_cache(index_fd, active_cache, active_nr) ||
326 commit_locked_index(&index_lock)))
327 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
328 die(_("%s: Unable to write new index file"), action_name(opts));
329 rollback_lock_file(&index_lock);
331 if (!clean) {
332 int i;
333 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
334 for (i = 0; i < active_nr;) {
335 struct cache_entry *ce = active_cache[i++];
336 if (ce_stage(ce)) {
337 strbuf_addch(msgbuf, '\t');
338 strbuf_addstr(msgbuf, ce->name);
339 strbuf_addch(msgbuf, '\n');
340 while (i < active_nr && !strcmp(ce->name,
341 active_cache[i]->name))
342 i++;
347 return !clean;
351 * If we are cherry-pick, and if the merge did not result in
352 * hand-editing, we will hit this commit and inherit the original
353 * author date and name.
354 * If we are revert, or if our cherry-pick results in a hand merge,
355 * we had better say that the current user is responsible for that.
357 static int run_git_commit(const char *defmsg, struct replay_opts *opts)
359 /* 6 is max possible length of our args array including NULL */
360 const char *args[6];
361 int i = 0;
363 args[i++] = "commit";
364 args[i++] = "-n";
365 if (opts->signoff)
366 args[i++] = "-s";
367 if (!opts->edit) {
368 args[i++] = "-F";
369 args[i++] = defmsg;
371 args[i] = NULL;
373 return run_command_v_opt(args, RUN_GIT_CMD);
376 static int do_pick_commit(struct commit *commit, struct replay_opts *opts)
378 unsigned char head[20];
379 struct commit *base, *next, *parent;
380 const char *base_label, *next_label;
381 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
382 char *defmsg = NULL;
383 struct strbuf msgbuf = STRBUF_INIT;
384 int res;
386 if (opts->no_commit) {
388 * We do not intend to commit immediately. We just want to
389 * merge the differences in, so let's compute the tree
390 * that represents the "current" state for merge-recursive
391 * to work on.
393 if (write_cache_as_tree(head, 0, NULL))
394 die (_("Your index file is unmerged."));
395 } else {
396 if (get_sha1("HEAD", head))
397 die (_("You do not have a valid HEAD"));
398 if (index_differs_from("HEAD", 0))
399 die_dirty_index(opts);
401 discard_cache();
403 if (!commit->parents) {
404 parent = NULL;
406 else if (commit->parents->next) {
407 /* Reverting or cherry-picking a merge commit */
408 int cnt;
409 struct commit_list *p;
411 if (!opts->mainline)
412 die(_("Commit %s is a merge but no -m option was given."),
413 sha1_to_hex(commit->object.sha1));
415 for (cnt = 1, p = commit->parents;
416 cnt != opts->mainline && p;
417 cnt++)
418 p = p->next;
419 if (cnt != opts->mainline || !p)
420 die(_("Commit %s does not have parent %d"),
421 sha1_to_hex(commit->object.sha1), opts->mainline);
422 parent = p->item;
423 } else if (0 < opts->mainline)
424 die(_("Mainline was specified but commit %s is not a merge."),
425 sha1_to_hex(commit->object.sha1));
426 else
427 parent = commit->parents->item;
429 if (opts->allow_ff && parent && !hashcmp(parent->object.sha1, head))
430 return fast_forward_to(commit->object.sha1, head);
432 if (parent && parse_commit(parent) < 0)
433 /* TRANSLATORS: The first %s will be "revert" or
434 "cherry-pick", the second %s a SHA1 */
435 die(_("%s: cannot parse parent commit %s"),
436 action_name(opts), sha1_to_hex(parent->object.sha1));
438 if (get_message(commit, &msg) != 0)
439 die(_("Cannot get commit message for %s"),
440 sha1_to_hex(commit->object.sha1));
443 * "commit" is an existing commit. We would want to apply
444 * the difference it introduces since its first parent "prev"
445 * on top of the current HEAD if we are cherry-pick. Or the
446 * reverse of it if we are revert.
449 defmsg = git_pathdup("MERGE_MSG");
451 if (opts->action == REVERT) {
452 base = commit;
453 base_label = msg.label;
454 next = parent;
455 next_label = msg.parent_label;
456 strbuf_addstr(&msgbuf, "Revert \"");
457 strbuf_addstr(&msgbuf, msg.subject);
458 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
459 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
461 if (commit->parents && commit->parents->next) {
462 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
463 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
465 strbuf_addstr(&msgbuf, ".\n");
466 } else {
467 const char *p;
469 base = parent;
470 base_label = msg.parent_label;
471 next = commit;
472 next_label = msg.label;
475 * Append the commit log message to msgbuf; it starts
476 * after the tree, parent, author, committer
477 * information followed by "\n\n".
479 p = strstr(msg.message, "\n\n");
480 if (p) {
481 p += 2;
482 strbuf_addstr(&msgbuf, p);
485 if (opts->record_origin) {
486 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
487 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
488 strbuf_addstr(&msgbuf, ")\n");
490 if (!opts->no_commit)
491 write_cherry_pick_head(commit);
494 if (!opts->strategy || !strcmp(opts->strategy, "recursive") || opts->action == REVERT) {
495 res = do_recursive_merge(base, next, base_label, next_label,
496 head, &msgbuf, opts);
497 write_message(&msgbuf, defmsg);
498 } else {
499 struct commit_list *common = NULL;
500 struct commit_list *remotes = NULL;
502 write_message(&msgbuf, defmsg);
504 commit_list_insert(base, &common);
505 commit_list_insert(next, &remotes);
506 res = try_merge_command(opts->strategy, opts->xopts_nr, opts->xopts,
507 common, sha1_to_hex(head), remotes);
508 free_commit_list(common);
509 free_commit_list(remotes);
512 if (res) {
513 error(opts->action == REVERT
514 ? _("could not revert %s... %s")
515 : _("could not apply %s... %s"),
516 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
517 msg.subject);
518 print_advice();
519 rerere(opts->allow_rerere_auto);
520 } else {
521 if (!opts->no_commit)
522 res = run_git_commit(defmsg, opts);
525 free_message(&msg);
526 free(defmsg);
528 return res;
531 static void prepare_revs(struct rev_info *revs, struct replay_opts *opts)
533 int argc;
535 init_revisions(revs, NULL);
536 revs->no_walk = 1;
537 if (opts->action != REVERT)
538 revs->reverse = 1;
540 argc = setup_revisions(opts->commit_argc, opts->commit_argv, revs, NULL);
541 if (argc > 1)
542 usage(*revert_or_cherry_pick_usage(opts));
544 if (prepare_revision_walk(revs))
545 die(_("revision walk setup failed"));
547 if (!revs->commits)
548 die(_("empty commit set passed"));
551 static void read_and_refresh_cache(struct replay_opts *opts)
553 static struct lock_file index_lock;
554 int index_fd = hold_locked_index(&index_lock, 0);
555 if (read_index_preload(&the_index, NULL) < 0)
556 die(_("git %s: failed to read the index"), action_name(opts));
557 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
558 if (the_index.cache_changed) {
559 if (write_index(&the_index, index_fd) ||
560 commit_locked_index(&index_lock))
561 die(_("git %s: failed to refresh the index"), action_name(opts));
563 rollback_lock_file(&index_lock);
566 static int pick_commits(struct replay_opts *opts)
568 struct rev_info revs;
569 struct commit *commit;
571 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
572 if (opts->allow_ff) {
573 if (opts->signoff)
574 die(_("cherry-pick --ff cannot be used with --signoff"));
575 if (opts->no_commit)
576 die(_("cherry-pick --ff cannot be used with --no-commit"));
577 if (opts->record_origin)
578 die(_("cherry-pick --ff cannot be used with -x"));
579 if (opts->edit)
580 die(_("cherry-pick --ff cannot be used with --edit"));
583 read_and_refresh_cache(opts);
585 prepare_revs(&revs, opts);
587 while ((commit = get_revision(&revs))) {
588 int res = do_pick_commit(commit, opts);
589 if (res)
590 return res;
593 return 0;
596 int cmd_revert(int argc, const char **argv, const char *prefix)
598 struct replay_opts opts;
600 memset(&opts, 0, sizeof(opts));
601 if (isatty(0))
602 opts.edit = 1;
603 opts.action = REVERT;
604 git_config(git_default_config, NULL);
605 parse_args(argc, argv, &opts);
606 return pick_commits(&opts);
609 int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
611 struct replay_opts opts;
613 memset(&opts, 0, sizeof(opts));
614 opts.action = CHERRY_PICK;
615 git_config(git_default_config, NULL);
616 parse_args(argc, argv, &opts);
617 return pick_commits(&opts);