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