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