revert/cherry-pick: work on merge commits as well
[git/git.git] / builtin-revert.c
CommitLineData
9509af68
JS
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
11/*
12 * This implements the builtins revert and cherry-pick.
13 *
14 * Copyright (c) 2007 Johannes E. Schindelin
15 *
16 * Based on git-revert.sh, which is
17 *
18 * Copyright (c) 2005 Linus Torvalds
19 * Copyright (c) 2005 Junio C Hamano
20 */
21
7791ecbc 22static const char *revert_usage = "git-revert [--edit | --no-edit] [-n] [-m parent-number] <commit-ish>";
9509af68 23
7791ecbc 24static const char *cherry_pick_usage = "git-cherry-pick [--edit] [-n] [-m parent-number] [-r] [-x] <commit-ish>";
9509af68
JS
25
26static int edit;
27static int replay;
4175e9e3 28static enum { REVERT, CHERRY_PICK } action;
9509af68
JS
29static int no_commit;
30static struct commit *commit;
31static int needed_deref;
7791ecbc 32static int mainline;
9509af68
JS
33
34static const char *me;
35
36#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
37
38static void parse_options(int argc, const char **argv)
39{
40 const char *usage_str = action == REVERT ?
41 revert_usage : cherry_pick_usage;
42 unsigned char sha1[20];
43 const char *arg;
44 int i;
45
46 if (argc < 2)
47 usage(usage_str);
48
32309f54 49 for (i = 1; i < argc; i++) {
9509af68 50 arg = argv[i];
32309f54
JH
51 if (arg[0] != '-')
52 break;
9509af68
JS
53 if (!strcmp(arg, "-n") || !strcmp(arg, "--no-commit"))
54 no_commit = 1;
55 else if (!strcmp(arg, "-e") || !strcmp(arg, "--edit"))
56 edit = 1;
57 else if (!strcmp(arg, "--no-edit"))
58 edit = 0;
59 else if (!strcmp(arg, "-x") || !strcmp(arg, "--i-really-want-"
60 "to-expose-my-private-commit-object-name"))
61 replay = 0;
7791ecbc
JH
62 else if (!strcmp(arg, "-m") || !strcmp(arg, "--mainline")) {
63 if (++i >= argc ||
64 strtol_i(argv[i], 10, &mainline) ||
65 mainline <= 0)
66 usage(usage_str);
67 }
9509af68
JS
68 else if (strcmp(arg, "-r"))
69 usage(usage_str);
70 }
32309f54
JH
71 if (i != argc - 1)
72 usage(usage_str);
9509af68
JS
73 arg = argv[argc - 1];
74 if (get_sha1(arg, sha1))
75 die ("Cannot find '%s'", arg);
76 commit = (struct commit *)parse_object(sha1);
77 if (!commit)
78 die ("Could not find %s", sha1_to_hex(sha1));
79 if (commit->object.type == OBJ_TAG) {
80 commit = (struct commit *)
81 deref_tag((struct object *)commit, arg, strlen(arg));
82 needed_deref = 1;
83 }
84 if (commit->object.type != OBJ_COMMIT)
85 die ("'%s' does not point to a commit", arg);
86}
87
88static char *get_oneline(const char *message)
89{
90 char *result;
91 const char *p = message, *abbrev, *eol;
92 int abbrev_len, oneline_len;
93
94 if (!p)
95 die ("Could not read commit message of %s",
96 sha1_to_hex(commit->object.sha1));
97 while (*p && (*p != '\n' || p[1] != '\n'))
98 p++;
99
100 if (*p) {
101 p += 2;
102 for (eol = p + 1; *eol && *eol != '\n'; eol++)
103 ; /* do nothing */
104 } else
105 eol = p;
106 abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
107 abbrev_len = strlen(abbrev);
108 oneline_len = eol - p;
109 result = xmalloc(abbrev_len + 5 + oneline_len);
110 memcpy(result, abbrev, abbrev_len);
111 memcpy(result + abbrev_len, "... ", 4);
112 memcpy(result + abbrev_len + 4, p, oneline_len);
113 result[abbrev_len + 4 + oneline_len] = '\0';
114 return result;
115}
116
52fae7de 117static char *get_encoding(const char *message)
9509af68
JS
118{
119 const char *p = message, *eol;
120
121 if (!p)
122 die ("Could not read commit message of %s",
123 sha1_to_hex(commit->object.sha1));
124 while (*p && *p != '\n') {
125 for (eol = p + 1; *eol && *eol != '\n'; eol++)
126 ; /* do nothing */
127 if (!prefixcmp(p, "encoding ")) {
128 char *result = xmalloc(eol - 8 - p);
129 strlcpy(result, p + 9, eol - 8 - p);
130 return result;
131 }
132 p = eol;
133 if (*p == '\n')
134 p++;
135 }
136 return NULL;
137}
138
4175e9e3 139static struct lock_file msg_file;
9509af68
JS
140static int msg_fd;
141
142static void add_to_msg(const char *string)
143{
144 int len = strlen(string);
145 if (write_in_full(msg_fd, string, len) < 0)
1dcb3b64 146 die ("Could not write to MERGE_MSG");
9509af68
JS
147}
148
149static void add_message_to_msg(const char *message)
150{
151 const char *p = message;
152 while (*p && (*p != '\n' || p[1] != '\n'))
153 p++;
154
155 if (!*p)
156 add_to_msg(sha1_to_hex(commit->object.sha1));
157
158 p += 2;
159 add_to_msg(p);
160 return;
161}
162
163static void set_author_ident_env(const char *message)
164{
165 const char *p = message;
166 if (!p)
167 die ("Could not read commit message of %s",
168 sha1_to_hex(commit->object.sha1));
169 while (*p && *p != '\n') {
170 const char *eol;
171
172 for (eol = p; *eol && *eol != '\n'; eol++)
173 ; /* do nothing */
174 if (!prefixcmp(p, "author ")) {
175 char *line, *pend, *email, *timestamp;
176
177 p += 7;
182af834 178 line = xmemdupz(p, eol - p);
9509af68
JS
179 email = strchr(line, '<');
180 if (!email)
181 die ("Could not extract author email from %s",
182 sha1_to_hex(commit->object.sha1));
183 if (email == line)
184 pend = line;
185 else
186 for (pend = email; pend != line + 1 &&
187 isspace(pend[-1]); pend--);
188 ; /* do nothing */
189 *pend = '\0';
190 email++;
191 timestamp = strchr(email, '>');
192 if (!timestamp)
193 die ("Could not extract author email from %s",
194 sha1_to_hex(commit->object.sha1));
195 *timestamp = '\0';
196 for (timestamp++; *timestamp && isspace(*timestamp);
197 timestamp++)
198 ; /* do nothing */
199 setenv("GIT_AUTHOR_NAME", line, 1);
200 setenv("GIT_AUTHOR_EMAIL", email, 1);
201 setenv("GIT_AUTHOR_DATE", timestamp, 1);
202 free(line);
203 return;
204 }
205 p = eol;
206 if (*p == '\n')
207 p++;
208 }
209 die ("No author information found in %s",
210 sha1_to_hex(commit->object.sha1));
211}
212
213static int merge_recursive(const char *base_sha1,
214 const char *head_sha1, const char *head_name,
215 const char *next_sha1, const char *next_name)
216{
217 char buffer[256];
497bdc88 218 const char *argv[6];
9509af68
JS
219
220 sprintf(buffer, "GITHEAD_%s", head_sha1);
221 setenv(buffer, head_name, 1);
222 sprintf(buffer, "GITHEAD_%s", next_sha1);
223 setenv(buffer, next_name, 1);
224
225 /*
226 * This three way merge is an interesting one. We are at
227 * $head, and would want to apply the change between $commit
228 * and $prev on top of us (when reverting), or the change between
229 * $prev and $commit on top of us (when cherry-picking or replaying).
230 */
497bdc88
SP
231 argv[0] = "merge-recursive";
232 argv[1] = base_sha1;
233 argv[2] = "--";
234 argv[3] = head_sha1;
235 argv[4] = next_sha1;
236 argv[5] = NULL;
237
238 return run_command_v_opt(argv, RUN_COMMAND_NO_STDIN | RUN_GIT_CMD);
9509af68
JS
239}
240
241static int revert_or_cherry_pick(int argc, const char **argv)
242{
243 unsigned char head[20];
7791ecbc 244 struct commit *base, *next, *parent;
9509af68 245 int i;
1a8f2741
SP
246 char *oneline, *reencoded_message = NULL;
247 const char *message, *encoding;
abda5227 248 const char *defmsg = xstrdup(git_path("MERGE_MSG"));
9509af68
JS
249
250 git_config(git_default_config);
251 me = action == REVERT ? "revert" : "cherry-pick";
252 setenv(GIT_REFLOG_ACTION, me, 0);
253 parse_options(argc, argv);
254
255 /* this is copied from the shell script, but it's never triggered... */
256 if (action == REVERT && replay)
257 die("revert is incompatible with replay");
258
259 if (no_commit) {
260 /*
261 * We do not intend to commit immediately. We just want to
262 * merge the differences in.
263 */
264 if (write_tree(head, 0, NULL))
265 die ("Your index file is unmerged.");
266 } else {
267 struct wt_status s;
268
269 if (get_sha1("HEAD", head))
270 die ("You do not have a valid HEAD");
271 wt_status_prepare(&s);
272 if (s.commitable || s.workdir_dirty)
273 die ("Dirty index: cannot %s", me);
274 discard_cache();
275 }
276
277 if (!commit->parents)
278 die ("Cannot %s a root commit", me);
7791ecbc
JH
279 if (commit->parents->next) {
280 /* Reverting or cherry-picking a merge commit */
281 int cnt;
282 struct commit_list *p;
283
284 if (!mainline)
285 die("Commit %s is a merge but no -m option was given.",
286 sha1_to_hex(commit->object.sha1));
287
288 for (cnt = 1, p = commit->parents;
289 cnt != mainline && p;
290 cnt++)
291 p = p->next;
292 if (cnt != mainline || !p)
293 die("Commit %s does not have parent %d",
294 sha1_to_hex(commit->object.sha1), mainline);
295 parent = p->item;
296 } else if (0 < mainline)
297 die("Mainline was specified but commit %s is not a merge.",
298 sha1_to_hex(commit->object.sha1));
299 else
300 parent = commit->parents->item;
301
9509af68
JS
302 if (!(message = commit->buffer))
303 die ("Cannot get commit message for %s",
304 sha1_to_hex(commit->object.sha1));
305
306 /*
307 * "commit" is an existing commit. We would want to apply
308 * the difference it introduces since its first parent "prev"
309 * on top of the current HEAD if we are cherry-pick. Or the
310 * reverse of it if we are revert.
311 */
312
abda5227 313 msg_fd = hold_lock_file_for_update(&msg_file, defmsg, 1);
9509af68
JS
314
315 encoding = get_encoding(message);
316 if (!encoding)
317 encoding = "utf-8";
318 if (!git_commit_encoding)
319 git_commit_encoding = "utf-8";
320 if ((reencoded_message = reencode_string(message,
321 git_commit_encoding, encoding)))
322 message = reencoded_message;
323
324 oneline = get_oneline(message);
325
326 if (action == REVERT) {
e43b0105
JS
327 char *oneline_body = strchr(oneline, ' ');
328
9509af68 329 base = commit;
7791ecbc 330 next = parent;
e43b0105
JS
331 add_to_msg("Revert \"");
332 add_to_msg(oneline_body + 1);
333 add_to_msg("\"\n\nThis reverts commit ");
9509af68
JS
334 add_to_msg(sha1_to_hex(commit->object.sha1));
335 add_to_msg(".\n");
336 } else {
7791ecbc 337 base = parent;
9509af68
JS
338 next = commit;
339 set_author_ident_env(message);
340 add_message_to_msg(message);
0e624044
SP
341 if (!replay) {
342 add_to_msg("(cherry picked from commit ");
9509af68
JS
343 add_to_msg(sha1_to_hex(commit->object.sha1));
344 add_to_msg(")\n");
345 }
346 }
347 if (needed_deref) {
348 add_to_msg("(original 'git ");
349 add_to_msg(me);
350 add_to_msg("' arguments: ");
351 for (i = 0; i < argc; i++) {
352 if (i)
353 add_to_msg(" ");
354 add_to_msg(argv[i]);
355 }
356 add_to_msg(")\n");
357 }
358
359 if (merge_recursive(sha1_to_hex(base->object.sha1),
360 sha1_to_hex(head), "HEAD",
f52463a5
JS
361 sha1_to_hex(next->object.sha1), oneline) ||
362 write_tree(head, 0, NULL)) {
9509af68
JS
363 add_to_msg("\nConflicts:\n\n");
364 read_cache();
365 for (i = 0; i < active_nr;) {
366 struct cache_entry *ce = active_cache[i++];
367 if (ce_stage(ce)) {
368 add_to_msg("\t");
369 add_to_msg(ce->name);
370 add_to_msg("\n");
371 while (i < active_nr && !strcmp(ce->name,
372 active_cache[i]->name))
373 i++;
374 }
375 }
376 if (close(msg_fd) || commit_lock_file(&msg_file) < 0)
abda5227 377 die ("Error wrapping up %s", defmsg);
9509af68
JS
378 fprintf(stderr, "Automatic %s failed. "
379 "After resolving the conflicts,\n"
380 "mark the corrected paths with 'git-add <paths>'\n"
381 "and commit the result.\n", me);
382 if (action == CHERRY_PICK) {
f52463a5
JS
383 fprintf(stderr, "When commiting, use the option "
384 "'-c %s' to retain authorship and message.\n",
385 find_unique_abbrev(commit->object.sha1,
386 DEFAULT_ABBREV));
9509af68
JS
387 }
388 exit(1);
389 }
390 if (close(msg_fd) || commit_lock_file(&msg_file) < 0)
abda5227 391 die ("Error wrapping up %s", defmsg);
9509af68
JS
392 fprintf(stderr, "Finished one %s.\n", me);
393
394 /*
395 *
396 * If we are cherry-pick, and if the merge did not result in
397 * hand-editing, we will hit this commit and inherit the original
398 * author date and name.
399 * If we are revert, or if our cherry-pick results in a hand merge,
400 * we had better say that the current user is responsible for that.
401 */
402
403 if (!no_commit) {
404 if (edit)
abda5227 405 return execl_git_cmd("commit", "-n", NULL);
9509af68 406 else
abda5227 407 return execl_git_cmd("commit", "-n", "-F", defmsg, NULL);
9509af68
JS
408 }
409 if (reencoded_message)
410 free(reencoded_message);
411
412 return 0;
413}
414
415int cmd_revert(int argc, const char **argv, const char *prefix)
416{
417 if (isatty(0))
418 edit = 1;
419 action = REVERT;
420 return revert_or_cherry_pick(argc, argv);
421}
422
423int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
424{
425 replay = 1;
426 action = CHERRY_PICK;
427 return revert_or_cherry_pick(argc, argv);
428}