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