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