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