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