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