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