revert: use strbuf to refactor the code that writes the merge message
[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"
f8103794 10#include "parse-options.h"
45525bd0 11#include "cache-tree.h"
0f2d4476
JK
12#include "diff.h"
13#include "revision.h"
aa1a0111 14#include "rerere.h"
6eb1b437 15#include "merge-recursive.h"
9509af68
JS
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
f8103794 28static const char * const revert_usage[] = {
1b1dd23f 29 "git revert [options] <commit-ish>",
f8103794
PH
30 NULL
31};
9509af68 32
f8103794 33static const char * const cherry_pick_usage[] = {
1b1dd23f 34 "git cherry-pick [options] <commit-ish>",
f8103794
PH
35 NULL
36};
9509af68 37
cfd9c277 38static int edit, no_replay, no_commit, mainline, signoff;
4175e9e3 39static enum { REVERT, CHERRY_PICK } action;
9509af68 40static struct commit *commit;
97915544 41static const char *commit_name;
cb6020bb 42static int allow_rerere_auto;
9509af68
JS
43
44static const char *me;
45
46#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
47
d6856540
JN
48static char *get_encoding(const char *message);
49
f8103794 50static void parse_args(int argc, const char **argv)
9509af68 51{
f8103794
PH
52 const char * const * usage_str =
53 action == REVERT ? revert_usage : cherry_pick_usage;
9509af68 54 unsigned char sha1[20];
f8103794
PH
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)"),
cfd9c277 61 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
02273fdb 62 OPT_INTEGER('m', "mainline", &mainline, "parent number"),
cb6020bb 63 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
f8103794
PH
64 OPT_END(),
65 };
66
37782920 67 if (parse_options(argc, argv, NULL, options, usage_str, 0) != 1)
f8103794 68 usage_with_options(usage_str, options);
9509af68 69
97915544
JK
70 commit_name = argv[0];
71 if (get_sha1(commit_name, sha1))
72 die ("Cannot find '%s'", commit_name);
dd9314cc 73 commit = lookup_commit_reference(sha1);
9509af68 74 if (!commit)
dd9314cc 75 exit(1);
9509af68
JS
76}
77
d6856540
JN
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)
9509af68 87{
d6856540
JN
88 const char *encoding;
89 const char *p, *abbrev, *eol;
90 char *q;
9509af68
JS
91 int abbrev_len, oneline_len;
92
d6856540
JN
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;
9509af68
JS
109 while (*p && (*p != '\n' || p[1] != '\n'))
110 p++;
9509af68
JS
111 if (*p) {
112 p += 2;
113 for (eol = p + 1; *eol && *eol != '\n'; eol++)
114 ; /* do nothing */
115 } else
116 eol = p;
9509af68 117 oneline_len = eol - p;
d6856540
JN
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);
9509af68
JS
136}
137
52fae7de 138static char *get_encoding(const char *message)
9509af68
JS
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
bc84a7fb 160static void add_message_to_msg(struct strbuf *msgbuf, const char *message)
9509af68
JS
161{
162 const char *p = message;
163 while (*p && (*p != '\n' || p[1] != '\n'))
164 p++;
165
166 if (!*p)
bc84a7fb 167 strbuf_addstr(msgbuf, sha1_to_hex(commit->object.sha1));
9509af68
JS
168
169 p += 2;
bc84a7fb 170 strbuf_addstr(msgbuf, p);
9509af68
JS
171}
172
173static void set_author_ident_env(const char *message)
174{
175 const char *p = message;
176 if (!p)
177 die ("Could not read commit message of %s",
178 sha1_to_hex(commit->object.sha1));
179 while (*p && *p != '\n') {
180 const char *eol;
181
182 for (eol = p; *eol && *eol != '\n'; eol++)
183 ; /* do nothing */
184 if (!prefixcmp(p, "author ")) {
185 char *line, *pend, *email, *timestamp;
186
187 p += 7;
182af834 188 line = xmemdupz(p, eol - p);
9509af68
JS
189 email = strchr(line, '<');
190 if (!email)
191 die ("Could not extract author email from %s",
192 sha1_to_hex(commit->object.sha1));
193 if (email == line)
194 pend = line;
195 else
196 for (pend = email; pend != line + 1 &&
197 isspace(pend[-1]); pend--);
198 ; /* do nothing */
199 *pend = '\0';
200 email++;
201 timestamp = strchr(email, '>');
202 if (!timestamp)
1e5f7add 203 die ("Could not extract author time from %s",
9509af68
JS
204 sha1_to_hex(commit->object.sha1));
205 *timestamp = '\0';
206 for (timestamp++; *timestamp && isspace(*timestamp);
207 timestamp++)
208 ; /* do nothing */
209 setenv("GIT_AUTHOR_NAME", line, 1);
210 setenv("GIT_AUTHOR_EMAIL", email, 1);
211 setenv("GIT_AUTHOR_DATE", timestamp, 1);
212 free(line);
213 return;
214 }
215 p = eol;
216 if (*p == '\n')
217 p++;
218 }
219 die ("No author information found in %s",
220 sha1_to_hex(commit->object.sha1));
221}
222
97915544 223static char *help_msg(const char *name)
804c7174 224{
08565bdb 225 struct strbuf helpbuf = STRBUF_INIT;
804c7174
WC
226 char *msg = getenv("GIT_CHERRY_PICK_HELP");
227
228 if (msg)
229 return msg;
230
08565bdb 231 strbuf_addstr(&helpbuf, " After resolving the conflicts,\n"
6e359978 232 "mark the corrected paths with 'git add <paths>' or 'git rm <paths>'\n"
4d128884 233 "and commit the result");
804c7174
WC
234
235 if (action == CHERRY_PICK) {
4d128884
JK
236 strbuf_addf(&helpbuf, " with: \n"
237 "\n"
238 " git commit -c %s\n",
97915544 239 name);
804c7174 240 }
4d128884
JK
241 else
242 strbuf_addch(&helpbuf, '.');
08565bdb 243 return strbuf_detach(&helpbuf, NULL);
804c7174
WC
244}
245
bc84a7fb
CC
246static void write_message(struct strbuf *msgbuf, const char *filename)
247{
248 static struct lock_file msg_file;
249
250 int msg_fd = hold_lock_file_for_update(&msg_file, filename,
251 LOCK_DIE_ON_ERROR);
252 if (write_in_full(msg_fd, msgbuf->buf, msgbuf->len) < 0)
253 die_errno("Could not write to %s.", filename);
254 strbuf_release(msgbuf);
255 if (commit_lock_file(&msg_file) < 0)
256 die("Error wrapping up %s", filename);
257}
258
6eb1b437
MV
259static struct tree *empty_tree(void)
260{
261 struct tree *tree = xcalloc(1, sizeof(struct tree));
262
263 tree->object.parsed = 1;
264 tree->object.type = OBJ_TREE;
265 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
266 return tree;
267}
268
d38a30df
MM
269static NORETURN void die_dirty_index(const char *me)
270{
271 if (read_cache_unmerged()) {
272 die_resolve_conflict(me);
273 } else {
274 if (advice_commit_before_merge)
275 die("Your local changes would be overwritten by %s.\n"
276 "Please, commit your changes or stash them to proceed.", me);
277 else
278 die("Your local changes would be overwritten by %s.\n", me);
279 }
280}
281
9509af68
JS
282static int revert_or_cherry_pick(int argc, const char **argv)
283{
284 unsigned char head[20];
7791ecbc 285 struct commit *base, *next, *parent;
bf975d37 286 const char *base_label, *next_label;
6eb1b437 287 int i, index_fd, clean;
d6856540
JN
288 struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
289
a1a846a1 290 char *defmsg = git_pathdup("MERGE_MSG");
6eb1b437
MV
291 struct merge_options o;
292 struct tree *result, *next_tree, *base_tree, *head_tree;
293 static struct lock_file index_lock;
bc84a7fb 294 struct strbuf msgbuf = STRBUF_INIT;
9509af68 295
ef90d6d4 296 git_config(git_default_config, NULL);
9509af68
JS
297 me = action == REVERT ? "revert" : "cherry-pick";
298 setenv(GIT_REFLOG_ACTION, me, 0);
f8103794 299 parse_args(argc, argv);
9509af68
JS
300
301 /* this is copied from the shell script, but it's never triggered... */
f8103794 302 if (action == REVERT && !no_replay)
9509af68
JS
303 die("revert is incompatible with replay");
304
6eb1b437
MV
305 if (read_cache() < 0)
306 die("git %s: failed to read the index", me);
9509af68
JS
307 if (no_commit) {
308 /*
309 * We do not intend to commit immediately. We just want to
71aa2b8f
JH
310 * merge the differences in, so let's compute the tree
311 * that represents the "current" state for merge-recursive
312 * to work on.
9509af68 313 */
45525bd0 314 if (write_cache_as_tree(head, 0, NULL))
9509af68
JS
315 die ("Your index file is unmerged.");
316 } else {
9509af68
JS
317 if (get_sha1("HEAD", head))
318 die ("You do not have a valid HEAD");
75f3ff2e 319 if (index_differs_from("HEAD", 0))
d38a30df 320 die_dirty_index(me);
9509af68 321 }
6eb1b437
MV
322 discard_cache();
323
324 index_fd = hold_locked_index(&index_lock, 1);
9509af68 325
f95ebf74
JS
326 if (!commit->parents) {
327 if (action == REVERT)
328 die ("Cannot revert a root commit");
329 parent = NULL;
330 }
331 else if (commit->parents->next) {
7791ecbc
JH
332 /* Reverting or cherry-picking a merge commit */
333 int cnt;
334 struct commit_list *p;
335
336 if (!mainline)
337 die("Commit %s is a merge but no -m option was given.",
338 sha1_to_hex(commit->object.sha1));
339
340 for (cnt = 1, p = commit->parents;
341 cnt != mainline && p;
342 cnt++)
343 p = p->next;
344 if (cnt != mainline || !p)
345 die("Commit %s does not have parent %d",
346 sha1_to_hex(commit->object.sha1), mainline);
347 parent = p->item;
348 } else if (0 < mainline)
349 die("Mainline was specified but commit %s is not a merge.",
350 sha1_to_hex(commit->object.sha1));
351 else
352 parent = commit->parents->item;
353
6eb1b437
MV
354 if (parent && parse_commit(parent) < 0)
355 die("%s: cannot parse parent commit %s",
356 me, sha1_to_hex(parent->object.sha1));
357
d6856540
JN
358 if (get_message(commit->buffer, &msg) != 0)
359 die("Cannot get commit message for %s",
360 sha1_to_hex(commit->object.sha1));
361
9509af68
JS
362 /*
363 * "commit" is an existing commit. We would want to apply
364 * the difference it introduces since its first parent "prev"
365 * on top of the current HEAD if we are cherry-pick. Or the
366 * reverse of it if we are revert.
367 */
368
9509af68
JS
369 if (action == REVERT) {
370 base = commit;
bf975d37 371 base_label = msg.label;
7791ecbc 372 next = parent;
d6856540 373 next_label = msg.parent_label;
bc84a7fb
CC
374 strbuf_addstr(&msgbuf, "Revert \"");
375 strbuf_addstr(&msgbuf, msg.subject);
376 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
377 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
d5be89d8
RR
378
379 if (commit->parents->next) {
bc84a7fb
CC
380 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
381 strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
d5be89d8 382 }
bc84a7fb 383 strbuf_addstr(&msgbuf, ".\n");
9509af68 384 } else {
7791ecbc 385 base = parent;
bf975d37 386 base_label = msg.parent_label;
9509af68 387 next = commit;
d6856540
JN
388 next_label = msg.label;
389 set_author_ident_env(msg.message);
bc84a7fb 390 add_message_to_msg(&msgbuf, msg.message);
f8103794 391 if (no_replay) {
bc84a7fb
CC
392 strbuf_addstr(&msgbuf, "(cherry picked from commit ");
393 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
394 strbuf_addstr(&msgbuf, ")\n");
9509af68
JS
395 }
396 }
9509af68 397
6eb1b437
MV
398 read_cache();
399 init_merge_options(&o);
bf975d37 400 o.ancestor = base ? base_label : "(empty tree)";
6eb1b437 401 o.branch1 = "HEAD";
d6856540 402 o.branch2 = next ? next_label : "(empty tree)";
6eb1b437
MV
403
404 head_tree = parse_tree_indirect(head);
405 next_tree = next ? next->tree : empty_tree();
406 base_tree = base ? base->tree : empty_tree();
407
408 clean = merge_trees(&o,
409 head_tree,
410 next_tree, base_tree, &result);
411
412 if (active_cache_changed &&
413 (write_cache(index_fd, active_cache, active_nr) ||
414 commit_locked_index(&index_lock)))
415 die("%s: Unable to write new index file", me);
0d66e959 416 rollback_lock_file(&index_lock);
6eb1b437
MV
417
418 if (!clean) {
bc84a7fb 419 strbuf_addstr(&msgbuf, "\nConflicts:\n\n");
9509af68
JS
420 for (i = 0; i < active_nr;) {
421 struct cache_entry *ce = active_cache[i++];
422 if (ce_stage(ce)) {
bc84a7fb
CC
423 strbuf_addch(&msgbuf, '\t');
424 strbuf_addstr(&msgbuf, ce->name);
425 strbuf_addch(&msgbuf, '\n');
9509af68
JS
426 while (i < active_nr && !strcmp(ce->name,
427 active_cache[i]->name))
428 i++;
429 }
430 }
bc84a7fb 431 write_message(&msgbuf, defmsg);
804c7174 432 fprintf(stderr, "Automatic %s failed.%s\n",
97915544 433 me, help_msg(commit_name));
cb6020bb 434 rerere(allow_rerere_auto);
9509af68
JS
435 exit(1);
436 }
bc84a7fb 437 write_message(&msgbuf, defmsg);
9509af68
JS
438 fprintf(stderr, "Finished one %s.\n", me);
439
440 /*
441 *
442 * If we are cherry-pick, and if the merge did not result in
443 * hand-editing, we will hit this commit and inherit the original
444 * author date and name.
445 * If we are revert, or if our cherry-pick results in a hand merge,
446 * we had better say that the current user is responsible for that.
447 */
448
449 if (!no_commit) {
cfd9c277
DM
450 /* 6 is max possible length of our args array including NULL */
451 const char *args[6];
452 int i = 0;
453 args[i++] = "commit";
454 args[i++] = "-n";
455 if (signoff)
456 args[i++] = "-s";
457 if (!edit) {
458 args[i++] = "-F";
459 args[i++] = defmsg;
460 }
461 args[i] = NULL;
462 return execv_git_cmd(args);
9509af68 463 }
d6856540 464 free_message(&msg);
d258b258 465 free(defmsg);
9509af68
JS
466
467 return 0;
468}
469
470int cmd_revert(int argc, const char **argv, const char *prefix)
471{
472 if (isatty(0))
473 edit = 1;
f8103794 474 no_replay = 1;
9509af68
JS
475 action = REVERT;
476 return revert_or_cherry_pick(argc, argv);
477}
478
479int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
480{
f8103794 481 no_replay = 0;
9509af68
JS
482 action = CHERRY_PICK;
483 return revert_or_cherry_pick(argc, argv);
484}