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