Merge branch 'jk/terse-push' into aw/mirror-push
[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
12 /*
13  * This implements the builtins revert and cherry-pick.
14  *
15  * Copyright (c) 2007 Johannes E. Schindelin
16  *
17  * Based on git-revert.sh, which is
18  *
19  * Copyright (c) 2005 Linus Torvalds
20  * Copyright (c) 2005 Junio C Hamano
21  */
22
23 static const char * const revert_usage[] = {
24         "git-revert [options] <commit-ish>",
25         NULL
26 };
27
28 static const char * const cherry_pick_usage[] = {
29         "git-cherry-pick [options] <commit-ish>",
30         NULL
31 };
32
33 static int edit, no_replay, no_commit, needed_deref;
34 static enum { REVERT, CHERRY_PICK } action;
35 static struct commit *commit;
36
37 static const char *me;
38
39 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
40
41 static void parse_args(int argc, const char **argv)
42 {
43         const char * const * usage_str =
44                 action == REVERT ?  revert_usage : cherry_pick_usage;
45         unsigned char sha1[20];
46         const char *arg;
47         int noop;
48         struct option options[] = {
49                 OPT_BOOLEAN('n', "no-commit", &no_commit, "don't automatically commit"),
50                 OPT_BOOLEAN('e', "edit", &edit, "edit the commit message"),
51                 OPT_BOOLEAN('x', NULL, &no_replay, "append commit name when cherry-picking"),
52                 OPT_BOOLEAN('r', NULL, &noop, "no-op (backward compatibility)"),
53                 OPT_END(),
54         };
55
56         if (parse_options(argc, argv, options, usage_str, 0) != 1)
57                 usage_with_options(usage_str, options);
58         arg = argv[0];
59         if (get_sha1(arg, sha1))
60                 die ("Cannot find '%s'", arg);
61         commit = (struct commit *)parse_object(sha1);
62         if (!commit)
63                 die ("Could not find %s", sha1_to_hex(sha1));
64         if (commit->object.type == OBJ_TAG) {
65                 commit = (struct commit *)
66                         deref_tag((struct object *)commit, arg, strlen(arg));
67                 needed_deref = 1;
68         }
69         if (commit->object.type != OBJ_COMMIT)
70                 die ("'%s' does not point to a commit", arg);
71 }
72
73 static char *get_oneline(const char *message)
74 {
75         char *result;
76         const char *p = message, *abbrev, *eol;
77         int abbrev_len, oneline_len;
78
79         if (!p)
80                 die ("Could not read commit message of %s",
81                                 sha1_to_hex(commit->object.sha1));
82         while (*p && (*p != '\n' || p[1] != '\n'))
83                 p++;
84
85         if (*p) {
86                 p += 2;
87                 for (eol = p + 1; *eol && *eol != '\n'; eol++)
88                         ; /* do nothing */
89         } else
90                 eol = p;
91         abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
92         abbrev_len = strlen(abbrev);
93         oneline_len = eol - p;
94         result = xmalloc(abbrev_len + 5 + oneline_len);
95         memcpy(result, abbrev, abbrev_len);
96         memcpy(result + abbrev_len, "... ", 4);
97         memcpy(result + abbrev_len + 4, p, oneline_len);
98         result[abbrev_len + 4 + oneline_len] = '\0';
99         return result;
100 }
101
102 static char *get_encoding(const char *message)
103 {
104         const char *p = message, *eol;
105
106         if (!p)
107                 die ("Could not read commit message of %s",
108                                 sha1_to_hex(commit->object.sha1));
109         while (*p && *p != '\n') {
110                 for (eol = p + 1; *eol && *eol != '\n'; eol++)
111                         ; /* do nothing */
112                 if (!prefixcmp(p, "encoding ")) {
113                         char *result = xmalloc(eol - 8 - p);
114                         strlcpy(result, p + 9, eol - 8 - p);
115                         return result;
116                 }
117                 p = eol;
118                 if (*p == '\n')
119                         p++;
120         }
121         return NULL;
122 }
123
124 static struct lock_file msg_file;
125 static int msg_fd;
126
127 static void add_to_msg(const char *string)
128 {
129         int len = strlen(string);
130         if (write_in_full(msg_fd, string, len) < 0)
131                 die ("Could not write to MERGE_MSG");
132 }
133
134 static void add_message_to_msg(const char *message)
135 {
136         const char *p = message;
137         while (*p && (*p != '\n' || p[1] != '\n'))
138                 p++;
139
140         if (!*p)
141                 add_to_msg(sha1_to_hex(commit->object.sha1));
142
143         p += 2;
144         add_to_msg(p);
145         return;
146 }
147
148 static void set_author_ident_env(const char *message)
149 {
150         const char *p = message;
151         if (!p)
152                 die ("Could not read commit message of %s",
153                                 sha1_to_hex(commit->object.sha1));
154         while (*p && *p != '\n') {
155                 const char *eol;
156
157                 for (eol = p; *eol && *eol != '\n'; eol++)
158                         ; /* do nothing */
159                 if (!prefixcmp(p, "author ")) {
160                         char *line, *pend, *email, *timestamp;
161
162                         p += 7;
163                         line = xmemdupz(p, eol - p);
164                         email = strchr(line, '<');
165                         if (!email)
166                                 die ("Could not extract author email from %s",
167                                         sha1_to_hex(commit->object.sha1));
168                         if (email == line)
169                                 pend = line;
170                         else
171                                 for (pend = email; pend != line + 1 &&
172                                                 isspace(pend[-1]); pend--);
173                                         ; /* do nothing */
174                         *pend = '\0';
175                         email++;
176                         timestamp = strchr(email, '>');
177                         if (!timestamp)
178                                 die ("Could not extract author email from %s",
179                                         sha1_to_hex(commit->object.sha1));
180                         *timestamp = '\0';
181                         for (timestamp++; *timestamp && isspace(*timestamp);
182                                         timestamp++)
183                                 ; /* do nothing */
184                         setenv("GIT_AUTHOR_NAME", line, 1);
185                         setenv("GIT_AUTHOR_EMAIL", email, 1);
186                         setenv("GIT_AUTHOR_DATE", timestamp, 1);
187                         free(line);
188                         return;
189                 }
190                 p = eol;
191                 if (*p == '\n')
192                         p++;
193         }
194         die ("No author information found in %s",
195                         sha1_to_hex(commit->object.sha1));
196 }
197
198 static int merge_recursive(const char *base_sha1,
199                 const char *head_sha1, const char *head_name,
200                 const char *next_sha1, const char *next_name)
201 {
202         char buffer[256];
203         const char *argv[6];
204
205         sprintf(buffer, "GITHEAD_%s", head_sha1);
206         setenv(buffer, head_name, 1);
207         sprintf(buffer, "GITHEAD_%s", next_sha1);
208         setenv(buffer, next_name, 1);
209
210         /*
211          * This three way merge is an interesting one.  We are at
212          * $head, and would want to apply the change between $commit
213          * and $prev on top of us (when reverting), or the change between
214          * $prev and $commit on top of us (when cherry-picking or replaying).
215          */
216         argv[0] = "merge-recursive";
217         argv[1] = base_sha1;
218         argv[2] = "--";
219         argv[3] = head_sha1;
220         argv[4] = next_sha1;
221         argv[5] = NULL;
222
223         return run_command_v_opt(argv, RUN_COMMAND_NO_STDIN | RUN_GIT_CMD);
224 }
225
226 static int revert_or_cherry_pick(int argc, const char **argv)
227 {
228         unsigned char head[20];
229         struct commit *base, *next;
230         int i;
231         char *oneline, *reencoded_message = NULL;
232         const char *message, *encoding;
233         const char *defmsg = xstrdup(git_path("MERGE_MSG"));
234
235         git_config(git_default_config);
236         me = action == REVERT ? "revert" : "cherry-pick";
237         setenv(GIT_REFLOG_ACTION, me, 0);
238         parse_args(argc, argv);
239
240         /* this is copied from the shell script, but it's never triggered... */
241         if (action == REVERT && !no_replay)
242                 die("revert is incompatible with replay");
243
244         if (no_commit) {
245                 /*
246                  * We do not intend to commit immediately.  We just want to
247                  * merge the differences in.
248                  */
249                 if (write_tree(head, 0, NULL))
250                         die ("Your index file is unmerged.");
251         } else {
252                 struct wt_status s;
253
254                 if (get_sha1("HEAD", head))
255                         die ("You do not have a valid HEAD");
256                 wt_status_prepare(&s);
257                 if (s.commitable || s.workdir_dirty)
258                         die ("Dirty index: cannot %s", me);
259                 discard_cache();
260         }
261
262         if (!commit->parents)
263                 die ("Cannot %s a root commit", me);
264         if (commit->parents->next)
265                 die ("Cannot %s a multi-parent commit.", me);
266         if (!(message = commit->buffer))
267                 die ("Cannot get commit message for %s",
268                                 sha1_to_hex(commit->object.sha1));
269
270         /*
271          * "commit" is an existing commit.  We would want to apply
272          * the difference it introduces since its first parent "prev"
273          * on top of the current HEAD if we are cherry-pick.  Or the
274          * reverse of it if we are revert.
275          */
276
277         msg_fd = hold_lock_file_for_update(&msg_file, defmsg, 1);
278
279         encoding = get_encoding(message);
280         if (!encoding)
281                 encoding = "utf-8";
282         if (!git_commit_encoding)
283                 git_commit_encoding = "utf-8";
284         if ((reencoded_message = reencode_string(message,
285                                         git_commit_encoding, encoding)))
286                 message = reencoded_message;
287
288         oneline = get_oneline(message);
289
290         if (action == REVERT) {
291                 char *oneline_body = strchr(oneline, ' ');
292
293                 base = commit;
294                 next = commit->parents->item;
295                 add_to_msg("Revert \"");
296                 add_to_msg(oneline_body + 1);
297                 add_to_msg("\"\n\nThis reverts commit ");
298                 add_to_msg(sha1_to_hex(commit->object.sha1));
299                 add_to_msg(".\n");
300         } else {
301                 base = commit->parents->item;
302                 next = commit;
303                 set_author_ident_env(message);
304                 add_message_to_msg(message);
305                 if (no_replay) {
306                         add_to_msg("(cherry picked from commit ");
307                         add_to_msg(sha1_to_hex(commit->object.sha1));
308                         add_to_msg(")\n");
309                 }
310         }
311         if (needed_deref) {
312                 add_to_msg("(original 'git ");
313                 add_to_msg(me);
314                 add_to_msg("' arguments: ");
315                 for (i = 0; i < argc; i++) {
316                         if (i)
317                                 add_to_msg(" ");
318                         add_to_msg(argv[i]);
319                 }
320                 add_to_msg(")\n");
321         }
322
323         if (merge_recursive(sha1_to_hex(base->object.sha1),
324                                 sha1_to_hex(head), "HEAD",
325                                 sha1_to_hex(next->object.sha1), oneline) ||
326                         write_tree(head, 0, NULL)) {
327                 add_to_msg("\nConflicts:\n\n");
328                 read_cache();
329                 for (i = 0; i < active_nr;) {
330                         struct cache_entry *ce = active_cache[i++];
331                         if (ce_stage(ce)) {
332                                 add_to_msg("\t");
333                                 add_to_msg(ce->name);
334                                 add_to_msg("\n");
335                                 while (i < active_nr && !strcmp(ce->name,
336                                                 active_cache[i]->name))
337                                         i++;
338                         }
339                 }
340                 if (close(msg_fd) || commit_lock_file(&msg_file) < 0)
341                         die ("Error wrapping up %s", defmsg);
342                 fprintf(stderr, "Automatic %s failed.  "
343                         "After resolving the conflicts,\n"
344                         "mark the corrected paths with 'git add <paths>' "
345                         "and commit the result.\n", me);
346                 if (action == CHERRY_PICK) {
347                         fprintf(stderr, "When commiting, use the option "
348                                 "'-c %s' to retain authorship and message.\n",
349                                 find_unique_abbrev(commit->object.sha1,
350                                         DEFAULT_ABBREV));
351                 }
352                 exit(1);
353         }
354         if (close(msg_fd) || commit_lock_file(&msg_file) < 0)
355                 die ("Error wrapping up %s", defmsg);
356         fprintf(stderr, "Finished one %s.\n", me);
357
358         /*
359          *
360          * If we are cherry-pick, and if the merge did not result in
361          * hand-editing, we will hit this commit and inherit the original
362          * author date and name.
363          * If we are revert, or if our cherry-pick results in a hand merge,
364          * we had better say that the current user is responsible for that.
365          */
366
367         if (!no_commit) {
368                 if (edit)
369                         return execl_git_cmd("commit", "-n", NULL);
370                 else
371                         return execl_git_cmd("commit", "-n", "-F", defmsg, NULL);
372         }
373         if (reencoded_message)
374                 free(reencoded_message);
375
376         return 0;
377 }
378
379 int cmd_revert(int argc, const char **argv, const char *prefix)
380 {
381         if (isatty(0))
382                 edit = 1;
383         no_replay = 1;
384         action = REVERT;
385         return revert_or_cherry_pick(argc, argv);
386 }
387
388 int cmd_cherry_pick(int argc, const char **argv, const char *prefix)
389 {
390         no_replay = 0;
391         action = CHERRY_PICK;
392         return revert_or_cherry_pick(argc, argv);
393 }