Merge branch 'maint'
[git] / builtin-log.c
1 /*
2  * Builtin "git log" and related commands (show, whatchanged)
3  *
4  * (C) Copyright 2006 Linus Torvalds
5  *               2006 Junio Hamano
6  */
7 #include "cache.h"
8 #include "commit.h"
9 #include "diff.h"
10 #include "revision.h"
11 #include "log-tree.h"
12 #include "builtin.h"
13 #include "tag.h"
14 #include "reflog-walk.h"
15 #include "patch-ids.h"
16 #include "refs.h"
17
18 static int default_show_root = 1;
19 static const char *fmt_patch_subject_prefix = "PATCH";
20
21 static void add_name_decoration(const char *prefix, const char *name, struct object *obj)
22 {
23         int plen = strlen(prefix);
24         int nlen = strlen(name);
25         struct name_decoration *res = xmalloc(sizeof(struct name_decoration) + plen + nlen);
26         memcpy(res->name, prefix, plen);
27         memcpy(res->name + plen, name, nlen + 1);
28         res->next = add_decoration(&name_decoration, obj, res);
29 }
30
31 static int add_ref_decoration(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
32 {
33         struct object *obj = parse_object(sha1);
34         if (!obj)
35                 return 0;
36         add_name_decoration("", refname, obj);
37         while (obj->type == OBJ_TAG) {
38                 obj = ((struct tag *)obj)->tagged;
39                 if (!obj)
40                         break;
41                 add_name_decoration("tag: ", refname, obj);
42         }
43         return 0;
44 }
45
46 static void cmd_log_init(int argc, const char **argv, const char *prefix,
47                       struct rev_info *rev)
48 {
49         int i;
50         int decorate = 0;
51
52         rev->abbrev = DEFAULT_ABBREV;
53         rev->commit_format = CMIT_FMT_DEFAULT;
54         rev->verbose_header = 1;
55         DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
56         rev->show_root_diff = default_show_root;
57         rev->subject_prefix = fmt_patch_subject_prefix;
58         argc = setup_revisions(argc, argv, rev, "HEAD");
59         if (rev->diffopt.pickaxe || rev->diffopt.filter)
60                 rev->always_show_header = 0;
61         if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
62                 rev->always_show_header = 0;
63                 if (rev->diffopt.nr_paths != 1)
64                         usage("git logs can only follow renames on one pathname at a time");
65         }
66         for (i = 1; i < argc; i++) {
67                 const char *arg = argv[i];
68                 if (!strcmp(arg, "--decorate")) {
69                         if (!decorate)
70                                 for_each_ref(add_ref_decoration, NULL);
71                         decorate = 1;
72                 } else
73                         die("unrecognized argument: %s", arg);
74         }
75 }
76
77 /*
78  * This gives a rough estimate for how many commits we
79  * will print out in the list.
80  */
81 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
82 {
83         int n = 0;
84
85         while (list) {
86                 struct commit *commit = list->item;
87                 unsigned int flags = commit->object.flags;
88                 list = list->next;
89                 if (!(flags & (TREESAME | UNINTERESTING)))
90                         n++;
91         }
92         return n;
93 }
94
95 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
96 {
97         if (rev->shown_one) {
98                 rev->shown_one = 0;
99                 if (rev->commit_format != CMIT_FMT_ONELINE)
100                         putchar(rev->diffopt.line_termination);
101         }
102         printf("Final output: %d %s\n", nr, stage);
103 }
104
105 struct itimerval early_output_timer;
106
107 static void log_show_early(struct rev_info *revs, struct commit_list *list)
108 {
109         int i = revs->early_output;
110         int show_header = 1;
111
112         sort_in_topological_order(&list, revs->lifo);
113         while (list && i) {
114                 struct commit *commit = list->item;
115                 switch (simplify_commit(revs, commit)) {
116                 case commit_show:
117                         if (show_header) {
118                                 int n = estimate_commit_count(revs, list);
119                                 show_early_header(revs, "incomplete", n);
120                                 show_header = 0;
121                         }
122                         log_tree_commit(revs, commit);
123                         i--;
124                         break;
125                 case commit_ignore:
126                         break;
127                 case commit_error:
128                         return;
129                 }
130                 list = list->next;
131         }
132
133         /* Did we already get enough commits for the early output? */
134         if (!i)
135                 return;
136
137         /*
138          * ..if no, then repeat it twice a second until we
139          * do.
140          *
141          * NOTE! We don't use "it_interval", because if the
142          * reader isn't listening, we want our output to be
143          * throttled by the writing, and not have the timer
144          * trigger every second even if we're blocked on a
145          * reader!
146          */
147         early_output_timer.it_value.tv_sec = 0;
148         early_output_timer.it_value.tv_usec = 500000;
149         setitimer(ITIMER_REAL, &early_output_timer, NULL);
150 }
151
152 static void early_output(int signal)
153 {
154         show_early_output = log_show_early;
155 }
156
157 static void setup_early_output(struct rev_info *rev)
158 {
159         struct sigaction sa;
160
161         /*
162          * Set up the signal handler, minimally intrusively:
163          * we only set a single volatile integer word (not
164          * using sigatomic_t - trying to avoid unnecessary
165          * system dependencies and headers), and using
166          * SA_RESTART.
167          */
168         memset(&sa, 0, sizeof(sa));
169         sa.sa_handler = early_output;
170         sigemptyset(&sa.sa_mask);
171         sa.sa_flags = SA_RESTART;
172         sigaction(SIGALRM, &sa, NULL);
173
174         /*
175          * If we can get the whole output in less than a
176          * tenth of a second, don't even bother doing the
177          * early-output thing..
178          *
179          * This is a one-time-only trigger.
180          */
181         early_output_timer.it_value.tv_sec = 0;
182         early_output_timer.it_value.tv_usec = 100000;
183         setitimer(ITIMER_REAL, &early_output_timer, NULL);
184 }
185
186 static void finish_early_output(struct rev_info *rev)
187 {
188         int n = estimate_commit_count(rev, rev->commits);
189         signal(SIGALRM, SIG_IGN);
190         show_early_header(rev, "done", n);
191 }
192
193 static int cmd_log_walk(struct rev_info *rev)
194 {
195         struct commit *commit;
196
197         if (rev->early_output)
198                 setup_early_output(rev);
199
200         prepare_revision_walk(rev);
201
202         if (rev->early_output)
203                 finish_early_output(rev);
204
205         while ((commit = get_revision(rev)) != NULL) {
206                 log_tree_commit(rev, commit);
207                 if (!rev->reflog_info) {
208                         /* we allow cycles in reflog ancestry */
209                         free(commit->buffer);
210                         commit->buffer = NULL;
211                 }
212                 free_commit_list(commit->parents);
213                 commit->parents = NULL;
214         }
215         return 0;
216 }
217
218 static int git_log_config(const char *var, const char *value)
219 {
220         if (!strcmp(var, "format.subjectprefix")) {
221                 if (!value)
222                         die("format.subjectprefix without value");
223                 fmt_patch_subject_prefix = xstrdup(value);
224                 return 0;
225         }
226         if (!strcmp(var, "log.showroot")) {
227                 default_show_root = git_config_bool(var, value);
228                 return 0;
229         }
230         return git_diff_ui_config(var, value);
231 }
232
233 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
234 {
235         struct rev_info rev;
236
237         git_config(git_log_config);
238         init_revisions(&rev, prefix);
239         rev.diff = 1;
240         rev.simplify_history = 0;
241         cmd_log_init(argc, argv, prefix, &rev);
242         if (!rev.diffopt.output_format)
243                 rev.diffopt.output_format = DIFF_FORMAT_RAW;
244         return cmd_log_walk(&rev);
245 }
246
247 static int show_object(const unsigned char *sha1, int suppress_header)
248 {
249         unsigned long size;
250         enum object_type type;
251         char *buf = read_sha1_file(sha1, &type, &size);
252         int offset = 0;
253
254         if (!buf)
255                 return error("Could not read object %s", sha1_to_hex(sha1));
256
257         if (suppress_header)
258                 while (offset < size && buf[offset++] != '\n') {
259                         int new_offset = offset;
260                         while (new_offset < size && buf[new_offset++] != '\n')
261                                 ; /* do nothing */
262                         offset = new_offset;
263                 }
264
265         if (offset < size)
266                 fwrite(buf + offset, size - offset, 1, stdout);
267         free(buf);
268         return 0;
269 }
270
271 static int show_tree_object(const unsigned char *sha1,
272                 const char *base, int baselen,
273                 const char *pathname, unsigned mode, int stage)
274 {
275         printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
276         return 0;
277 }
278
279 int cmd_show(int argc, const char **argv, const char *prefix)
280 {
281         struct rev_info rev;
282         struct object_array_entry *objects;
283         int i, count, ret = 0;
284
285         git_config(git_log_config);
286         init_revisions(&rev, prefix);
287         rev.diff = 1;
288         rev.combine_merges = 1;
289         rev.dense_combined_merges = 1;
290         rev.always_show_header = 1;
291         rev.ignore_merges = 0;
292         rev.no_walk = 1;
293         cmd_log_init(argc, argv, prefix, &rev);
294
295         count = rev.pending.nr;
296         objects = rev.pending.objects;
297         for (i = 0; i < count && !ret; i++) {
298                 struct object *o = objects[i].item;
299                 const char *name = objects[i].name;
300                 switch (o->type) {
301                 case OBJ_BLOB:
302                         ret = show_object(o->sha1, 0);
303                         break;
304                 case OBJ_TAG: {
305                         struct tag *t = (struct tag *)o;
306
307                         printf("%stag %s%s\n\n",
308                                         diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
309                                         t->tag,
310                                         diff_get_color_opt(&rev.diffopt, DIFF_RESET));
311                         ret = show_object(o->sha1, 1);
312                         objects[i].item = (struct object *)t->tagged;
313                         i--;
314                         break;
315                 }
316                 case OBJ_TREE:
317                         printf("%stree %s%s\n\n",
318                                         diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
319                                         name,
320                                         diff_get_color_opt(&rev.diffopt, DIFF_RESET));
321                         read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
322                                         show_tree_object);
323                         break;
324                 case OBJ_COMMIT:
325                         rev.pending.nr = rev.pending.alloc = 0;
326                         rev.pending.objects = NULL;
327                         add_object_array(o, name, &rev.pending);
328                         ret = cmd_log_walk(&rev);
329                         break;
330                 default:
331                         ret = error("Unknown type: %d", o->type);
332                 }
333         }
334         free(objects);
335         return ret;
336 }
337
338 /*
339  * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
340  */
341 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
342 {
343         struct rev_info rev;
344
345         git_config(git_log_config);
346         init_revisions(&rev, prefix);
347         init_reflog_walk(&rev.reflog_info);
348         rev.abbrev_commit = 1;
349         rev.verbose_header = 1;
350         cmd_log_init(argc, argv, prefix, &rev);
351
352         /*
353          * This means that we override whatever commit format the user gave
354          * on the cmd line.  Sad, but cmd_log_init() currently doesn't
355          * allow us to set a different default.
356          */
357         rev.commit_format = CMIT_FMT_ONELINE;
358         rev.always_show_header = 1;
359
360         /*
361          * We get called through "git reflog", so unlike the other log
362          * routines, we need to set up our pager manually..
363          */
364         setup_pager();
365
366         return cmd_log_walk(&rev);
367 }
368
369 int cmd_log(int argc, const char **argv, const char *prefix)
370 {
371         struct rev_info rev;
372
373         git_config(git_log_config);
374         init_revisions(&rev, prefix);
375         rev.always_show_header = 1;
376         cmd_log_init(argc, argv, prefix, &rev);
377         return cmd_log_walk(&rev);
378 }
379
380 /* format-patch */
381 #define FORMAT_PATCH_NAME_MAX 64
382
383 static int istitlechar(char c)
384 {
385         return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
386                 (c >= '0' && c <= '9') || c == '.' || c == '_';
387 }
388
389 static char *extra_headers = NULL;
390 static int extra_headers_size = 0;
391 static const char *fmt_patch_suffix = ".patch";
392 static int numbered = 0;
393 static int auto_number = 0;
394
395 static int git_format_config(const char *var, const char *value)
396 {
397         if (!strcmp(var, "format.headers")) {
398                 int len;
399
400                 if (!value)
401                         die("format.headers without value");
402                 len = strlen(value);
403                 extra_headers_size += len + 1;
404                 extra_headers = xrealloc(extra_headers, extra_headers_size);
405                 extra_headers[extra_headers_size - len - 1] = 0;
406                 strcat(extra_headers, value);
407                 return 0;
408         }
409         if (!strcmp(var, "format.suffix")) {
410                 if (!value)
411                         die("format.suffix without value");
412                 fmt_patch_suffix = xstrdup(value);
413                 return 0;
414         }
415         if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
416                 return 0;
417         }
418         if (!strcmp(var, "format.numbered")) {
419                 if (!strcasecmp(value, "auto")) {
420                         auto_number = 1;
421                         return 0;
422                 }
423
424                 numbered = git_config_bool(var, value);
425                 return 0;
426         }
427
428         return git_log_config(var, value);
429 }
430
431
432 static FILE *realstdout = NULL;
433 static const char *output_directory = NULL;
434
435 static int reopen_stdout(struct commit *commit, int nr, int keep_subject,
436                          int numbered_files)
437 {
438         char filename[PATH_MAX];
439         char *sol;
440         int len = 0;
441         int suffix_len = strlen(fmt_patch_suffix) + 1;
442
443         if (output_directory) {
444                 if (strlen(output_directory) >=
445                     sizeof(filename) - FORMAT_PATCH_NAME_MAX - suffix_len)
446                         return error("name of output directory is too long");
447                 strlcpy(filename, output_directory, sizeof(filename) - suffix_len);
448                 len = strlen(filename);
449                 if (filename[len - 1] != '/')
450                         filename[len++] = '/';
451         }
452
453         if (numbered_files) {
454                 sprintf(filename + len, "%d", nr);
455                 len = strlen(filename);
456
457         } else {
458                 sprintf(filename + len, "%04d", nr);
459                 len = strlen(filename);
460
461                 sol = strstr(commit->buffer, "\n\n");
462                 if (sol) {
463                         int j, space = 1;
464
465                         sol += 2;
466                         /* strip [PATCH] or [PATCH blabla] */
467                         if (!keep_subject && !prefixcmp(sol, "[PATCH")) {
468                                 char *eos = strchr(sol + 6, ']');
469                                 if (eos) {
470                                         while (isspace(*eos))
471                                                 eos++;
472                                         sol = eos;
473                                 }
474                         }
475
476                         for (j = 0;
477                              j < FORMAT_PATCH_NAME_MAX - suffix_len - 5 &&
478                                      len < sizeof(filename) - suffix_len &&
479                                      sol[j] && sol[j] != '\n';
480                              j++) {
481                                 if (istitlechar(sol[j])) {
482                                         if (space) {
483                                                 filename[len++] = '-';
484                                                 space = 0;
485                                         }
486                                         filename[len++] = sol[j];
487                                         if (sol[j] == '.')
488                                                 while (sol[j + 1] == '.')
489                                                         j++;
490                                 } else
491                                         space = 1;
492                         }
493                         while (filename[len - 1] == '.'
494                                || filename[len - 1] == '-')
495                                 len--;
496                         filename[len] = 0;
497                 }
498                 if (len + suffix_len >= sizeof(filename))
499                         return error("Patch pathname too long");
500                 strcpy(filename + len, fmt_patch_suffix);
501         }
502
503         fprintf(realstdout, "%s\n", filename);
504         if (freopen(filename, "w", stdout) == NULL)
505                 return error("Cannot open patch file %s",filename);
506
507         return 0;
508 }
509
510 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
511 {
512         struct rev_info check_rev;
513         struct commit *commit;
514         struct object *o1, *o2;
515         unsigned flags1, flags2;
516
517         if (rev->pending.nr != 2)
518                 die("Need exactly one range.");
519
520         o1 = rev->pending.objects[0].item;
521         flags1 = o1->flags;
522         o2 = rev->pending.objects[1].item;
523         flags2 = o2->flags;
524
525         if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
526                 die("Not a range.");
527
528         init_patch_ids(ids);
529
530         /* given a range a..b get all patch ids for b..a */
531         init_revisions(&check_rev, prefix);
532         o1->flags ^= UNINTERESTING;
533         o2->flags ^= UNINTERESTING;
534         add_pending_object(&check_rev, o1, "o1");
535         add_pending_object(&check_rev, o2, "o2");
536         prepare_revision_walk(&check_rev);
537
538         while ((commit = get_revision(&check_rev)) != NULL) {
539                 /* ignore merges */
540                 if (commit->parents && commit->parents->next)
541                         continue;
542
543                 add_commit_patch_id(commit, ids);
544         }
545
546         /* reset for next revision walk */
547         clear_commit_marks((struct commit *)o1,
548                         SEEN | UNINTERESTING | SHOWN | ADDED);
549         clear_commit_marks((struct commit *)o2,
550                         SEEN | UNINTERESTING | SHOWN | ADDED);
551         o1->flags = flags1;
552         o2->flags = flags2;
553 }
554
555 static void gen_message_id(char *dest, unsigned int length, char *base)
556 {
557         const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
558         const char *email_start = strrchr(committer, '<');
559         const char *email_end = strrchr(committer, '>');
560         if(!email_start || !email_end || email_start > email_end - 1)
561                 die("Could not extract email from committer identity.");
562         snprintf(dest, length, "%s.%lu.git.%.*s", base,
563                  (unsigned long) time(NULL),
564                  (int)(email_end - email_start - 1), email_start + 1);
565 }
566
567 static const char *clean_message_id(const char *msg_id)
568 {
569         char ch;
570         const char *a, *z, *m;
571
572         m = msg_id;
573         while ((ch = *m) && (isspace(ch) || (ch == '<')))
574                 m++;
575         a = m;
576         z = NULL;
577         while ((ch = *m)) {
578                 if (!isspace(ch) && (ch != '>'))
579                         z = m;
580                 m++;
581         }
582         if (!z)
583                 die("insane in-reply-to: %s", msg_id);
584         if (++z == m)
585                 return a;
586         return xmemdupz(a, z - a);
587 }
588
589 int cmd_format_patch(int argc, const char **argv, const char *prefix)
590 {
591         struct commit *commit;
592         struct commit **list = NULL;
593         struct rev_info rev;
594         int nr = 0, total, i, j;
595         int use_stdout = 0;
596         int start_number = -1;
597         int keep_subject = 0;
598         int numbered_files = 0;         /* _just_ numbers */
599         int subject_prefix = 0;
600         int ignore_if_in_upstream = 0;
601         int thread = 0;
602         const char *in_reply_to = NULL;
603         struct patch_ids ids;
604         char *add_signoff = NULL;
605         char message_id[1024];
606         char ref_message_id[1024];
607
608         git_config(git_format_config);
609         init_revisions(&rev, prefix);
610         rev.commit_format = CMIT_FMT_EMAIL;
611         rev.verbose_header = 1;
612         rev.diff = 1;
613         rev.combine_merges = 0;
614         rev.ignore_merges = 1;
615         rev.diffopt.msg_sep = "";
616         DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
617
618         rev.subject_prefix = fmt_patch_subject_prefix;
619         rev.extra_headers = extra_headers;
620
621         /*
622          * Parse the arguments before setup_revisions(), or something
623          * like "git format-patch -o a123 HEAD^.." may fail; a123 is
624          * possibly a valid SHA1.
625          */
626         for (i = 1, j = 1; i < argc; i++) {
627                 if (!strcmp(argv[i], "--stdout"))
628                         use_stdout = 1;
629                 else if (!strcmp(argv[i], "-n") ||
630                                 !strcmp(argv[i], "--numbered"))
631                         numbered = 1;
632                 else if (!strcmp(argv[i], "-N") ||
633                                 !strcmp(argv[i], "--no-numbered")) {
634                         numbered = 0;
635                         auto_number = 0;
636                 }
637                 else if (!prefixcmp(argv[i], "--start-number="))
638                         start_number = strtol(argv[i] + 15, NULL, 10);
639                 else if (!strcmp(argv[i], "--numbered-files"))
640                         numbered_files = 1;
641                 else if (!strcmp(argv[i], "--start-number")) {
642                         i++;
643                         if (i == argc)
644                                 die("Need a number for --start-number");
645                         start_number = strtol(argv[i], NULL, 10);
646                 }
647                 else if (!strcmp(argv[i], "-k") ||
648                                 !strcmp(argv[i], "--keep-subject")) {
649                         keep_subject = 1;
650                         rev.total = -1;
651                 }
652                 else if (!strcmp(argv[i], "--output-directory") ||
653                          !strcmp(argv[i], "-o")) {
654                         i++;
655                         if (argc <= i)
656                                 die("Which directory?");
657                         if (output_directory)
658                                 die("Two output directories?");
659                         output_directory = argv[i];
660                 }
661                 else if (!strcmp(argv[i], "--signoff") ||
662                          !strcmp(argv[i], "-s")) {
663                         const char *committer;
664                         const char *endpos;
665                         committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
666                         endpos = strchr(committer, '>');
667                         if (!endpos)
668                                 die("bogos committer info %s\n", committer);
669                         add_signoff = xmemdupz(committer, endpos - committer + 1);
670                 }
671                 else if (!strcmp(argv[i], "--attach")) {
672                         rev.mime_boundary = git_version_string;
673                         rev.no_inline = 1;
674                 }
675                 else if (!prefixcmp(argv[i], "--attach=")) {
676                         rev.mime_boundary = argv[i] + 9;
677                         rev.no_inline = 1;
678                 }
679                 else if (!strcmp(argv[i], "--inline")) {
680                         rev.mime_boundary = git_version_string;
681                         rev.no_inline = 0;
682                 }
683                 else if (!prefixcmp(argv[i], "--inline=")) {
684                         rev.mime_boundary = argv[i] + 9;
685                         rev.no_inline = 0;
686                 }
687                 else if (!strcmp(argv[i], "--ignore-if-in-upstream"))
688                         ignore_if_in_upstream = 1;
689                 else if (!strcmp(argv[i], "--thread"))
690                         thread = 1;
691                 else if (!prefixcmp(argv[i], "--in-reply-to="))
692                         in_reply_to = argv[i] + 14;
693                 else if (!strcmp(argv[i], "--in-reply-to")) {
694                         i++;
695                         if (i == argc)
696                                 die("Need a Message-Id for --in-reply-to");
697                         in_reply_to = argv[i];
698                 } else if (!prefixcmp(argv[i], "--subject-prefix=")) {
699                         subject_prefix = 1;
700                         rev.subject_prefix = argv[i] + 17;
701                 } else if (!prefixcmp(argv[i], "--suffix="))
702                         fmt_patch_suffix = argv[i] + 9;
703                 else
704                         argv[j++] = argv[i];
705         }
706         argc = j;
707
708         if (start_number < 0)
709                 start_number = 1;
710         if (numbered && keep_subject)
711                 die ("-n and -k are mutually exclusive.");
712         if (keep_subject && subject_prefix)
713                 die ("--subject-prefix and -k are mutually exclusive.");
714         if (numbered_files && use_stdout)
715                 die ("--numbered-files and --stdout are mutually exclusive.");
716
717         argc = setup_revisions(argc, argv, &rev, "HEAD");
718         if (argc > 1)
719                 die ("unrecognized argument: %s", argv[1]);
720
721         if (!rev.diffopt.output_format)
722                 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH;
723
724         if (!DIFF_OPT_TST(&rev.diffopt, TEXT))
725                 DIFF_OPT_SET(&rev.diffopt, BINARY);
726
727         if (!output_directory && !use_stdout)
728                 output_directory = prefix;
729
730         if (output_directory) {
731                 if (use_stdout)
732                         die("standard output, or directory, which one?");
733                 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
734                         die("Could not create directory %s",
735                             output_directory);
736         }
737
738         if (rev.pending.nr == 1) {
739                 if (rev.max_count < 0 && !rev.show_root_diff) {
740                         /*
741                          * This is traditional behaviour of "git format-patch
742                          * origin" that prepares what the origin side still
743                          * does not have.
744                          */
745                         rev.pending.objects[0].item->flags |= UNINTERESTING;
746                         add_head_to_pending(&rev);
747                 }
748                 /*
749                  * Otherwise, it is "format-patch -22 HEAD", and/or
750                  * "format-patch --root HEAD".  The user wants
751                  * get_revision() to do the usual traversal.
752                  */
753         }
754
755         if (ignore_if_in_upstream)
756                 get_patch_ids(&rev, &ids, prefix);
757
758         if (!use_stdout)
759                 realstdout = xfdopen(xdup(1), "w");
760
761         prepare_revision_walk(&rev);
762         while ((commit = get_revision(&rev)) != NULL) {
763                 /* ignore merges */
764                 if (commit->parents && commit->parents->next)
765                         continue;
766
767                 if (ignore_if_in_upstream &&
768                                 has_commit_patch_id(commit, &ids))
769                         continue;
770
771                 nr++;
772                 list = xrealloc(list, nr * sizeof(list[0]));
773                 list[nr - 1] = commit;
774         }
775         total = nr;
776         if (!keep_subject && auto_number && total > 1)
777                 numbered = 1;
778         if (numbered)
779                 rev.total = total + start_number - 1;
780         rev.add_signoff = add_signoff;
781         if (in_reply_to)
782                 rev.ref_message_id = clean_message_id(in_reply_to);
783         while (0 <= --nr) {
784                 int shown;
785                 commit = list[nr];
786                 rev.nr = total - nr + (start_number - 1);
787                 /* Make the second and subsequent mails replies to the first */
788                 if (thread) {
789                         if (nr == (total - 2)) {
790                                 strncpy(ref_message_id, message_id,
791                                         sizeof(ref_message_id));
792                                 ref_message_id[sizeof(ref_message_id)-1]='\0';
793                                 rev.ref_message_id = ref_message_id;
794                         }
795                         gen_message_id(message_id, sizeof(message_id),
796                                        sha1_to_hex(commit->object.sha1));
797                         rev.message_id = message_id;
798                 }
799                 if (!use_stdout)
800                         if (reopen_stdout(commit, rev.nr, keep_subject,
801                                           numbered_files))
802                                 die("Failed to create output files");
803                 shown = log_tree_commit(&rev, commit);
804                 free(commit->buffer);
805                 commit->buffer = NULL;
806
807                 /* We put one extra blank line between formatted
808                  * patches and this flag is used by log-tree code
809                  * to see if it needs to emit a LF before showing
810                  * the log; when using one file per patch, we do
811                  * not want the extra blank line.
812                  */
813                 if (!use_stdout)
814                         rev.shown_one = 0;
815                 if (shown) {
816                         if (rev.mime_boundary)
817                                 printf("\n--%s%s--\n\n\n",
818                                        mime_boundary_leader,
819                                        rev.mime_boundary);
820                         else
821                                 printf("-- \n%s\n\n", git_version_string);
822                 }
823                 if (!use_stdout)
824                         fclose(stdout);
825         }
826         free(list);
827         if (ignore_if_in_upstream)
828                 free_patch_ids(&ids);
829         return 0;
830 }
831
832 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
833 {
834         unsigned char sha1[20];
835         if (get_sha1(arg, sha1) == 0) {
836                 struct commit *commit = lookup_commit_reference(sha1);
837                 if (commit) {
838                         commit->object.flags |= flags;
839                         add_pending_object(revs, &commit->object, arg);
840                         return 0;
841                 }
842         }
843         return -1;
844 }
845
846 static const char cherry_usage[] =
847 "git-cherry [-v] <upstream> [<head>] [<limit>]";
848 int cmd_cherry(int argc, const char **argv, const char *prefix)
849 {
850         struct rev_info revs;
851         struct patch_ids ids;
852         struct commit *commit;
853         struct commit_list *list = NULL;
854         const char *upstream;
855         const char *head = "HEAD";
856         const char *limit = NULL;
857         int verbose = 0;
858
859         if (argc > 1 && !strcmp(argv[1], "-v")) {
860                 verbose = 1;
861                 argc--;
862                 argv++;
863         }
864
865         switch (argc) {
866         case 4:
867                 limit = argv[3];
868                 /* FALLTHROUGH */
869         case 3:
870                 head = argv[2];
871                 /* FALLTHROUGH */
872         case 2:
873                 upstream = argv[1];
874                 break;
875         default:
876                 usage(cherry_usage);
877         }
878
879         init_revisions(&revs, prefix);
880         revs.diff = 1;
881         revs.combine_merges = 0;
882         revs.ignore_merges = 1;
883         DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
884
885         if (add_pending_commit(head, &revs, 0))
886                 die("Unknown commit %s", head);
887         if (add_pending_commit(upstream, &revs, UNINTERESTING))
888                 die("Unknown commit %s", upstream);
889
890         /* Don't say anything if head and upstream are the same. */
891         if (revs.pending.nr == 2) {
892                 struct object_array_entry *o = revs.pending.objects;
893                 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
894                         return 0;
895         }
896
897         get_patch_ids(&revs, &ids, prefix);
898
899         if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
900                 die("Unknown commit %s", limit);
901
902         /* reverse the list of commits */
903         prepare_revision_walk(&revs);
904         while ((commit = get_revision(&revs)) != NULL) {
905                 /* ignore merges */
906                 if (commit->parents && commit->parents->next)
907                         continue;
908
909                 commit_list_insert(commit, &list);
910         }
911
912         while (list) {
913                 char sign = '+';
914
915                 commit = list->item;
916                 if (has_commit_patch_id(commit, &ids))
917                         sign = '-';
918
919                 if (verbose) {
920                         struct strbuf buf;
921                         strbuf_init(&buf, 0);
922                         pretty_print_commit(CMIT_FMT_ONELINE, commit,
923                                             &buf, 0, NULL, NULL, 0, 0);
924                         printf("%c %s %s\n", sign,
925                                sha1_to_hex(commit->object.sha1), buf.buf);
926                         strbuf_release(&buf);
927                 }
928                 else {
929                         printf("%c %s\n", sign,
930                                sha1_to_hex(commit->object.sha1));
931                 }
932
933                 list = list->next;
934         }
935
936         free_patch_ids(&ids);
937         return 0;
938 }