]> asedeno.scripts.mit.edu Git - git.git/blob - builtin-revert.c
Be more user-friendly when refusing to do something because of conflict.
[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
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;
39 static enum { REVERT, CHERRY_PICK } action;
40 static struct commit *commit;
41
42 static const char *me;
43
44 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
45
46 static void parse_args(int argc, const char **argv)
47 {
48         const char * const * usage_str =
49                 action == REVERT ?  revert_usage : cherry_pick_usage;
50         unsigned char sha1[20];
51         const char *arg;
52         int noop;
53         struct option options[] = {
54                 OPT_BOOLEAN('n', "no-commit", &no_commit, "don't automatically commit"),
55                 OPT_BOOLEAN('e', "edit", &edit, "edit the commit message"),
56                 OPT_BOOLEAN('x', NULL, &no_replay, "append commit name when cherry-picking"),
57                 OPT_BOOLEAN('r', NULL, &noop, "no-op (backward compatibility)"),
58                 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
59                 OPT_INTEGER('m', "mainline", &mainline, "parent number"),
60                 OPT_END(),
61         };
62
63         if (parse_options(argc, argv, NULL, options, usage_str, 0) != 1)
64                 usage_with_options(usage_str, options);
65         arg = argv[0];
66
67         if (get_sha1(arg, sha1))
68                 die ("Cannot find '%s'", arg);
69         commit = (struct commit *)parse_object(sha1);
70         if (!commit)
71                 die ("Could not find %s", sha1_to_hex(sha1));
72         if (commit->object.type == OBJ_TAG) {
73                 commit = (struct commit *)
74                         deref_tag((struct object *)commit, arg, strlen(arg));
75         }
76         if (commit->object.type != OBJ_COMMIT)
77                 die ("'%s' does not point to a commit", arg);
78 }
79
80 static char *get_oneline(const char *message)
81 {
82         char *result;
83         const char *p = message, *abbrev, *eol;
84         int abbrev_len, oneline_len;
85
86         if (!p)
87                 die ("Could not read commit message of %s",
88                                 sha1_to_hex(commit->object.sha1));
89         while (*p && (*p != '\n' || p[1] != '\n'))
90                 p++;
91
92         if (*p) {
93                 p += 2;
94                 for (eol = p + 1; *eol && *eol != '\n'; eol++)
95                         ; /* do nothing */
96         } else
97                 eol = p;
98         abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
99         abbrev_len = strlen(abbrev);
100         oneline_len = eol - p;
101         result = xmalloc(abbrev_len + 5 + oneline_len);
102         memcpy(result, abbrev, abbrev_len);
103         memcpy(result + abbrev_len, "... ", 4);
104         memcpy(result + abbrev_len + 4, p, oneline_len);
105         result[abbrev_len + 4 + oneline_len] = '\0';
106         return result;
107 }
108
109 static char *get_encoding(const char *message)
110 {
111         const char *p = message, *eol;
112
113         if (!p)
114                 die ("Could not read commit message of %s",
115                                 sha1_to_hex(commit->object.sha1));
116         while (*p && *p != '\n') {
117                 for (eol = p + 1; *eol && *eol != '\n'; eol++)
118                         ; /* do nothing */
119                 if (!prefixcmp(p, "encoding ")) {
120                         char *result = xmalloc(eol - 8 - p);
121                         strlcpy(result, p + 9, eol - 8 - p);
122                         return result;
123                 }
124                 p = eol;
125                 if (*p == '\n')
126                         p++;
127         }
128         return NULL;
129 }
130
131 static struct lock_file msg_file;
132 static int msg_fd;
133
134 static void add_to_msg(const char *string)
135 {
136         int len = strlen(string);
137         if (write_in_full(msg_fd, string, len) < 0)
138                 die_errno ("Could not write to MERGE_MSG");
139 }
140
141 static void add_message_to_msg(const char *message)
142 {
143         const char *p = message;
144         while (*p && (*p != '\n' || p[1] != '\n'))
145                 p++;
146
147         if (!*p)
148                 add_to_msg(sha1_to_hex(commit->object.sha1));
149
150         p += 2;
151         add_to_msg(p);
152         return;
153 }
154
155 static void set_author_ident_env(const char *message)
156 {
157         const char *p = message;
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                 const char *eol;
163
164                 for (eol = p; *eol && *eol != '\n'; eol++)
165                         ; /* do nothing */
166                 if (!prefixcmp(p, "author ")) {
167                         char *line, *pend, *email, *timestamp;
168
169                         p += 7;
170                         line = xmemdupz(p, eol - p);
171                         email = strchr(line, '<');
172                         if (!email)
173                                 die ("Could not extract author email from %s",
174                                         sha1_to_hex(commit->object.sha1));
175                         if (email == line)
176                                 pend = line;
177                         else
178                                 for (pend = email; pend != line + 1 &&
179                                                 isspace(pend[-1]); pend--);
180                                         ; /* do nothing */
181                         *pend = '\0';
182                         email++;
183                         timestamp = strchr(email, '>');
184                         if (!timestamp)
185                                 die ("Could not extract author time from %s",
186                                         sha1_to_hex(commit->object.sha1));
187                         *timestamp = '\0';
188                         for (timestamp++; *timestamp && isspace(*timestamp);
189                                         timestamp++)
190                                 ; /* do nothing */
191                         setenv("GIT_AUTHOR_NAME", line, 1);
192                         setenv("GIT_AUTHOR_EMAIL", email, 1);
193                         setenv("GIT_AUTHOR_DATE", timestamp, 1);
194                         free(line);
195                         return;
196                 }
197                 p = eol;
198                 if (*p == '\n')
199                         p++;
200         }
201         die ("No author information found in %s",
202                         sha1_to_hex(commit->object.sha1));
203 }
204
205 static char *help_msg(const unsigned char *sha1)
206 {
207         static char helpbuf[1024];
208         char *msg = getenv("GIT_CHERRY_PICK_HELP");
209
210         if (msg)
211                 return msg;
212
213         strcpy(helpbuf, "  After resolving the conflicts,\n"
214                "mark the corrected paths with 'git add <paths>' "
215                "or 'git rm <paths>' and commit the result.");
216
217         if (action == CHERRY_PICK) {
218                 sprintf(helpbuf + strlen(helpbuf),
219                         "\nWhen commiting, use the option "
220                         "'-c %s' to retain authorship and message.",
221                         find_unique_abbrev(sha1, DEFAULT_ABBREV));
222         }
223         return helpbuf;
224 }
225
226 static struct tree *empty_tree(void)
227 {
228         struct tree *tree = xcalloc(1, sizeof(struct tree));
229
230         tree->object.parsed = 1;
231         tree->object.type = OBJ_TREE;
232         pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
233         return tree;
234 }
235
236 static NORETURN void die_dirty_index(const char *me)
237 {
238         if (read_cache_unmerged()) {
239                 die_resolve_conflict(me);
240         } else {
241                 if (advice_commit_before_merge)
242                         die("Your local changes would be overwritten by %s.\n"
243                             "Please, commit your changes or stash them to proceed.", me);
244                 else
245                         die("Your local changes would be overwritten by %s.\n", me);
246         }
247 }
248
249 static int revert_or_cherry_pick(int argc, const char **argv)
250 {
251         unsigned char head[20];
252         struct commit *base, *next, *parent;
253         int i, index_fd, clean;
254         char *oneline, *reencoded_message = NULL;
255         const char *message, *encoding;
256         char *defmsg = git_pathdup("MERGE_MSG");
257         struct merge_options o;
258         struct tree *result, *next_tree, *base_tree, *head_tree;
259         static struct lock_file index_lock;
260
261         git_config(git_default_config, NULL);
262         me = action == REVERT ? "revert" : "cherry-pick";
263         setenv(GIT_REFLOG_ACTION, me, 0);
264         parse_args(argc, argv);
265
266         /* this is copied from the shell script, but it's never triggered... */
267         if (action == REVERT && !no_replay)
268                 die("revert is incompatible with replay");
269
270         if (read_cache() < 0)
271                 die("git %s: failed to read the index", me);
272         if (no_commit) {
273                 /*
274                  * We do not intend to commit immediately.  We just want to
275                  * merge the differences in, so let's compute the tree
276                  * that represents the "current" state for merge-recursive
277                  * to work on.
278                  */
279                 if (write_cache_as_tree(head, 0, NULL))
280                         die ("Your index file is unmerged.");
281         } else {
282                 if (get_sha1("HEAD", head))
283                         die ("You do not have a valid HEAD");
284                 if (index_differs_from("HEAD", 0))
285                         die_dirty_index(me);
286         }
287         discard_cache();
288
289         index_fd = hold_locked_index(&index_lock, 1);
290
291         if (!commit->parents) {
292                 if (action == REVERT)
293                         die ("Cannot revert a root commit");
294                 parent = NULL;
295         }
296         else if (commit->parents->next) {
297                 /* Reverting or cherry-picking a merge commit */
298                 int cnt;
299                 struct commit_list *p;
300
301                 if (!mainline)
302                         die("Commit %s is a merge but no -m option was given.",
303                             sha1_to_hex(commit->object.sha1));
304
305                 for (cnt = 1, p = commit->parents;
306                      cnt != mainline && p;
307                      cnt++)
308                         p = p->next;
309                 if (cnt != mainline || !p)
310                         die("Commit %s does not have parent %d",
311                             sha1_to_hex(commit->object.sha1), mainline);
312                 parent = p->item;
313         } else if (0 < mainline)
314                 die("Mainline was specified but commit %s is not a merge.",
315                     sha1_to_hex(commit->object.sha1));
316         else
317                 parent = commit->parents->item;
318
319         if (!(message = commit->buffer))
320                 die ("Cannot get commit message for %s",
321                                 sha1_to_hex(commit->object.sha1));
322
323         if (parent && parse_commit(parent) < 0)
324                 die("%s: cannot parse parent commit %s",
325                     me, sha1_to_hex(parent->object.sha1));
326
327         /*
328          * "commit" is an existing commit.  We would want to apply
329          * the difference it introduces since its first parent "prev"
330          * on top of the current HEAD if we are cherry-pick.  Or the
331          * reverse of it if we are revert.
332          */
333
334         msg_fd = hold_lock_file_for_update(&msg_file, defmsg,
335                                            LOCK_DIE_ON_ERROR);
336
337         encoding = get_encoding(message);
338         if (!encoding)
339                 encoding = "UTF-8";
340         if (!git_commit_encoding)
341                 git_commit_encoding = "UTF-8";
342         if ((reencoded_message = reencode_string(message,
343                                         git_commit_encoding, encoding)))
344                 message = reencoded_message;
345
346         oneline = get_oneline(message);
347
348         if (action == REVERT) {
349                 char *oneline_body = strchr(oneline, ' ');
350
351                 base = commit;
352                 next = parent;
353                 add_to_msg("Revert \"");
354                 add_to_msg(oneline_body + 1);
355                 add_to_msg("\"\n\nThis reverts commit ");
356                 add_to_msg(sha1_to_hex(commit->object.sha1));
357
358                 if (commit->parents->next) {
359                         add_to_msg(", reversing\nchanges made to ");
360                         add_to_msg(sha1_to_hex(parent->object.sha1));
361                 }
362                 add_to_msg(".\n");
363         } else {
364                 base = parent;
365                 next = commit;
366                 set_author_ident_env(message);
367                 add_message_to_msg(message);
368                 if (no_replay) {
369                         add_to_msg("(cherry picked from commit ");
370                         add_to_msg(sha1_to_hex(commit->object.sha1));
371                         add_to_msg(")\n");
372                 }
373         }
374
375         read_cache();
376         init_merge_options(&o);
377         o.branch1 = "HEAD";
378         o.branch2 = oneline;
379
380         head_tree = parse_tree_indirect(head);
381         next_tree = next ? next->tree : empty_tree();
382         base_tree = base ? base->tree : empty_tree();
383
384         clean = merge_trees(&o,
385                             head_tree,
386                             next_tree, base_tree, &result);
387
388         if (active_cache_changed &&
389             (write_cache(index_fd, active_cache, active_nr) ||
390              commit_locked_index(&index_lock)))
391                 die("%s: Unable to write new index file", me);
392         rollback_lock_file(&index_lock);
393
394         if (!clean) {
395                 add_to_msg("\nConflicts:\n\n");
396                 for (i = 0; i < active_nr;) {
397                         struct cache_entry *ce = active_cache[i++];
398                         if (ce_stage(ce)) {
399                                 add_to_msg("\t");
400                                 add_to_msg(ce->name);
401                                 add_to_msg("\n");
402                                 while (i < active_nr && !strcmp(ce->name,
403                                                 active_cache[i]->name))
404                                         i++;
405                         }
406                 }
407                 if (commit_lock_file(&msg_file) < 0)
408                         die ("Error wrapping up %s", defmsg);
409                 fprintf(stderr, "Automatic %s failed.%s\n",
410                         me, help_msg(commit->object.sha1));
411                 rerere();
412                 exit(1);
413         }
414         if (commit_lock_file(&msg_file) < 0)
415                 die ("Error wrapping up %s", defmsg);
416         fprintf(stderr, "Finished one %s.\n", me);
417
418         /*
419          *
420          * If we are cherry-pick, and if the merge did not result in
421          * hand-editing, we will hit this commit and inherit the original
422          * author date and name.
423          * If we are revert, or if our cherry-pick results in a hand merge,
424          * we had better say that the current user is responsible for that.
425          */
426
427         if (!no_commit) {
428                 /* 6 is max possible length of our args array including NULL */
429                 const char *args[6];
430                 int i = 0;
431                 args[i++] = "commit";
432                 args[i++] = "-n";
433                 if (signoff)
434                         args[i++] = "-s";
435                 if (!edit) {
436                         args[i++] = "-F";
437                         args[i++] = defmsg;
438                 }
439                 args[i] = NULL;
440                 return execv_git_cmd(args);
441         }
442         free(reencoded_message);
443         free(defmsg);
444
445         return 0;
446 }
447
448 int cmd_revert(int argc, const char **argv, const char *prefix)
449 {
450         if (isatty(0))
451                 edit = 1;
452         no_replay = 1;
453         action = REVERT;
454         return revert_or_cherry_pick(argc, argv);
455 }
456
457 int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
458 {
459         no_replay = 0;
460         action = CHERRY_PICK;
461         return revert_or_cherry_pick(argc, argv);
462 }