d6c9f1dadb8f002d0c859ce6698a6fba8874904a
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"
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
28static const char * const revert_usage[] = {
29 "git revert [options] <commit-ish>",
30 NULL
31};
32
33static const char * const cherry_pick_usage[] = {
34 "git cherry-pick [options] <commit-ish>",
35 NULL
36};
37
38static int edit, record_origin, no_commit, mainline, signoff, allow_ff;
39static enum { REVERT, CHERRY_PICK } action;
40static int commit_argc;
41static const char **commit_argv;
42static int allow_rerere_auto;
43
44static const char *me;
45
46/* Merge strategy. */
47static const char *strategy;
48static const char **xopts;
49static size_t xopts_nr, xopts_alloc;
50
51#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
52
53static char *get_encoding(const char *message);
54
55static const char * const *revert_or_cherry_pick_usage(void)
56{
57 return action == REVERT ? revert_usage : cherry_pick_usage;
58}
59
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
71static void parse_args(int argc, const char **argv)
72{
73 const char * const * usage_str = revert_or_cherry_pick_usage();
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"),
78 { OPTION_BOOLEAN, 'r', NULL, &noop, NULL, "no-op (backward compatibility)",
79 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 0 },
80 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
81 OPT_INTEGER('m', "mainline", &mainline, "parent number"),
82 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
83 OPT_STRING(0, "strategy", &strategy, "strategy", "merge strategy"),
84 OPT_CALLBACK('X', "strategy-option", &xopts, "option",
85 "option for merge strategy", option_parse_x),
86 OPT_END(),
87 OPT_END(),
88 OPT_END(),
89 };
90
91 if (action == CHERRY_PICK) {
92 struct option cp_extra[] = {
93 OPT_BOOLEAN('x', NULL, &record_origin, "append commit name"),
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))
98 die(_("program error"));
99 }
100
101 commit_argc = parse_options(argc, argv, NULL, options, usage_str,
102 PARSE_OPT_KEEP_ARGV0 |
103 PARSE_OPT_KEEP_UNKNOWN);
104 if (commit_argc < 2)
105 usage_with_options(usage_str, options);
106
107 commit_argv = argv;
108}
109
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
118static int get_message(struct commit *commit, struct commit_message *out)
119{
120 const char *encoding;
121 const char *abbrev, *subject;
122 int abbrev_len, subject_len;
123 char *q;
124
125 if (!commit->buffer)
126 return -1;
127 encoding = get_encoding(commit->buffer);
128 if (!encoding)
129 encoding = "UTF-8";
130 if (!git_commit_encoding)
131 git_commit_encoding = "UTF-8";
132
133 out->reencoded_message = NULL;
134 out->message = commit->buffer;
135 if (strcmp(encoding, git_commit_encoding))
136 out->reencoded_message = reencode_string(commit->buffer,
137 git_commit_encoding, encoding);
138 if (out->reencoded_message)
139 out->message = out->reencoded_message;
140
141 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
142 abbrev_len = strlen(abbrev);
143
144 subject_len = find_commit_subject(out->message, &subject);
145
146 out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
147 strlen("... ") + subject_len + 1);
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;
154 q = mempcpy(q, subject, subject_len);
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);
163}
164
165static char *get_encoding(const char *message)
166{
167 const char *p = message, *eol;
168
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
184static void write_cherry_pick_head(struct commit *commit)
185{
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)
193 die_errno(_("Could not open '%s' for writing"),
194 git_path("CHERRY_PICK_HEAD"));
195 if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
196 die_errno(_("Could not write to '%s'"), git_path("CHERRY_PICK_HEAD"));
197 strbuf_release(&buf);
198}
199
200static void print_advice(void)
201{
202 char *msg = getenv("GIT_CHERRY_PICK_HELP");
203
204 if (msg) {
205 fprintf(stderr, "%s\n", msg);
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"));
212 return;
213 }
214
215 advise("after resolving the conflicts, mark the corrected paths");
216 advise("with 'git add <paths>' or 'git rm <paths>'");
217 advise("and commit the result with 'git commit'");
218}
219
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)
227 die_errno(_("Could not write to %s."), filename);
228 strbuf_release(msgbuf);
229 if (commit_lock_file(&msg_file) < 0)
230 die(_("Error wrapping up %s"), filename);
231}
232
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
243static NORETURN void die_dirty_index(const char *me)
244{
245 if (read_cache_unmerged()) {
246 die_resolve_conflict(me);
247 } else {
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 }
261 }
262}
263
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
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)
278{
279 struct merge_options o;
280 struct tree *result, *next_tree, *base_tree, *head_tree;
281 int clean, index_fd;
282 const char **xopt;
283 static struct lock_file index_lock;
284
285 index_fd = hold_locked_index(&index_lock, 1);
286
287 read_cache();
288
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
298 for (xopt = xopts; xopt != xopts + xopts_nr; xopt++)
299 parse_merge_opt(&o, *xopt);
300
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)))
308 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
309 die(_("%s: Unable to write new index file"), me);
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 }
326 }
327
328 return !clean;
329}
330
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);
355}
356
357static int do_pick_commit(struct commit *commit)
358{
359 unsigned char head[20];
360 struct commit *base, *next, *parent;
361 const char *base_label, *next_label;
362 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
363 char *defmsg = NULL;
364 struct strbuf msgbuf = STRBUF_INIT;
365 int res;
366
367 if (no_commit) {
368 /*
369 * We do not intend to commit immediately. We just want to
370 * merge the differences in, so let's compute the tree
371 * that represents the "current" state for merge-recursive
372 * to work on.
373 */
374 if (write_cache_as_tree(head, 0, NULL))
375 die (_("Your index file is unmerged."));
376 } else {
377 if (get_sha1("HEAD", head))
378 die (_("You do not have a valid HEAD"));
379 if (index_differs_from("HEAD", 0))
380 die_dirty_index(me);
381 }
382 discard_cache();
383
384 if (!commit->parents) {
385 parent = NULL;
386 }
387 else if (commit->parents->next) {
388 /* Reverting or cherry-picking a merge commit */
389 int cnt;
390 struct commit_list *p;
391
392 if (!mainline)
393 die(_("Commit %s is a merge but no -m option was given."),
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)
401 die(_("Commit %s does not have parent %d"),
402 sha1_to_hex(commit->object.sha1), mainline);
403 parent = p->item;
404 } else if (0 < mainline)
405 die(_("Mainline was specified but commit %s is not a merge."),
406 sha1_to_hex(commit->object.sha1));
407 else
408 parent = commit->parents->item;
409
410 if (allow_ff && parent && !hashcmp(parent->object.sha1, head))
411 return fast_forward_to(commit->object.sha1, head);
412
413 if (parent && parse_commit(parent) < 0)
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"),
417 me, sha1_to_hex(parent->object.sha1));
418
419 if (get_message(commit, &msg) != 0)
420 die(_("Cannot get commit message for %s"),
421 sha1_to_hex(commit->object.sha1));
422
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
430 defmsg = git_pathdup("MERGE_MSG");
431
432 if (action == REVERT) {
433 base = commit;
434 base_label = msg.label;
435 next = parent;
436 next_label = msg.parent_label;
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));
441
442 if (commit->parents && commit->parents->next) {
443 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
444 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
445 }
446 strbuf_addstr(&msgbuf, ".\n");
447 } else {
448 const char *p;
449
450 base = parent;
451 base_label = msg.parent_label;
452 next = commit;
453 next_label = msg.label;
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
466 if (record_origin) {
467 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
468 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
469 strbuf_addstr(&msgbuf, ")\n");
470 }
471 if (!no_commit)
472 write_cherry_pick_head(commit);
473 }
474
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 {
480 struct commit_list *common = NULL;
481 struct commit_list *remotes = NULL;
482
483 write_message(&msgbuf, defmsg);
484
485 commit_list_insert(base, &common);
486 commit_list_insert(next, &remotes);
487 res = try_merge_command(strategy, xopts_nr, xopts, common,
488 sha1_to_hex(head), remotes);
489 free_commit_list(common);
490 free_commit_list(remotes);
491 }
492
493 if (res) {
494 error(action == REVERT
495 ? _("could not revert %s... %s")
496 : _("could not apply %s... %s"),
497 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
498 msg.subject);
499 print_advice();
500 rerere(allow_rerere_auto);
501 } else {
502 if (!no_commit)
503 res = run_git_commit(defmsg);
504 }
505
506 free_message(&msg);
507 free(defmsg);
508
509 return res;
510}
511
512static void prepare_revs(struct rev_info *revs)
513{
514 int argc;
515
516 init_revisions(revs, NULL);
517 revs->no_walk = 1;
518 if (action != REVERT)
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());
524
525 if (prepare_revision_walk(revs))
526 die(_("revision walk setup failed"));
527
528 if (!revs->commits)
529 die(_("empty commit set passed"));
530}
531
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)
537 die(_("git %s: failed to read the index"), me);
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))
542 die(_("git %s: failed to refresh the index"), me);
543 }
544 rollback_lock_file(&index_lock);
545}
546
547static int revert_or_cherry_pick(int argc, const char **argv)
548{
549 struct rev_info revs;
550 struct commit *commit;
551
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)
559 die(_("cherry-pick --ff cannot be used with --signoff"));
560 if (no_commit)
561 die(_("cherry-pick --ff cannot be used with --no-commit"));
562 if (record_origin)
563 die(_("cherry-pick --ff cannot be used with -x"));
564 if (edit)
565 die(_("cherry-pick --ff cannot be used with --edit"));
566 }
567
568 read_and_refresh_cache(me);
569
570 prepare_revs(&revs);
571
572 while ((commit = get_revision(&revs))) {
573 int res = do_pick_commit(commit);
574 if (res)
575 return res;
576 }
577
578 return 0;
579}
580
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{
591 action = CHERRY_PICK;
592 return revert_or_cherry_pick(argc, argv);
593}