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