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