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