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