merge: backport GIT_MERGE_AUTOEDIT support
[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 "color.h"
9 #include "commit.h"
10 #include "diff.h"
11 #include "revision.h"
12 #include "log-tree.h"
13 #include "builtin.h"
14 #include "tag.h"
15 #include "reflog-walk.h"
16 #include "patch-ids.h"
17 #include "run-command.h"
18 #include "shortlog.h"
19 #include "remote.h"
20 #include "string-list.h"
21 #include "parse-options.h"
22 #include "branch.h"
23
24 /* Set a default date-time format for git log ("log.date" config variable) */
25 static const char *default_date_mode = NULL;
26
27 static int default_abbrev_commit;
28 static int default_show_root = 1;
29 static int decoration_style;
30 static int decoration_given;
31 static const char *fmt_patch_subject_prefix = "PATCH";
32 static const char *fmt_pretty;
33
34 static const char * const builtin_log_usage[] = {
35         "git log [<options>] [<since>..<until>] [[--] <path>...]\n"
36         "   or: git show [options] <object>...",
37         NULL
38 };
39
40 static int parse_decoration_style(const char *var, const char *value)
41 {
42         switch (git_config_maybe_bool(var, value)) {
43         case 1:
44                 return DECORATE_SHORT_REFS;
45         case 0:
46                 return 0;
47         default:
48                 break;
49         }
50         if (!strcmp(value, "full"))
51                 return DECORATE_FULL_REFS;
52         else if (!strcmp(value, "short"))
53                 return DECORATE_SHORT_REFS;
54         return -1;
55 }
56
57 static int decorate_callback(const struct option *opt, const char *arg, int unset)
58 {
59         if (unset)
60                 decoration_style = 0;
61         else if (arg)
62                 decoration_style = parse_decoration_style("command line", arg);
63         else
64                 decoration_style = DECORATE_SHORT_REFS;
65
66         if (decoration_style < 0)
67                 die("invalid --decorate option: %s", arg);
68
69         decoration_given = 1;
70
71         return 0;
72 }
73
74 static void cmd_log_init_defaults(struct rev_info *rev)
75 {
76         if (fmt_pretty)
77                 get_commit_format(fmt_pretty, rev);
78         rev->verbose_header = 1;
79         DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
80         rev->abbrev_commit = default_abbrev_commit;
81         rev->show_root_diff = default_show_root;
82         rev->subject_prefix = fmt_patch_subject_prefix;
83         DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
84
85         if (default_date_mode)
86                 rev->date_mode = parse_date_format(default_date_mode);
87 }
88
89 static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
90                          struct rev_info *rev, struct setup_revision_opt *opt)
91 {
92         struct userformat_want w;
93         int quiet = 0, source = 0;
94
95         const struct option builtin_log_options[] = {
96                 OPT_BOOLEAN(0, "quiet", &quiet, "suppress diff output"),
97                 OPT_BOOLEAN(0, "source", &source, "show source"),
98                 { OPTION_CALLBACK, 0, "decorate", NULL, NULL, "decorate options",
99                   PARSE_OPT_OPTARG, decorate_callback},
100                 OPT_END()
101         };
102
103         argc = parse_options(argc, argv, prefix,
104                              builtin_log_options, builtin_log_usage,
105                              PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
106                              PARSE_OPT_KEEP_DASHDASH);
107
108         argc = setup_revisions(argc, argv, rev, opt);
109         if (quiet)
110                 rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
111
112         /* Any arguments at this point are not recognized */
113         if (argc > 1)
114                 die("unrecognized argument: %s", argv[1]);
115
116         memset(&w, 0, sizeof(w));
117         userformat_find_requirements(NULL, &w);
118
119         if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
120                 rev->show_notes = 1;
121         if (rev->show_notes)
122                 init_display_notes(&rev->notes_opt);
123
124         if (rev->diffopt.pickaxe || rev->diffopt.filter)
125                 rev->always_show_header = 0;
126         if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
127                 rev->always_show_header = 0;
128                 if (rev->diffopt.pathspec.nr != 1)
129                         usage("git logs can only follow renames on one pathname at a time");
130         }
131
132         if (source)
133                 rev->show_source = 1;
134
135         if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
136                 /*
137                  * "log --pretty=raw" is special; ignore UI oriented
138                  * configuration variables such as decoration.
139                  */
140                 if (!decoration_given)
141                         decoration_style = 0;
142                 if (!rev->abbrev_commit_given)
143                         rev->abbrev_commit = 0;
144         }
145
146         if (decoration_style) {
147                 rev->show_decorations = 1;
148                 load_ref_decorations(decoration_style);
149         }
150         setup_pager();
151 }
152
153 static void cmd_log_init(int argc, const char **argv, const char *prefix,
154                          struct rev_info *rev, struct setup_revision_opt *opt)
155 {
156         cmd_log_init_defaults(rev);
157         cmd_log_init_finish(argc, argv, prefix, rev, opt);
158 }
159
160 /*
161  * This gives a rough estimate for how many commits we
162  * will print out in the list.
163  */
164 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
165 {
166         int n = 0;
167
168         while (list) {
169                 struct commit *commit = list->item;
170                 unsigned int flags = commit->object.flags;
171                 list = list->next;
172                 if (!(flags & (TREESAME | UNINTERESTING)))
173                         n++;
174         }
175         return n;
176 }
177
178 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
179 {
180         if (rev->shown_one) {
181                 rev->shown_one = 0;
182                 if (rev->commit_format != CMIT_FMT_ONELINE)
183                         putchar(rev->diffopt.line_termination);
184         }
185         printf(_("Final output: %d %s\n"), nr, stage);
186 }
187
188 static struct itimerval early_output_timer;
189
190 static void log_show_early(struct rev_info *revs, struct commit_list *list)
191 {
192         int i = revs->early_output;
193         int show_header = 1;
194
195         sort_in_topological_order(&list, revs->lifo);
196         while (list && i) {
197                 struct commit *commit = list->item;
198                 switch (simplify_commit(revs, commit)) {
199                 case commit_show:
200                         if (show_header) {
201                                 int n = estimate_commit_count(revs, list);
202                                 show_early_header(revs, "incomplete", n);
203                                 show_header = 0;
204                         }
205                         log_tree_commit(revs, commit);
206                         i--;
207                         break;
208                 case commit_ignore:
209                         break;
210                 case commit_error:
211                         return;
212                 }
213                 list = list->next;
214         }
215
216         /* Did we already get enough commits for the early output? */
217         if (!i)
218                 return;
219
220         /*
221          * ..if no, then repeat it twice a second until we
222          * do.
223          *
224          * NOTE! We don't use "it_interval", because if the
225          * reader isn't listening, we want our output to be
226          * throttled by the writing, and not have the timer
227          * trigger every second even if we're blocked on a
228          * reader!
229          */
230         early_output_timer.it_value.tv_sec = 0;
231         early_output_timer.it_value.tv_usec = 500000;
232         setitimer(ITIMER_REAL, &early_output_timer, NULL);
233 }
234
235 static void early_output(int signal)
236 {
237         show_early_output = log_show_early;
238 }
239
240 static void setup_early_output(struct rev_info *rev)
241 {
242         struct sigaction sa;
243
244         /*
245          * Set up the signal handler, minimally intrusively:
246          * we only set a single volatile integer word (not
247          * using sigatomic_t - trying to avoid unnecessary
248          * system dependencies and headers), and using
249          * SA_RESTART.
250          */
251         memset(&sa, 0, sizeof(sa));
252         sa.sa_handler = early_output;
253         sigemptyset(&sa.sa_mask);
254         sa.sa_flags = SA_RESTART;
255         sigaction(SIGALRM, &sa, NULL);
256
257         /*
258          * If we can get the whole output in less than a
259          * tenth of a second, don't even bother doing the
260          * early-output thing..
261          *
262          * This is a one-time-only trigger.
263          */
264         early_output_timer.it_value.tv_sec = 0;
265         early_output_timer.it_value.tv_usec = 100000;
266         setitimer(ITIMER_REAL, &early_output_timer, NULL);
267 }
268
269 static void finish_early_output(struct rev_info *rev)
270 {
271         int n = estimate_commit_count(rev, rev->commits);
272         signal(SIGALRM, SIG_IGN);
273         show_early_header(rev, "done", n);
274 }
275
276 static int cmd_log_walk(struct rev_info *rev)
277 {
278         struct commit *commit;
279         int saved_nrl = 0;
280         int saved_dcctc = 0;
281
282         if (rev->early_output)
283                 setup_early_output(rev);
284
285         if (prepare_revision_walk(rev))
286                 die(_("revision walk setup failed"));
287
288         if (rev->early_output)
289                 finish_early_output(rev);
290
291         /*
292          * For --check and --exit-code, the exit code is based on CHECK_FAILED
293          * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
294          * retain that state information if replacing rev->diffopt in this loop
295          */
296         while ((commit = get_revision(rev)) != NULL) {
297                 if (!log_tree_commit(rev, commit) &&
298                     rev->max_count >= 0)
299                         /*
300                          * We decremented max_count in get_revision,
301                          * but we didn't actually show the commit.
302                          */
303                         rev->max_count++;
304                 if (!rev->reflog_info) {
305                         /* we allow cycles in reflog ancestry */
306                         free(commit->buffer);
307                         commit->buffer = NULL;
308                 }
309                 free_commit_list(commit->parents);
310                 commit->parents = NULL;
311                 if (saved_nrl < rev->diffopt.needed_rename_limit)
312                         saved_nrl = rev->diffopt.needed_rename_limit;
313                 if (rev->diffopt.degraded_cc_to_c)
314                         saved_dcctc = 1;
315         }
316         rev->diffopt.degraded_cc_to_c = saved_dcctc;
317         rev->diffopt.needed_rename_limit = saved_nrl;
318
319         if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
320             DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
321                 return 02;
322         }
323         return diff_result_code(&rev->diffopt, 0);
324 }
325
326 static int git_log_config(const char *var, const char *value, void *cb)
327 {
328         if (!strcmp(var, "format.pretty"))
329                 return git_config_string(&fmt_pretty, var, value);
330         if (!strcmp(var, "format.subjectprefix"))
331                 return git_config_string(&fmt_patch_subject_prefix, var, value);
332         if (!strcmp(var, "log.abbrevcommit")) {
333                 default_abbrev_commit = git_config_bool(var, value);
334                 return 0;
335         }
336         if (!strcmp(var, "log.date"))
337                 return git_config_string(&default_date_mode, var, value);
338         if (!strcmp(var, "log.decorate")) {
339                 decoration_style = parse_decoration_style(var, value);
340                 if (decoration_style < 0)
341                         decoration_style = 0; /* maybe warn? */
342                 return 0;
343         }
344         if (!strcmp(var, "log.showroot")) {
345                 default_show_root = git_config_bool(var, value);
346                 return 0;
347         }
348         if (!prefixcmp(var, "color.decorate."))
349                 return parse_decorate_color_config(var, 15, value);
350
351         return git_diff_ui_config(var, value, cb);
352 }
353
354 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
355 {
356         struct rev_info rev;
357         struct setup_revision_opt opt;
358
359         git_config(git_log_config, NULL);
360
361         init_revisions(&rev, prefix);
362         rev.diff = 1;
363         rev.simplify_history = 0;
364         memset(&opt, 0, sizeof(opt));
365         opt.def = "HEAD";
366         cmd_log_init(argc, argv, prefix, &rev, &opt);
367         if (!rev.diffopt.output_format)
368                 rev.diffopt.output_format = DIFF_FORMAT_RAW;
369         return cmd_log_walk(&rev);
370 }
371
372 static void show_tagger(char *buf, int len, struct rev_info *rev)
373 {
374         struct strbuf out = STRBUF_INIT;
375         struct pretty_print_context pp = {0};
376
377         pp.fmt = rev->commit_format;
378         pp.date_mode = rev->date_mode;
379         pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
380         printf("%s", out.buf);
381         strbuf_release(&out);
382 }
383
384 static int show_object(const unsigned char *sha1, int show_tag_object,
385         struct rev_info *rev)
386 {
387         unsigned long size;
388         enum object_type type;
389         char *buf = read_sha1_file(sha1, &type, &size);
390         int offset = 0;
391
392         if (!buf)
393                 return error(_("Could not read object %s"), sha1_to_hex(sha1));
394
395         if (show_tag_object)
396                 while (offset < size && buf[offset] != '\n') {
397                         int new_offset = offset + 1;
398                         while (new_offset < size && buf[new_offset++] != '\n')
399                                 ; /* do nothing */
400                         if (!prefixcmp(buf + offset, "tagger "))
401                                 show_tagger(buf + offset + 7,
402                                             new_offset - offset - 7, rev);
403                         offset = new_offset;
404                 }
405
406         if (offset < size)
407                 fwrite(buf + offset, size - offset, 1, stdout);
408         free(buf);
409         return 0;
410 }
411
412 static int show_tree_object(const unsigned char *sha1,
413                 const char *base, int baselen,
414                 const char *pathname, unsigned mode, int stage, void *context)
415 {
416         printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
417         return 0;
418 }
419
420 static void show_rev_tweak_rev(struct rev_info *rev, struct setup_revision_opt *opt)
421 {
422         if (rev->ignore_merges) {
423                 /* There was no "-m" on the command line */
424                 rev->ignore_merges = 0;
425                 if (!rev->first_parent_only && !rev->combine_merges) {
426                         /* No "--first-parent", "-c", nor "--cc" */
427                         rev->combine_merges = 1;
428                         rev->dense_combined_merges = 1;
429                 }
430         }
431         if (!rev->diffopt.output_format)
432                 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
433 }
434
435 int cmd_show(int argc, const char **argv, const char *prefix)
436 {
437         struct rev_info rev;
438         struct object_array_entry *objects;
439         struct setup_revision_opt opt;
440         struct pathspec match_all;
441         int i, count, ret = 0;
442
443         git_config(git_log_config, NULL);
444
445         init_pathspec(&match_all, NULL);
446         init_revisions(&rev, prefix);
447         rev.diff = 1;
448         rev.always_show_header = 1;
449         rev.no_walk = 1;
450         memset(&opt, 0, sizeof(opt));
451         opt.def = "HEAD";
452         opt.tweak = show_rev_tweak_rev;
453         cmd_log_init(argc, argv, prefix, &rev, &opt);
454
455         count = rev.pending.nr;
456         objects = rev.pending.objects;
457         for (i = 0; i < count && !ret; i++) {
458                 struct object *o = objects[i].item;
459                 const char *name = objects[i].name;
460                 switch (o->type) {
461                 case OBJ_BLOB:
462                         ret = show_object(o->sha1, 0, NULL);
463                         break;
464                 case OBJ_TAG: {
465                         struct tag *t = (struct tag *)o;
466
467                         if (rev.shown_one)
468                                 putchar('\n');
469                         printf("%stag %s%s\n",
470                                         diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
471                                         t->tag,
472                                         diff_get_color_opt(&rev.diffopt, DIFF_RESET));
473                         ret = show_object(o->sha1, 1, &rev);
474                         rev.shown_one = 1;
475                         if (ret)
476                                 break;
477                         o = parse_object(t->tagged->sha1);
478                         if (!o)
479                                 ret = error(_("Could not read object %s"),
480                                             sha1_to_hex(t->tagged->sha1));
481                         objects[i].item = o;
482                         i--;
483                         break;
484                 }
485                 case OBJ_TREE:
486                         if (rev.shown_one)
487                                 putchar('\n');
488                         printf("%stree %s%s\n\n",
489                                         diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
490                                         name,
491                                         diff_get_color_opt(&rev.diffopt, DIFF_RESET));
492                         read_tree_recursive((struct tree *)o, "", 0, 0, &match_all,
493                                         show_tree_object, NULL);
494                         rev.shown_one = 1;
495                         break;
496                 case OBJ_COMMIT:
497                         rev.pending.nr = rev.pending.alloc = 0;
498                         rev.pending.objects = NULL;
499                         add_object_array(o, name, &rev.pending);
500                         ret = cmd_log_walk(&rev);
501                         break;
502                 default:
503                         ret = error(_("Unknown type: %d"), o->type);
504                 }
505         }
506         free(objects);
507         return ret;
508 }
509
510 /*
511  * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
512  */
513 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
514 {
515         struct rev_info rev;
516         struct setup_revision_opt opt;
517
518         git_config(git_log_config, NULL);
519
520         init_revisions(&rev, prefix);
521         init_reflog_walk(&rev.reflog_info);
522         rev.verbose_header = 1;
523         memset(&opt, 0, sizeof(opt));
524         opt.def = "HEAD";
525         cmd_log_init_defaults(&rev);
526         rev.abbrev_commit = 1;
527         rev.commit_format = CMIT_FMT_ONELINE;
528         rev.use_terminator = 1;
529         rev.always_show_header = 1;
530         cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
531
532         return cmd_log_walk(&rev);
533 }
534
535 int cmd_log(int argc, const char **argv, const char *prefix)
536 {
537         struct rev_info rev;
538         struct setup_revision_opt opt;
539
540         git_config(git_log_config, NULL);
541
542         init_revisions(&rev, prefix);
543         rev.always_show_header = 1;
544         memset(&opt, 0, sizeof(opt));
545         opt.def = "HEAD";
546         cmd_log_init(argc, argv, prefix, &rev, &opt);
547         return cmd_log_walk(&rev);
548 }
549
550 /* format-patch */
551
552 static const char *fmt_patch_suffix = ".patch";
553 static int numbered = 0;
554 static int auto_number = 1;
555
556 static char *default_attach = NULL;
557
558 static struct string_list extra_hdr;
559 static struct string_list extra_to;
560 static struct string_list extra_cc;
561
562 static void add_header(const char *value)
563 {
564         struct string_list_item *item;
565         int len = strlen(value);
566         while (len && value[len - 1] == '\n')
567                 len--;
568
569         if (!strncasecmp(value, "to: ", 4)) {
570                 item = string_list_append(&extra_to, value + 4);
571                 len -= 4;
572         } else if (!strncasecmp(value, "cc: ", 4)) {
573                 item = string_list_append(&extra_cc, value + 4);
574                 len -= 4;
575         } else {
576                 item = string_list_append(&extra_hdr, value);
577         }
578
579         item->string[len] = '\0';
580 }
581
582 #define THREAD_SHALLOW 1
583 #define THREAD_DEEP 2
584 static int thread;
585 static int do_signoff;
586 static const char *signature = git_version_string;
587
588 static int git_format_config(const char *var, const char *value, void *cb)
589 {
590         if (!strcmp(var, "format.headers")) {
591                 if (!value)
592                         die(_("format.headers without value"));
593                 add_header(value);
594                 return 0;
595         }
596         if (!strcmp(var, "format.suffix"))
597                 return git_config_string(&fmt_patch_suffix, var, value);
598         if (!strcmp(var, "format.to")) {
599                 if (!value)
600                         return config_error_nonbool(var);
601                 string_list_append(&extra_to, value);
602                 return 0;
603         }
604         if (!strcmp(var, "format.cc")) {
605                 if (!value)
606                         return config_error_nonbool(var);
607                 string_list_append(&extra_cc, value);
608                 return 0;
609         }
610         if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
611             !strcmp(var, "color.ui")) {
612                 return 0;
613         }
614         if (!strcmp(var, "format.numbered")) {
615                 if (value && !strcasecmp(value, "auto")) {
616                         auto_number = 1;
617                         return 0;
618                 }
619                 numbered = git_config_bool(var, value);
620                 auto_number = auto_number && numbered;
621                 return 0;
622         }
623         if (!strcmp(var, "format.attach")) {
624                 if (value && *value)
625                         default_attach = xstrdup(value);
626                 else
627                         default_attach = xstrdup(git_version_string);
628                 return 0;
629         }
630         if (!strcmp(var, "format.thread")) {
631                 if (value && !strcasecmp(value, "deep")) {
632                         thread = THREAD_DEEP;
633                         return 0;
634                 }
635                 if (value && !strcasecmp(value, "shallow")) {
636                         thread = THREAD_SHALLOW;
637                         return 0;
638                 }
639                 thread = git_config_bool(var, value) && THREAD_SHALLOW;
640                 return 0;
641         }
642         if (!strcmp(var, "format.signoff")) {
643                 do_signoff = git_config_bool(var, value);
644                 return 0;
645         }
646         if (!strcmp(var, "format.signature"))
647                 return git_config_string(&signature, var, value);
648
649         return git_log_config(var, value, cb);
650 }
651
652 static FILE *realstdout = NULL;
653 static const char *output_directory = NULL;
654 static int outdir_offset;
655
656 static int reopen_stdout(struct commit *commit, struct rev_info *rev, int quiet)
657 {
658         struct strbuf filename = STRBUF_INIT;
659         int suffix_len = strlen(fmt_patch_suffix) + 1;
660
661         if (output_directory) {
662                 strbuf_addstr(&filename, output_directory);
663                 if (filename.len >=
664                     PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
665                         return error(_("name of output directory is too long"));
666                 if (filename.buf[filename.len - 1] != '/')
667                         strbuf_addch(&filename, '/');
668         }
669
670         get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
671
672         if (!quiet)
673                 fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
674
675         if (freopen(filename.buf, "w", stdout) == NULL)
676                 return error(_("Cannot open patch file %s"), filename.buf);
677
678         strbuf_release(&filename);
679         return 0;
680 }
681
682 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
683 {
684         struct rev_info check_rev;
685         struct commit *commit;
686         struct object *o1, *o2;
687         unsigned flags1, flags2;
688
689         if (rev->pending.nr != 2)
690                 die(_("Need exactly one range."));
691
692         o1 = rev->pending.objects[0].item;
693         flags1 = o1->flags;
694         o2 = rev->pending.objects[1].item;
695         flags2 = o2->flags;
696
697         if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
698                 die(_("Not a range."));
699
700         init_patch_ids(ids);
701
702         /* given a range a..b get all patch ids for b..a */
703         init_revisions(&check_rev, prefix);
704         o1->flags ^= UNINTERESTING;
705         o2->flags ^= UNINTERESTING;
706         add_pending_object(&check_rev, o1, "o1");
707         add_pending_object(&check_rev, o2, "o2");
708         if (prepare_revision_walk(&check_rev))
709                 die(_("revision walk setup failed"));
710
711         while ((commit = get_revision(&check_rev)) != NULL) {
712                 /* ignore merges */
713                 if (commit->parents && commit->parents->next)
714                         continue;
715
716                 add_commit_patch_id(commit, ids);
717         }
718
719         /* reset for next revision walk */
720         clear_commit_marks((struct commit *)o1,
721                         SEEN | UNINTERESTING | SHOWN | ADDED);
722         clear_commit_marks((struct commit *)o2,
723                         SEEN | UNINTERESTING | SHOWN | ADDED);
724         o1->flags = flags1;
725         o2->flags = flags2;
726 }
727
728 static void gen_message_id(struct rev_info *info, char *base)
729 {
730         const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
731         const char *email_start = strrchr(committer, '<');
732         const char *email_end = strrchr(committer, '>');
733         struct strbuf buf = STRBUF_INIT;
734         if (!email_start || !email_end || email_start > email_end - 1)
735                 die(_("Could not extract email from committer identity."));
736         strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
737                     (unsigned long) time(NULL),
738                     (int)(email_end - email_start - 1), email_start + 1);
739         info->message_id = strbuf_detach(&buf, NULL);
740 }
741
742 static void print_signature(void)
743 {
744         if (signature && *signature)
745                 printf("-- \n%s\n\n", signature);
746 }
747
748 static void add_branch_description(struct strbuf *buf, const char *branch_name)
749 {
750         struct strbuf desc = STRBUF_INIT;
751         if (!branch_name || !*branch_name)
752                 return;
753         read_branch_desc(&desc, branch_name);
754         if (desc.len) {
755                 strbuf_addch(buf, '\n');
756                 strbuf_add(buf, desc.buf, desc.len);
757                 strbuf_addch(buf, '\n');
758         }
759 }
760
761 static void make_cover_letter(struct rev_info *rev, int use_stdout,
762                               int numbered, int numbered_files,
763                               struct commit *origin,
764                               int nr, struct commit **list, struct commit *head,
765                               const char *branch_name,
766                               int quiet)
767 {
768         const char *committer;
769         const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
770         const char *msg;
771         struct shortlog log;
772         struct strbuf sb = STRBUF_INIT;
773         int i;
774         const char *encoding = "UTF-8";
775         struct diff_options opts;
776         int need_8bit_cte = 0;
777         struct commit *commit = NULL;
778         struct pretty_print_context pp = {0};
779
780         if (rev->commit_format != CMIT_FMT_EMAIL)
781                 die(_("Cover letter needs email format"));
782
783         committer = git_committer_info(0);
784
785         if (!numbered_files) {
786                 /*
787                  * We fake a commit for the cover letter so we get the filename
788                  * desired.
789                  */
790                 commit = xcalloc(1, sizeof(*commit));
791                 commit->buffer = xmalloc(400);
792                 snprintf(commit->buffer, 400,
793                         "tree 0000000000000000000000000000000000000000\n"
794                         "parent %s\n"
795                         "author %s\n"
796                         "committer %s\n\n"
797                         "cover letter\n",
798                         sha1_to_hex(head->object.sha1), committer, committer);
799         }
800
801         if (!use_stdout && reopen_stdout(commit, rev, quiet))
802                 return;
803
804         if (commit) {
805
806                 free(commit->buffer);
807                 free(commit);
808         }
809
810         log_write_email_headers(rev, head, &pp.subject, &pp.after_subject,
811                                 &need_8bit_cte);
812
813         for (i = 0; !need_8bit_cte && i < nr; i++)
814                 if (has_non_ascii(list[i]->buffer))
815                         need_8bit_cte = 1;
816
817         msg = body;
818         pp.fmt = CMIT_FMT_EMAIL;
819         pp.date_mode = DATE_RFC2822;
820         pp_user_info(&pp, NULL, &sb, committer, encoding);
821         pp_title_line(&pp, &msg, &sb, encoding, need_8bit_cte);
822         pp_remainder(&pp, &msg, &sb, 0);
823         add_branch_description(&sb, branch_name);
824         printf("%s\n", sb.buf);
825
826         strbuf_release(&sb);
827
828         shortlog_init(&log);
829         log.wrap_lines = 1;
830         log.wrap = 72;
831         log.in1 = 2;
832         log.in2 = 4;
833         for (i = 0; i < nr; i++)
834                 shortlog_add_commit(&log, list[i]);
835
836         shortlog_output(&log);
837
838         /*
839          * We can only do diffstat with a unique reference point
840          */
841         if (!origin)
842                 return;
843
844         memcpy(&opts, &rev->diffopt, sizeof(opts));
845         opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
846
847         diff_setup_done(&opts);
848
849         diff_tree_sha1(origin->tree->object.sha1,
850                        head->tree->object.sha1,
851                        "", &opts);
852         diffcore_std(&opts);
853         diff_flush(&opts);
854
855         printf("\n");
856         print_signature();
857 }
858
859 static const char *clean_message_id(const char *msg_id)
860 {
861         char ch;
862         const char *a, *z, *m;
863
864         m = msg_id;
865         while ((ch = *m) && (isspace(ch) || (ch == '<')))
866                 m++;
867         a = m;
868         z = NULL;
869         while ((ch = *m)) {
870                 if (!isspace(ch) && (ch != '>'))
871                         z = m;
872                 m++;
873         }
874         if (!z)
875                 die(_("insane in-reply-to: %s"), msg_id);
876         if (++z == m)
877                 return a;
878         return xmemdupz(a, z - a);
879 }
880
881 static const char *set_outdir(const char *prefix, const char *output_directory)
882 {
883         if (output_directory && is_absolute_path(output_directory))
884                 return output_directory;
885
886         if (!prefix || !*prefix) {
887                 if (output_directory)
888                         return output_directory;
889                 /* The user did not explicitly ask for "./" */
890                 outdir_offset = 2;
891                 return "./";
892         }
893
894         outdir_offset = strlen(prefix);
895         if (!output_directory)
896                 return prefix;
897
898         return xstrdup(prefix_filename(prefix, outdir_offset,
899                                        output_directory));
900 }
901
902 static const char * const builtin_format_patch_usage[] = {
903         "git format-patch [options] [<since> | <revision range>]",
904         NULL
905 };
906
907 static int keep_subject = 0;
908
909 static int keep_callback(const struct option *opt, const char *arg, int unset)
910 {
911         ((struct rev_info *)opt->value)->total = -1;
912         keep_subject = 1;
913         return 0;
914 }
915
916 static int subject_prefix = 0;
917
918 static int subject_prefix_callback(const struct option *opt, const char *arg,
919                             int unset)
920 {
921         subject_prefix = 1;
922         ((struct rev_info *)opt->value)->subject_prefix = arg;
923         return 0;
924 }
925
926 static int numbered_cmdline_opt = 0;
927
928 static int numbered_callback(const struct option *opt, const char *arg,
929                              int unset)
930 {
931         *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
932         if (unset)
933                 auto_number =  0;
934         return 0;
935 }
936
937 static int no_numbered_callback(const struct option *opt, const char *arg,
938                                 int unset)
939 {
940         return numbered_callback(opt, arg, 1);
941 }
942
943 static int output_directory_callback(const struct option *opt, const char *arg,
944                               int unset)
945 {
946         const char **dir = (const char **)opt->value;
947         if (*dir)
948                 die(_("Two output directories?"));
949         *dir = arg;
950         return 0;
951 }
952
953 static int thread_callback(const struct option *opt, const char *arg, int unset)
954 {
955         int *thread = (int *)opt->value;
956         if (unset)
957                 *thread = 0;
958         else if (!arg || !strcmp(arg, "shallow"))
959                 *thread = THREAD_SHALLOW;
960         else if (!strcmp(arg, "deep"))
961                 *thread = THREAD_DEEP;
962         else
963                 return 1;
964         return 0;
965 }
966
967 static int attach_callback(const struct option *opt, const char *arg, int unset)
968 {
969         struct rev_info *rev = (struct rev_info *)opt->value;
970         if (unset)
971                 rev->mime_boundary = NULL;
972         else if (arg)
973                 rev->mime_boundary = arg;
974         else
975                 rev->mime_boundary = git_version_string;
976         rev->no_inline = unset ? 0 : 1;
977         return 0;
978 }
979
980 static int inline_callback(const struct option *opt, const char *arg, int unset)
981 {
982         struct rev_info *rev = (struct rev_info *)opt->value;
983         if (unset)
984                 rev->mime_boundary = NULL;
985         else if (arg)
986                 rev->mime_boundary = arg;
987         else
988                 rev->mime_boundary = git_version_string;
989         rev->no_inline = 0;
990         return 0;
991 }
992
993 static int header_callback(const struct option *opt, const char *arg, int unset)
994 {
995         if (unset) {
996                 string_list_clear(&extra_hdr, 0);
997                 string_list_clear(&extra_to, 0);
998                 string_list_clear(&extra_cc, 0);
999         } else {
1000             add_header(arg);
1001         }
1002         return 0;
1003 }
1004
1005 static int to_callback(const struct option *opt, const char *arg, int unset)
1006 {
1007         if (unset)
1008                 string_list_clear(&extra_to, 0);
1009         else
1010                 string_list_append(&extra_to, arg);
1011         return 0;
1012 }
1013
1014 static int cc_callback(const struct option *opt, const char *arg, int unset)
1015 {
1016         if (unset)
1017                 string_list_clear(&extra_cc, 0);
1018         else
1019                 string_list_append(&extra_cc, arg);
1020         return 0;
1021 }
1022
1023 static char *find_branch_name(struct rev_info *rev)
1024 {
1025         int i, positive = -1;
1026         unsigned char branch_sha1[20];
1027         struct strbuf buf = STRBUF_INIT;
1028         const char *branch;
1029
1030         for (i = 0; i < rev->cmdline.nr; i++) {
1031                 if (rev->cmdline.rev[i].flags & UNINTERESTING)
1032                         continue;
1033                 if (positive < 0)
1034                         positive = i;
1035                 else
1036                         return NULL;
1037         }
1038         if (positive < 0)
1039                 return NULL;
1040         strbuf_addf(&buf, "refs/heads/%s", rev->cmdline.rev[positive].name);
1041         branch = resolve_ref_unsafe(buf.buf, branch_sha1, 1, NULL);
1042         if (!branch ||
1043             prefixcmp(branch, "refs/heads/") ||
1044             hashcmp(rev->cmdline.rev[positive].item->sha1, branch_sha1))
1045                 branch = NULL;
1046         strbuf_release(&buf);
1047         if (branch)
1048                 return xstrdup(rev->cmdline.rev[positive].name);
1049         return NULL;
1050 }
1051
1052 int cmd_format_patch(int argc, const char **argv, const char *prefix)
1053 {
1054         struct commit *commit;
1055         struct commit **list = NULL;
1056         struct rev_info rev;
1057         struct setup_revision_opt s_r_opt;
1058         int nr = 0, total, i;
1059         int use_stdout = 0;
1060         int start_number = -1;
1061         int numbered_files = 0;         /* _just_ numbers */
1062         int ignore_if_in_upstream = 0;
1063         int cover_letter = 0;
1064         int boundary_count = 0;
1065         int no_binary_diff = 0;
1066         struct commit *origin = NULL, *head = NULL;
1067         const char *in_reply_to = NULL;
1068         struct patch_ids ids;
1069         char *add_signoff = NULL;
1070         struct strbuf buf = STRBUF_INIT;
1071         int use_patch_format = 0;
1072         int quiet = 0;
1073         char *branch_name = NULL;
1074         const struct option builtin_format_patch_options[] = {
1075                 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
1076                             "use [PATCH n/m] even with a single patch",
1077                             PARSE_OPT_NOARG, numbered_callback },
1078                 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
1079                             "use [PATCH] even with multiple patches",
1080                             PARSE_OPT_NOARG, no_numbered_callback },
1081                 OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
1082                 OPT_BOOLEAN(0, "stdout", &use_stdout,
1083                             "print patches to standard out"),
1084                 OPT_BOOLEAN(0, "cover-letter", &cover_letter,
1085                             "generate a cover letter"),
1086                 OPT_BOOLEAN(0, "numbered-files", &numbered_files,
1087                             "use simple number sequence for output file names"),
1088                 OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
1089                             "use <sfx> instead of '.patch'"),
1090                 OPT_INTEGER(0, "start-number", &start_number,
1091                             "start numbering patches at <n> instead of 1"),
1092                 { OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
1093                             "Use [<prefix>] instead of [PATCH]",
1094                             PARSE_OPT_NONEG, subject_prefix_callback },
1095                 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
1096                             "dir", "store resulting files in <dir>",
1097                             PARSE_OPT_NONEG, output_directory_callback },
1098                 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
1099                             "don't strip/add [PATCH]",
1100                             PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
1101                 OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
1102                             "don't output binary diffs"),
1103                 OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1104                             "don't include a patch matching a commit upstream"),
1105                 { OPTION_BOOLEAN, 'p', "no-stat", &use_patch_format, NULL,
1106                   "show patch format instead of default (patch + stat)",
1107                   PARSE_OPT_NONEG | PARSE_OPT_NOARG },
1108                 OPT_GROUP("Messaging"),
1109                 { OPTION_CALLBACK, 0, "add-header", NULL, "header",
1110                             "add email header", 0, header_callback },
1111                 { OPTION_CALLBACK, 0, "to", NULL, "email", "add To: header",
1112                             0, to_callback },
1113                 { OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
1114                             0, cc_callback },
1115                 OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
1116                             "make first mail a reply to <message-id>"),
1117                 { OPTION_CALLBACK, 0, "attach", &rev, "boundary",
1118                             "attach the patch", PARSE_OPT_OPTARG,
1119                             attach_callback },
1120                 { OPTION_CALLBACK, 0, "inline", &rev, "boundary",
1121                             "inline the patch",
1122                             PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1123                             inline_callback },
1124                 { OPTION_CALLBACK, 0, "thread", &thread, "style",
1125                             "enable message threading, styles: shallow, deep",
1126                             PARSE_OPT_OPTARG, thread_callback },
1127                 OPT_STRING(0, "signature", &signature, "signature",
1128                             "add a signature"),
1129                 OPT_BOOLEAN(0, "quiet", &quiet,
1130                             "don't print the patch filenames"),
1131                 OPT_END()
1132         };
1133
1134         extra_hdr.strdup_strings = 1;
1135         extra_to.strdup_strings = 1;
1136         extra_cc.strdup_strings = 1;
1137         git_config(git_format_config, NULL);
1138         init_revisions(&rev, prefix);
1139         rev.commit_format = CMIT_FMT_EMAIL;
1140         rev.verbose_header = 1;
1141         rev.diff = 1;
1142         rev.max_parents = 1;
1143         DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
1144         rev.subject_prefix = fmt_patch_subject_prefix;
1145         memset(&s_r_opt, 0, sizeof(s_r_opt));
1146         s_r_opt.def = "HEAD";
1147
1148         if (default_attach) {
1149                 rev.mime_boundary = default_attach;
1150                 rev.no_inline = 1;
1151         }
1152
1153         /*
1154          * Parse the arguments before setup_revisions(), or something
1155          * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1156          * possibly a valid SHA1.
1157          */
1158         argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1159                              builtin_format_patch_usage,
1160                              PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1161                              PARSE_OPT_KEEP_DASHDASH);
1162
1163         if (do_signoff) {
1164                 const char *committer;
1165                 const char *endpos;
1166                 committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
1167                 endpos = strchr(committer, '>');
1168                 if (!endpos)
1169                         die(_("bogus committer info %s"), committer);
1170                 add_signoff = xmemdupz(committer, endpos - committer + 1);
1171         }
1172
1173         for (i = 0; i < extra_hdr.nr; i++) {
1174                 strbuf_addstr(&buf, extra_hdr.items[i].string);
1175                 strbuf_addch(&buf, '\n');
1176         }
1177
1178         if (extra_to.nr)
1179                 strbuf_addstr(&buf, "To: ");
1180         for (i = 0; i < extra_to.nr; i++) {
1181                 if (i)
1182                         strbuf_addstr(&buf, "    ");
1183                 strbuf_addstr(&buf, extra_to.items[i].string);
1184                 if (i + 1 < extra_to.nr)
1185                         strbuf_addch(&buf, ',');
1186                 strbuf_addch(&buf, '\n');
1187         }
1188
1189         if (extra_cc.nr)
1190                 strbuf_addstr(&buf, "Cc: ");
1191         for (i = 0; i < extra_cc.nr; i++) {
1192                 if (i)
1193                         strbuf_addstr(&buf, "    ");
1194                 strbuf_addstr(&buf, extra_cc.items[i].string);
1195                 if (i + 1 < extra_cc.nr)
1196                         strbuf_addch(&buf, ',');
1197                 strbuf_addch(&buf, '\n');
1198         }
1199
1200         rev.extra_headers = strbuf_detach(&buf, NULL);
1201
1202         if (start_number < 0)
1203                 start_number = 1;
1204
1205         /*
1206          * If numbered is set solely due to format.numbered in config,
1207          * and it would conflict with --keep-subject (-k) from the
1208          * command line, reset "numbered".
1209          */
1210         if (numbered && keep_subject && !numbered_cmdline_opt)
1211                 numbered = 0;
1212
1213         if (numbered && keep_subject)
1214                 die (_("-n and -k are mutually exclusive."));
1215         if (keep_subject && subject_prefix)
1216                 die (_("--subject-prefix and -k are mutually exclusive."));
1217         rev.preserve_subject = keep_subject;
1218
1219         argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1220         if (argc > 1)
1221                 die (_("unrecognized argument: %s"), argv[1]);
1222
1223         if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1224                 die(_("--name-only does not make sense"));
1225         if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1226                 die(_("--name-status does not make sense"));
1227         if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1228                 die(_("--check does not make sense"));
1229
1230         if (!use_patch_format &&
1231                 (!rev.diffopt.output_format ||
1232                  rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1233                 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1234
1235         /* Always generate a patch */
1236         rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1237
1238         if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1239                 DIFF_OPT_SET(&rev.diffopt, BINARY);
1240
1241         if (rev.show_notes)
1242                 init_display_notes(&rev.notes_opt);
1243
1244         if (!use_stdout)
1245                 output_directory = set_outdir(prefix, output_directory);
1246         else
1247                 setup_pager();
1248
1249         if (output_directory) {
1250                 if (use_stdout)
1251                         die(_("standard output, or directory, which one?"));
1252                 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1253                         die_errno(_("Could not create directory '%s'"),
1254                                   output_directory);
1255         }
1256
1257         if (rev.pending.nr == 1) {
1258                 if (rev.max_count < 0 && !rev.show_root_diff) {
1259                         /*
1260                          * This is traditional behaviour of "git format-patch
1261                          * origin" that prepares what the origin side still
1262                          * does not have.
1263                          */
1264                         unsigned char sha1[20];
1265                         const char *ref;
1266
1267                         rev.pending.objects[0].item->flags |= UNINTERESTING;
1268                         add_head_to_pending(&rev);
1269                         ref = resolve_ref_unsafe("HEAD", sha1, 1, NULL);
1270                         if (ref && !prefixcmp(ref, "refs/heads/"))
1271                                 branch_name = xstrdup(ref + strlen("refs/heads/"));
1272                         else
1273                                 branch_name = xstrdup(""); /* no branch */
1274                 }
1275                 /*
1276                  * Otherwise, it is "format-patch -22 HEAD", and/or
1277                  * "format-patch --root HEAD".  The user wants
1278                  * get_revision() to do the usual traversal.
1279                  */
1280         }
1281
1282         /*
1283          * We cannot move this anywhere earlier because we do want to
1284          * know if --root was given explicitly from the command line.
1285          */
1286         rev.show_root_diff = 1;
1287
1288         if (cover_letter) {
1289                 /*
1290                  * NEEDSWORK:randomly pick one positive commit to show
1291                  * diffstat; this is often the tip and the command
1292                  * happens to do the right thing in most cases, but a
1293                  * complex command like "--cover-letter a b c ^bottom"
1294                  * picks "c" and shows diffstat between bottom..c
1295                  * which may not match what the series represents at
1296                  * all and totally broken.
1297                  */
1298                 int i;
1299                 for (i = 0; i < rev.pending.nr; i++) {
1300                         struct object *o = rev.pending.objects[i].item;
1301                         if (!(o->flags & UNINTERESTING))
1302                                 head = (struct commit *)o;
1303                 }
1304                 /* There is nothing to show; it is not an error, though. */
1305                 if (!head)
1306                         return 0;
1307                 if (!branch_name)
1308                         branch_name = find_branch_name(&rev);
1309         }
1310
1311         if (ignore_if_in_upstream) {
1312                 /* Don't say anything if head and upstream are the same. */
1313                 if (rev.pending.nr == 2) {
1314                         struct object_array_entry *o = rev.pending.objects;
1315                         if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1316                                 return 0;
1317                 }
1318                 get_patch_ids(&rev, &ids, prefix);
1319         }
1320
1321         if (!use_stdout)
1322                 realstdout = xfdopen(xdup(1), "w");
1323
1324         if (prepare_revision_walk(&rev))
1325                 die(_("revision walk setup failed"));
1326         rev.boundary = 1;
1327         while ((commit = get_revision(&rev)) != NULL) {
1328                 if (commit->object.flags & BOUNDARY) {
1329                         boundary_count++;
1330                         origin = (boundary_count == 1) ? commit : NULL;
1331                         continue;
1332                 }
1333
1334                 if (ignore_if_in_upstream &&
1335                                 has_commit_patch_id(commit, &ids))
1336                         continue;
1337
1338                 nr++;
1339                 list = xrealloc(list, nr * sizeof(list[0]));
1340                 list[nr - 1] = commit;
1341         }
1342         total = nr;
1343         if (!keep_subject && auto_number && total > 1)
1344                 numbered = 1;
1345         if (numbered)
1346                 rev.total = total + start_number - 1;
1347         if (in_reply_to || thread || cover_letter)
1348                 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1349         if (in_reply_to) {
1350                 const char *msgid = clean_message_id(in_reply_to);
1351                 string_list_append(rev.ref_message_ids, msgid);
1352         }
1353         rev.numbered_files = numbered_files;
1354         rev.patch_suffix = fmt_patch_suffix;
1355         if (cover_letter) {
1356                 if (thread)
1357                         gen_message_id(&rev, "cover");
1358                 make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1359                                   origin, nr, list, head, branch_name, quiet);
1360                 total++;
1361                 start_number--;
1362         }
1363         rev.add_signoff = add_signoff;
1364         while (0 <= --nr) {
1365                 int shown;
1366                 commit = list[nr];
1367                 rev.nr = total - nr + (start_number - 1);
1368                 /* Make the second and subsequent mails replies to the first */
1369                 if (thread) {
1370                         /* Have we already had a message ID? */
1371                         if (rev.message_id) {
1372                                 /*
1373                                  * For deep threading: make every mail
1374                                  * a reply to the previous one, no
1375                                  * matter what other options are set.
1376                                  *
1377                                  * For shallow threading:
1378                                  *
1379                                  * Without --cover-letter and
1380                                  * --in-reply-to, make every mail a
1381                                  * reply to the one before.
1382                                  *
1383                                  * With --in-reply-to but no
1384                                  * --cover-letter, make every mail a
1385                                  * reply to the <reply-to>.
1386                                  *
1387                                  * With --cover-letter, make every
1388                                  * mail but the cover letter a reply
1389                                  * to the cover letter.  The cover
1390                                  * letter is a reply to the
1391                                  * --in-reply-to, if specified.
1392                                  */
1393                                 if (thread == THREAD_SHALLOW
1394                                     && rev.ref_message_ids->nr > 0
1395                                     && (!cover_letter || rev.nr > 1))
1396                                         free(rev.message_id);
1397                                 else
1398                                         string_list_append(rev.ref_message_ids,
1399                                                            rev.message_id);
1400                         }
1401                         gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1402                 }
1403
1404                 if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
1405                                                  &rev, quiet))
1406                         die(_("Failed to create output files"));
1407                 shown = log_tree_commit(&rev, commit);
1408                 free(commit->buffer);
1409                 commit->buffer = NULL;
1410
1411                 /* We put one extra blank line between formatted
1412                  * patches and this flag is used by log-tree code
1413                  * to see if it needs to emit a LF before showing
1414                  * the log; when using one file per patch, we do
1415                  * not want the extra blank line.
1416                  */
1417                 if (!use_stdout)
1418                         rev.shown_one = 0;
1419                 if (shown) {
1420                         if (rev.mime_boundary)
1421                                 printf("\n--%s%s--\n\n\n",
1422                                        mime_boundary_leader,
1423                                        rev.mime_boundary);
1424                         else
1425                                 print_signature();
1426                 }
1427                 if (!use_stdout)
1428                         fclose(stdout);
1429         }
1430         free(list);
1431         free(branch_name);
1432         string_list_clear(&extra_to, 0);
1433         string_list_clear(&extra_cc, 0);
1434         string_list_clear(&extra_hdr, 0);
1435         if (ignore_if_in_upstream)
1436                 free_patch_ids(&ids);
1437         return 0;
1438 }
1439
1440 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1441 {
1442         unsigned char sha1[20];
1443         if (get_sha1(arg, sha1) == 0) {
1444                 struct commit *commit = lookup_commit_reference(sha1);
1445                 if (commit) {
1446                         commit->object.flags |= flags;
1447                         add_pending_object(revs, &commit->object, arg);
1448                         return 0;
1449                 }
1450         }
1451         return -1;
1452 }
1453
1454 static const char * const cherry_usage[] = {
1455         "git cherry [-v] [<upstream> [<head> [<limit>]]]",
1456         NULL
1457 };
1458
1459 static void print_commit(char sign, struct commit *commit, int verbose,
1460                          int abbrev)
1461 {
1462         if (!verbose) {
1463                 printf("%c %s\n", sign,
1464                        find_unique_abbrev(commit->object.sha1, abbrev));
1465         } else {
1466                 struct strbuf buf = STRBUF_INIT;
1467                 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
1468                 printf("%c %s %s\n", sign,
1469                        find_unique_abbrev(commit->object.sha1, abbrev),
1470                        buf.buf);
1471                 strbuf_release(&buf);
1472         }
1473 }
1474
1475 int cmd_cherry(int argc, const char **argv, const char *prefix)
1476 {
1477         struct rev_info revs;
1478         struct patch_ids ids;
1479         struct commit *commit;
1480         struct commit_list *list = NULL;
1481         struct branch *current_branch;
1482         const char *upstream;
1483         const char *head = "HEAD";
1484         const char *limit = NULL;
1485         int verbose = 0, abbrev = 0;
1486
1487         struct option options[] = {
1488                 OPT__ABBREV(&abbrev),
1489                 OPT__VERBOSE(&verbose, "be verbose"),
1490                 OPT_END()
1491         };
1492
1493         argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
1494
1495         switch (argc) {
1496         case 3:
1497                 limit = argv[2];
1498                 /* FALLTHROUGH */
1499         case 2:
1500                 head = argv[1];
1501                 /* FALLTHROUGH */
1502         case 1:
1503                 upstream = argv[0];
1504                 break;
1505         default:
1506                 current_branch = branch_get(NULL);
1507                 if (!current_branch || !current_branch->merge
1508                                         || !current_branch->merge[0]
1509                                         || !current_branch->merge[0]->dst) {
1510                         fprintf(stderr, _("Could not find a tracked"
1511                                         " remote branch, please"
1512                                         " specify <upstream> manually.\n"));
1513                         usage_with_options(cherry_usage, options);
1514                 }
1515
1516                 upstream = current_branch->merge[0]->dst;
1517         }
1518
1519         init_revisions(&revs, prefix);
1520         revs.diff = 1;
1521         revs.combine_merges = 0;
1522         revs.ignore_merges = 1;
1523         DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
1524
1525         if (add_pending_commit(head, &revs, 0))
1526                 die(_("Unknown commit %s"), head);
1527         if (add_pending_commit(upstream, &revs, UNINTERESTING))
1528                 die(_("Unknown commit %s"), upstream);
1529
1530         /* Don't say anything if head and upstream are the same. */
1531         if (revs.pending.nr == 2) {
1532                 struct object_array_entry *o = revs.pending.objects;
1533                 if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
1534                         return 0;
1535         }
1536
1537         get_patch_ids(&revs, &ids, prefix);
1538
1539         if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1540                 die(_("Unknown commit %s"), limit);
1541
1542         /* reverse the list of commits */
1543         if (prepare_revision_walk(&revs))
1544                 die(_("revision walk setup failed"));
1545         while ((commit = get_revision(&revs)) != NULL) {
1546                 /* ignore merges */
1547                 if (commit->parents && commit->parents->next)
1548                         continue;
1549
1550                 commit_list_insert(commit, &list);
1551         }
1552
1553         while (list) {
1554                 char sign = '+';
1555
1556                 commit = list->item;
1557                 if (has_commit_patch_id(commit, &ids))
1558                         sign = '-';
1559                 print_commit(sign, commit, verbose, abbrev);
1560                 list = list->next;
1561         }
1562
1563         free_patch_ids(&ids);
1564         return 0;
1565 }