Merge branch 'jc/replacing'
[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 "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
28 static const char * const revert_usage[] = {
29         "git revert [options] <commit-ish>",
30         NULL
31 };
32
33 static const char * const cherry_pick_usage[] = {
34         "git cherry-pick [options] <commit-ish>",
35         NULL
36 };
37
38 static int edit, no_replay, no_commit, mainline, signoff, allow_ff;
39 static enum { REVERT, CHERRY_PICK } action;
40 static struct commit *commit;
41 static int commit_argc;
42 static const char **commit_argv;
43 static int allow_rerere_auto;
44
45 static const char *me;
46
47 /* Merge strategy. */
48 static const char *strategy;
49 static const char **xopts;
50 static size_t xopts_nr, xopts_alloc;
51
52 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
53
54 static char *get_encoding(const char *message);
55
56 static const char * const *revert_or_cherry_pick_usage(void)
57 {
58         return action == REVERT ? revert_usage : cherry_pick_usage;
59 }
60
61 static int option_parse_x(const struct option *opt,
62                           const char *arg, int unset)
63 {
64         if (unset)
65                 return 0;
66
67         ALLOC_GROW(xopts, xopts_nr + 1, xopts_alloc);
68         xopts[xopts_nr++] = xstrdup(arg);
69         return 0;
70 }
71
72 static void parse_args(int argc, const char **argv)
73 {
74         const char * const * usage_str = revert_or_cherry_pick_usage();
75         int noop;
76         struct option options[] = {
77                 OPT_BOOLEAN('n', "no-commit", &no_commit, "don't automatically commit"),
78                 OPT_BOOLEAN('e', "edit", &edit, "edit the commit message"),
79                 { OPTION_BOOLEAN, 'r', NULL, &noop, NULL, "no-op (backward compatibility)",
80                   PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 0 },
81                 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
82                 OPT_INTEGER('m', "mainline", &mainline, "parent number"),
83                 OPT_RERERE_AUTOUPDATE(&allow_rerere_auto),
84                 OPT_STRING(0, "strategy", &strategy, "strategy", "merge strategy"),
85                 OPT_CALLBACK('X', "strategy-option", &xopts, "option",
86                         "option for merge strategy", option_parse_x),
87                 OPT_END(),
88                 OPT_END(),
89                 OPT_END(),
90         };
91
92         if (action == CHERRY_PICK) {
93                 struct option cp_extra[] = {
94                         OPT_BOOLEAN('x', NULL, &no_replay, "append commit name"),
95                         OPT_BOOLEAN(0, "ff", &allow_ff, "allow fast-forward"),
96                         OPT_END(),
97                 };
98                 if (parse_options_concat(options, ARRAY_SIZE(options), cp_extra))
99                         die(_("program error"));
100         }
101
102         commit_argc = parse_options(argc, argv, NULL, options, usage_str,
103                                     PARSE_OPT_KEEP_ARGV0 |
104                                     PARSE_OPT_KEEP_UNKNOWN);
105         if (commit_argc < 2)
106                 usage_with_options(usage_str, options);
107
108         commit_argv = argv;
109 }
110
111 struct commit_message {
112         char *parent_label;
113         const char *label;
114         const char *subject;
115         char *reencoded_message;
116         const char *message;
117 };
118
119 static int get_message(const char *raw_message, struct commit_message *out)
120 {
121         const char *encoding;
122         const char *abbrev, *subject;
123         int abbrev_len, subject_len;
124         char *q;
125
126         if (!raw_message)
127                 return -1;
128         encoding = get_encoding(raw_message);
129         if (!encoding)
130                 encoding = "UTF-8";
131         if (!git_commit_encoding)
132                 git_commit_encoding = "UTF-8";
133
134         out->reencoded_message = NULL;
135         out->message = raw_message;
136         if (strcmp(encoding, git_commit_encoding))
137                 out->reencoded_message = reencode_string(raw_message,
138                                         git_commit_encoding, encoding);
139         if (out->reencoded_message)
140                 out->message = out->reencoded_message;
141
142         abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
143         abbrev_len = strlen(abbrev);
144
145         subject_len = find_commit_subject(out->message, &subject);
146
147         out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
148                               strlen("... ") + subject_len + 1);
149         q = out->parent_label;
150         q = mempcpy(q, "parent of ", strlen("parent of "));
151         out->label = q;
152         q = mempcpy(q, abbrev, abbrev_len);
153         q = mempcpy(q, "... ", strlen("... "));
154         out->subject = q;
155         q = mempcpy(q, subject, subject_len);
156         *q = '\0';
157         return 0;
158 }
159
160 static void free_message(struct commit_message *msg)
161 {
162         free(msg->parent_label);
163         free(msg->reencoded_message);
164 }
165
166 static char *get_encoding(const char *message)
167 {
168         const char *p = message, *eol;
169
170         if (!p)
171                 die (_("Could not read commit message of %s"),
172                                 sha1_to_hex(commit->object.sha1));
173         while (*p && *p != '\n') {
174                 for (eol = p + 1; *eol && *eol != '\n'; eol++)
175                         ; /* do nothing */
176                 if (!prefixcmp(p, "encoding ")) {
177                         char *result = xmalloc(eol - 8 - p);
178                         strlcpy(result, p + 9, eol - 8 - p);
179                         return result;
180                 }
181                 p = eol;
182                 if (*p == '\n')
183                         p++;
184         }
185         return NULL;
186 }
187
188 static void add_message_to_msg(struct strbuf *msgbuf, const char *message)
189 {
190         const char *p = message;
191         while (*p && (*p != '\n' || p[1] != '\n'))
192                 p++;
193
194         if (!*p)
195                 strbuf_addstr(msgbuf, sha1_to_hex(commit->object.sha1));
196
197         p += 2;
198         strbuf_addstr(msgbuf, p);
199 }
200
201 static void write_cherry_pick_head(void)
202 {
203         int fd;
204         struct strbuf buf = STRBUF_INIT;
205
206         strbuf_addf(&buf, "%s\n", sha1_to_hex(commit->object.sha1));
207
208         fd = open(git_path("CHERRY_PICK_HEAD"), O_WRONLY | O_CREAT, 0666);
209         if (fd < 0)
210                 die_errno(_("Could not open '%s' for writing"),
211                           git_path("CHERRY_PICK_HEAD"));
212         if (write_in_full(fd, buf.buf, buf.len) != buf.len || close(fd))
213                 die_errno(_("Could not write to '%s'"), git_path("CHERRY_PICK_HEAD"));
214         strbuf_release(&buf);
215 }
216
217 static void advise(const char *advice, ...)
218 {
219         va_list params;
220
221         va_start(params, advice);
222         vreportf("hint: ", advice, params);
223         va_end(params);
224 }
225
226 static void print_advice(void)
227 {
228         char *msg = getenv("GIT_CHERRY_PICK_HELP");
229
230         if (msg) {
231                 fprintf(stderr, "%s\n", msg);
232                 /*
233                  * A conflict has occured but the porcelain
234                  * (typically rebase --interactive) wants to take care
235                  * of the commit itself so remove CHERRY_PICK_HEAD
236                  */
237                 unlink(git_path("CHERRY_PICK_HEAD"));
238                 return;
239         }
240
241         advise("after resolving the conflicts, mark the corrected paths");
242         advise("with 'git add <paths>' or 'git rm <paths>'");
243         advise("and commit the result with 'git commit'");
244 }
245
246 static 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
259 static 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
269 static 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                         if (action == REVERT)
276                                 die(_("Your local changes would be overwritten by revert.\n"
277                                           "Please, commit your changes or stash them to proceed."));
278                         else
279                                 die(_("Your local changes would be overwritten by cherry-pick.\n"
280                                           "Please, commit your changes or stash them to proceed."));
281                 } else {
282                         if (action == REVERT)
283                                 die(_("Your local changes would be overwritten by revert.\n"));
284                         else
285                                 die(_("Your local changes would be overwritten by cherry-pick.\n"));
286                 }
287         }
288 }
289
290 static int fast_forward_to(const unsigned char *to, const unsigned char *from)
291 {
292         struct ref_lock *ref_lock;
293
294         read_cache();
295         if (checkout_fast_forward(from, to))
296                 exit(1); /* the callee should have complained already */
297         ref_lock = lock_any_ref_for_update("HEAD", from, 0);
298         return write_ref_sha1(ref_lock, to, "cherry-pick");
299 }
300
301 static int do_recursive_merge(struct commit *base, struct commit *next,
302                               const char *base_label, const char *next_label,
303                               unsigned char *head, struct strbuf *msgbuf)
304 {
305         struct merge_options o;
306         struct tree *result, *next_tree, *base_tree, *head_tree;
307         int clean, index_fd;
308         const char **xopt;
309         static struct lock_file index_lock;
310
311         index_fd = hold_locked_index(&index_lock, 1);
312
313         read_cache();
314
315         init_merge_options(&o);
316         o.ancestor = base ? base_label : "(empty tree)";
317         o.branch1 = "HEAD";
318         o.branch2 = next ? next_label : "(empty tree)";
319
320         head_tree = parse_tree_indirect(head);
321         next_tree = next ? next->tree : empty_tree();
322         base_tree = base ? base->tree : empty_tree();
323
324         for (xopt = xopts; xopt != xopts + xopts_nr; xopt++)
325                 parse_merge_opt(&o, *xopt);
326
327         clean = merge_trees(&o,
328                             head_tree,
329                             next_tree, base_tree, &result);
330
331         if (active_cache_changed &&
332             (write_cache(index_fd, active_cache, active_nr) ||
333              commit_locked_index(&index_lock)))
334                 /* TRANSLATORS: %s will be "revert" or "cherry-pick" */
335                 die(_("%s: Unable to write new index file"), me);
336         rollback_lock_file(&index_lock);
337
338         if (!clean) {
339                 int i;
340                 strbuf_addstr(msgbuf, "\nConflicts:\n\n");
341                 for (i = 0; i < active_nr;) {
342                         struct cache_entry *ce = active_cache[i++];
343                         if (ce_stage(ce)) {
344                                 strbuf_addch(msgbuf, '\t');
345                                 strbuf_addstr(msgbuf, ce->name);
346                                 strbuf_addch(msgbuf, '\n');
347                                 while (i < active_nr && !strcmp(ce->name,
348                                                 active_cache[i]->name))
349                                         i++;
350                         }
351                 }
352         }
353
354         return !clean;
355 }
356
357 /*
358  * If we are cherry-pick, and if the merge did not result in
359  * hand-editing, we will hit this commit and inherit the original
360  * author date and name.
361  * If we are revert, or if our cherry-pick results in a hand merge,
362  * we had better say that the current user is responsible for that.
363  */
364 static int run_git_commit(const char *defmsg)
365 {
366         /* 6 is max possible length of our args array including NULL */
367         const char *args[6];
368         int i = 0;
369
370         args[i++] = "commit";
371         args[i++] = "-n";
372         if (signoff)
373                 args[i++] = "-s";
374         if (!edit) {
375                 args[i++] = "-F";
376                 args[i++] = defmsg;
377         }
378         args[i] = NULL;
379
380         return run_command_v_opt(args, RUN_GIT_CMD);
381 }
382
383 static int do_pick_commit(void)
384 {
385         unsigned char head[20];
386         struct commit *base, *next, *parent;
387         const char *base_label, *next_label;
388         struct commit_message msg = { NULL, NULL, NULL, NULL, NULL };
389         char *defmsg = NULL;
390         struct strbuf msgbuf = STRBUF_INIT;
391         int res;
392
393         if (no_commit) {
394                 /*
395                  * We do not intend to commit immediately.  We just want to
396                  * merge the differences in, so let's compute the tree
397                  * that represents the "current" state for merge-recursive
398                  * to work on.
399                  */
400                 if (write_cache_as_tree(head, 0, NULL))
401                         die (_("Your index file is unmerged."));
402         } else {
403                 if (get_sha1("HEAD", head))
404                         die (_("You do not have a valid HEAD"));
405                 if (index_differs_from("HEAD", 0))
406                         die_dirty_index(me);
407         }
408         discard_cache();
409
410         if (!commit->parents) {
411                 parent = NULL;
412         }
413         else if (commit->parents->next) {
414                 /* Reverting or cherry-picking a merge commit */
415                 int cnt;
416                 struct commit_list *p;
417
418                 if (!mainline)
419                         die(_("Commit %s is a merge but no -m option was given."),
420                             sha1_to_hex(commit->object.sha1));
421
422                 for (cnt = 1, p = commit->parents;
423                      cnt != mainline && p;
424                      cnt++)
425                         p = p->next;
426                 if (cnt != mainline || !p)
427                         die(_("Commit %s does not have parent %d"),
428                             sha1_to_hex(commit->object.sha1), mainline);
429                 parent = p->item;
430         } else if (0 < mainline)
431                 die(_("Mainline was specified but commit %s is not a merge."),
432                     sha1_to_hex(commit->object.sha1));
433         else
434                 parent = commit->parents->item;
435
436         if (allow_ff && parent && !hashcmp(parent->object.sha1, head))
437                 return fast_forward_to(commit->object.sha1, head);
438
439         if (parent && parse_commit(parent) < 0)
440                 /* TRANSLATORS: The first %s will be "revert" or
441                    "cherry-pick", the second %s a SHA1 */
442                 die(_("%s: cannot parse parent commit %s"),
443                     me, sha1_to_hex(parent->object.sha1));
444
445         if (get_message(commit->buffer, &msg) != 0)
446                 die(_("Cannot get commit message for %s"),
447                                 sha1_to_hex(commit->object.sha1));
448
449         /*
450          * "commit" is an existing commit.  We would want to apply
451          * the difference it introduces since its first parent "prev"
452          * on top of the current HEAD if we are cherry-pick.  Or the
453          * reverse of it if we are revert.
454          */
455
456         defmsg = git_pathdup("MERGE_MSG");
457
458         if (action == REVERT) {
459                 base = commit;
460                 base_label = msg.label;
461                 next = parent;
462                 next_label = msg.parent_label;
463                 strbuf_addstr(&msgbuf, "Revert \"");
464                 strbuf_addstr(&msgbuf, msg.subject);
465                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
466                 strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
467
468                 if (commit->parents && commit->parents->next) {
469                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
470                         strbuf_addstr(&msgbuf, sha1_to_hex(parent->object.sha1));
471                 }
472                 strbuf_addstr(&msgbuf, ".\n");
473         } else {
474                 base = parent;
475                 base_label = msg.parent_label;
476                 next = commit;
477                 next_label = msg.label;
478                 add_message_to_msg(&msgbuf, msg.message);
479                 if (no_replay) {
480                         strbuf_addstr(&msgbuf, "(cherry picked from commit ");
481                         strbuf_addstr(&msgbuf, sha1_to_hex(commit->object.sha1));
482                         strbuf_addstr(&msgbuf, ")\n");
483                 }
484                 if (!no_commit)
485                         write_cherry_pick_head();
486         }
487
488         if (!strategy || !strcmp(strategy, "recursive") || action == REVERT) {
489                 res = do_recursive_merge(base, next, base_label, next_label,
490                                          head, &msgbuf);
491                 write_message(&msgbuf, defmsg);
492         } else {
493                 struct commit_list *common = NULL;
494                 struct commit_list *remotes = NULL;
495
496                 write_message(&msgbuf, defmsg);
497
498                 commit_list_insert(base, &common);
499                 commit_list_insert(next, &remotes);
500                 res = try_merge_command(strategy, xopts_nr, xopts, common,
501                                         sha1_to_hex(head), remotes);
502                 free_commit_list(common);
503                 free_commit_list(remotes);
504         }
505
506         if (res) {
507                 error(action == REVERT
508                       ? _("could not revert %s... %s")
509                       : _("could not apply %s... %s"),
510                       find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV),
511                       msg.subject);
512                 print_advice();
513                 rerere(allow_rerere_auto);
514         } else {
515                 if (!no_commit)
516                         res = run_git_commit(defmsg);
517         }
518
519         free_message(&msg);
520         free(defmsg);
521
522         return res;
523 }
524
525 static void prepare_revs(struct rev_info *revs)
526 {
527         int argc;
528
529         init_revisions(revs, NULL);
530         revs->no_walk = 1;
531         if (action != REVERT)
532                 revs->reverse = 1;
533
534         argc = setup_revisions(commit_argc, commit_argv, revs, NULL);
535         if (argc > 1)
536                 usage(*revert_or_cherry_pick_usage());
537
538         if (prepare_revision_walk(revs))
539                 die(_("revision walk setup failed"));
540
541         if (!revs->commits)
542                 die(_("empty commit set passed"));
543 }
544
545 static void read_and_refresh_cache(const char *me)
546 {
547         static struct lock_file index_lock;
548         int index_fd = hold_locked_index(&index_lock, 0);
549         if (read_index_preload(&the_index, NULL) < 0)
550                 die(_("git %s: failed to read the index"), me);
551         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
552         if (the_index.cache_changed) {
553                 if (write_index(&the_index, index_fd) ||
554                     commit_locked_index(&index_lock))
555                         die(_("git %s: failed to refresh the index"), me);
556         }
557         rollback_lock_file(&index_lock);
558 }
559
560 static int revert_or_cherry_pick(int argc, const char **argv)
561 {
562         struct rev_info revs;
563
564         git_config(git_default_config, NULL);
565         me = action == REVERT ? "revert" : "cherry-pick";
566         setenv(GIT_REFLOG_ACTION, me, 0);
567         parse_args(argc, argv);
568
569         if (allow_ff) {
570                 if (signoff)
571                         die(_("cherry-pick --ff cannot be used with --signoff"));
572                 if (no_commit)
573                         die(_("cherry-pick --ff cannot be used with --no-commit"));
574                 if (no_replay)
575                         die(_("cherry-pick --ff cannot be used with -x"));
576                 if (edit)
577                         die(_("cherry-pick --ff cannot be used with --edit"));
578         }
579
580         read_and_refresh_cache(me);
581
582         prepare_revs(&revs);
583
584         while ((commit = get_revision(&revs))) {
585                 int res = do_pick_commit();
586                 if (res)
587                         return res;
588         }
589
590         return 0;
591 }
592
593 int cmd_revert(int argc, const char **argv, const char *prefix)
594 {
595         if (isatty(0))
596                 edit = 1;
597         action = REVERT;
598         return revert_or_cherry_pick(argc, argv);
599 }
600
601 int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
602 {
603         action = CHERRY_PICK;
604         return revert_or_cherry_pick(argc, argv);
605 }