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