Merge branch 'cs/pretty-formats-doc-typofix'
[git.git] / builtin / log.c
blobc4b35fdaf9b77c05da927fb3a2800a7fd8da9f91
1 /*
2 * Builtin "git log" and related commands (show, whatchanged)
4 * (C) Copyright 2006 Linus Torvalds
5 * 2006 Junio Hamano
6 */
7 #define USE_THE_INDEX_COMPATIBILITY_MACROS
8 #include "cache.h"
9 #include "config.h"
10 #include "refs.h"
11 #include "object-store.h"
12 #include "color.h"
13 #include "commit.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "log-tree.h"
17 #include "builtin.h"
18 #include "tag.h"
19 #include "reflog-walk.h"
20 #include "patch-ids.h"
21 #include "run-command.h"
22 #include "shortlog.h"
23 #include "remote.h"
24 #include "string-list.h"
25 #include "parse-options.h"
26 #include "line-log.h"
27 #include "branch.h"
28 #include "streaming.h"
29 #include "version.h"
30 #include "mailmap.h"
31 #include "gpg-interface.h"
32 #include "progress.h"
33 #include "commit-slab.h"
34 #include "repository.h"
35 #include "commit-reach.h"
36 #include "interdiff.h"
37 #include "range-diff.h"
39 #define MAIL_DEFAULT_WRAP 72
41 /* Set a default date-time format for git log ("log.date" config variable) */
42 static const char *default_date_mode = NULL;
44 static int default_abbrev_commit;
45 static int default_show_root = 1;
46 static int default_follow;
47 static int default_show_signature;
48 static int decoration_style;
49 static int decoration_given;
50 static int use_mailmap_config = 1;
51 static const char *fmt_patch_subject_prefix = "PATCH";
52 static const char *fmt_pretty;
54 static const char * const builtin_log_usage[] = {
55 N_("git log [<options>] [<revision-range>] [[--] <path>...]"),
56 N_("git show [<options>] <object>..."),
57 NULL
60 struct line_opt_callback_data {
61 struct rev_info *rev;
62 const char *prefix;
63 struct string_list args;
66 static int session_is_interactive(void)
68 return isatty(1) || pager_in_use();
71 static int auto_decoration_style(void)
73 return session_is_interactive() ? DECORATE_SHORT_REFS : 0;
76 static int parse_decoration_style(const char *value)
78 switch (git_parse_maybe_bool(value)) {
79 case 1:
80 return DECORATE_SHORT_REFS;
81 case 0:
82 return 0;
83 default:
84 break;
86 if (!strcmp(value, "full"))
87 return DECORATE_FULL_REFS;
88 else if (!strcmp(value, "short"))
89 return DECORATE_SHORT_REFS;
90 else if (!strcmp(value, "auto"))
91 return auto_decoration_style();
93 * Please update _git_log() in git-completion.bash when you
94 * add new decoration styles.
96 return -1;
99 static int decorate_callback(const struct option *opt, const char *arg, int unset)
101 if (unset)
102 decoration_style = 0;
103 else if (arg)
104 decoration_style = parse_decoration_style(arg);
105 else
106 decoration_style = DECORATE_SHORT_REFS;
108 if (decoration_style < 0)
109 die(_("invalid --decorate option: %s"), arg);
111 decoration_given = 1;
113 return 0;
116 static int log_line_range_callback(const struct option *option, const char *arg, int unset)
118 struct line_opt_callback_data *data = option->value;
120 BUG_ON_OPT_NEG(unset);
122 if (!arg)
123 return -1;
125 data->rev->line_level_traverse = 1;
126 string_list_append(&data->args, arg);
128 return 0;
131 static void init_log_defaults(void)
133 init_grep_defaults(the_repository);
134 init_diff_ui_defaults();
136 decoration_style = auto_decoration_style();
139 static void cmd_log_init_defaults(struct rev_info *rev)
141 if (fmt_pretty)
142 get_commit_format(fmt_pretty, rev);
143 if (default_follow)
144 rev->diffopt.flags.default_follow_renames = 1;
145 rev->verbose_header = 1;
146 rev->diffopt.flags.recursive = 1;
147 rev->diffopt.stat_width = -1; /* use full terminal width */
148 rev->diffopt.stat_graph_width = -1; /* respect statGraphWidth config */
149 rev->abbrev_commit = default_abbrev_commit;
150 rev->show_root_diff = default_show_root;
151 rev->subject_prefix = fmt_patch_subject_prefix;
152 rev->show_signature = default_show_signature;
153 rev->diffopt.flags.allow_textconv = 1;
155 if (default_date_mode)
156 parse_date_format(default_date_mode, &rev->date_mode);
159 static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
160 struct rev_info *rev, struct setup_revision_opt *opt)
162 struct userformat_want w;
163 int quiet = 0, source = 0, mailmap;
164 static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
165 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
166 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
167 struct decoration_filter decoration_filter = {&decorate_refs_include,
168 &decorate_refs_exclude};
169 static struct revision_sources revision_sources;
171 const struct option builtin_log_options[] = {
172 OPT__QUIET(&quiet, N_("suppress diff output")),
173 OPT_BOOL(0, "source", &source, N_("show source")),
174 OPT_BOOL(0, "use-mailmap", &mailmap, N_("Use mail map file")),
175 OPT_STRING_LIST(0, "decorate-refs", &decorate_refs_include,
176 N_("pattern"), N_("only decorate refs that match <pattern>")),
177 OPT_STRING_LIST(0, "decorate-refs-exclude", &decorate_refs_exclude,
178 N_("pattern"), N_("do not decorate refs that match <pattern>")),
179 { OPTION_CALLBACK, 0, "decorate", NULL, NULL, N_("decorate options"),
180 PARSE_OPT_OPTARG, decorate_callback},
181 OPT_CALLBACK('L', NULL, &line_cb, "n,m:file",
182 N_("Process line range n,m in file, counting from 1"),
183 log_line_range_callback),
184 OPT_END()
187 line_cb.rev = rev;
188 line_cb.prefix = prefix;
190 mailmap = use_mailmap_config;
191 argc = parse_options(argc, argv, prefix,
192 builtin_log_options, builtin_log_usage,
193 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
194 PARSE_OPT_KEEP_DASHDASH);
196 if (quiet)
197 rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
198 argc = setup_revisions(argc, argv, rev, opt);
200 /* Any arguments at this point are not recognized */
201 if (argc > 1)
202 die(_("unrecognized argument: %s"), argv[1]);
204 memset(&w, 0, sizeof(w));
205 userformat_find_requirements(NULL, &w);
207 if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
208 rev->show_notes = 1;
209 if (rev->show_notes)
210 init_display_notes(&rev->notes_opt);
212 if ((rev->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
213 rev->diffopt.filter || rev->diffopt.flags.follow_renames)
214 rev->always_show_header = 0;
216 if (source || w.source) {
217 init_revision_sources(&revision_sources);
218 rev->sources = &revision_sources;
221 if (mailmap) {
222 rev->mailmap = xcalloc(1, sizeof(struct string_list));
223 read_mailmap(rev->mailmap, NULL);
226 if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
228 * "log --pretty=raw" is special; ignore UI oriented
229 * configuration variables such as decoration.
231 if (!decoration_given)
232 decoration_style = 0;
233 if (!rev->abbrev_commit_given)
234 rev->abbrev_commit = 0;
237 if (decoration_style) {
238 rev->show_decorations = 1;
239 load_ref_decorations(&decoration_filter, decoration_style);
242 if (rev->line_level_traverse)
243 line_log_init(rev, line_cb.prefix, &line_cb.args);
245 setup_pager();
248 static void cmd_log_init(int argc, const char **argv, const char *prefix,
249 struct rev_info *rev, struct setup_revision_opt *opt)
251 cmd_log_init_defaults(rev);
252 cmd_log_init_finish(argc, argv, prefix, rev, opt);
256 * This gives a rough estimate for how many commits we
257 * will print out in the list.
259 static int estimate_commit_count(struct commit_list *list)
261 int n = 0;
263 while (list) {
264 struct commit *commit = list->item;
265 unsigned int flags = commit->object.flags;
266 list = list->next;
267 if (!(flags & (TREESAME | UNINTERESTING)))
268 n++;
270 return n;
273 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
275 if (rev->shown_one) {
276 rev->shown_one = 0;
277 if (rev->commit_format != CMIT_FMT_ONELINE)
278 putchar(rev->diffopt.line_termination);
280 fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
283 static struct itimerval early_output_timer;
285 static void log_show_early(struct rev_info *revs, struct commit_list *list)
287 int i = revs->early_output, close_file = revs->diffopt.close_file;
288 int show_header = 1;
290 revs->diffopt.close_file = 0;
291 sort_in_topological_order(&list, revs->sort_order);
292 while (list && i) {
293 struct commit *commit = list->item;
294 switch (simplify_commit(revs, commit)) {
295 case commit_show:
296 if (show_header) {
297 int n = estimate_commit_count(list);
298 show_early_header(revs, "incomplete", n);
299 show_header = 0;
301 log_tree_commit(revs, commit);
302 i--;
303 break;
304 case commit_ignore:
305 break;
306 case commit_error:
307 if (close_file)
308 fclose(revs->diffopt.file);
309 return;
311 list = list->next;
314 /* Did we already get enough commits for the early output? */
315 if (!i) {
316 if (close_file)
317 fclose(revs->diffopt.file);
318 return;
322 * ..if no, then repeat it twice a second until we
323 * do.
325 * NOTE! We don't use "it_interval", because if the
326 * reader isn't listening, we want our output to be
327 * throttled by the writing, and not have the timer
328 * trigger every second even if we're blocked on a
329 * reader!
331 early_output_timer.it_value.tv_sec = 0;
332 early_output_timer.it_value.tv_usec = 500000;
333 setitimer(ITIMER_REAL, &early_output_timer, NULL);
336 static void early_output(int signal)
338 show_early_output = log_show_early;
341 static void setup_early_output(void)
343 struct sigaction sa;
346 * Set up the signal handler, minimally intrusively:
347 * we only set a single volatile integer word (not
348 * using sigatomic_t - trying to avoid unnecessary
349 * system dependencies and headers), and using
350 * SA_RESTART.
352 memset(&sa, 0, sizeof(sa));
353 sa.sa_handler = early_output;
354 sigemptyset(&sa.sa_mask);
355 sa.sa_flags = SA_RESTART;
356 sigaction(SIGALRM, &sa, NULL);
359 * If we can get the whole output in less than a
360 * tenth of a second, don't even bother doing the
361 * early-output thing..
363 * This is a one-time-only trigger.
365 early_output_timer.it_value.tv_sec = 0;
366 early_output_timer.it_value.tv_usec = 100000;
367 setitimer(ITIMER_REAL, &early_output_timer, NULL);
370 static void finish_early_output(struct rev_info *rev)
372 int n = estimate_commit_count(rev->commits);
373 signal(SIGALRM, SIG_IGN);
374 show_early_header(rev, "done", n);
377 static int cmd_log_walk(struct rev_info *rev)
379 struct commit *commit;
380 int saved_nrl = 0;
381 int saved_dcctc = 0, close_file = rev->diffopt.close_file;
383 if (rev->early_output)
384 setup_early_output();
386 if (prepare_revision_walk(rev))
387 die(_("revision walk setup failed"));
389 if (rev->early_output)
390 finish_early_output(rev);
393 * For --check and --exit-code, the exit code is based on CHECK_FAILED
394 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
395 * retain that state information if replacing rev->diffopt in this loop
397 rev->diffopt.close_file = 0;
398 while ((commit = get_revision(rev)) != NULL) {
399 if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
401 * We decremented max_count in get_revision,
402 * but we didn't actually show the commit.
404 rev->max_count++;
405 if (!rev->reflog_info) {
407 * We may show a given commit multiple times when
408 * walking the reflogs.
410 free_commit_buffer(the_repository->parsed_objects,
411 commit);
412 free_commit_list(commit->parents);
413 commit->parents = NULL;
415 if (saved_nrl < rev->diffopt.needed_rename_limit)
416 saved_nrl = rev->diffopt.needed_rename_limit;
417 if (rev->diffopt.degraded_cc_to_c)
418 saved_dcctc = 1;
420 rev->diffopt.degraded_cc_to_c = saved_dcctc;
421 rev->diffopt.needed_rename_limit = saved_nrl;
422 if (close_file)
423 fclose(rev->diffopt.file);
425 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
426 rev->diffopt.flags.check_failed) {
427 return 02;
429 return diff_result_code(&rev->diffopt, 0);
432 static int git_log_config(const char *var, const char *value, void *cb)
434 const char *slot_name;
436 if (!strcmp(var, "format.pretty"))
437 return git_config_string(&fmt_pretty, var, value);
438 if (!strcmp(var, "format.subjectprefix"))
439 return git_config_string(&fmt_patch_subject_prefix, var, value);
440 if (!strcmp(var, "log.abbrevcommit")) {
441 default_abbrev_commit = git_config_bool(var, value);
442 return 0;
444 if (!strcmp(var, "log.date"))
445 return git_config_string(&default_date_mode, var, value);
446 if (!strcmp(var, "log.decorate")) {
447 decoration_style = parse_decoration_style(value);
448 if (decoration_style < 0)
449 decoration_style = 0; /* maybe warn? */
450 return 0;
452 if (!strcmp(var, "log.showroot")) {
453 default_show_root = git_config_bool(var, value);
454 return 0;
456 if (!strcmp(var, "log.follow")) {
457 default_follow = git_config_bool(var, value);
458 return 0;
460 if (skip_prefix(var, "color.decorate.", &slot_name))
461 return parse_decorate_color_config(var, slot_name, value);
462 if (!strcmp(var, "log.mailmap")) {
463 use_mailmap_config = git_config_bool(var, value);
464 return 0;
466 if (!strcmp(var, "log.showsignature")) {
467 default_show_signature = git_config_bool(var, value);
468 return 0;
471 if (grep_config(var, value, cb) < 0)
472 return -1;
473 if (git_gpg_config(var, value, cb) < 0)
474 return -1;
475 return git_diff_ui_config(var, value, cb);
478 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
480 struct rev_info rev;
481 struct setup_revision_opt opt;
483 init_log_defaults();
484 git_config(git_log_config, NULL);
486 repo_init_revisions(the_repository, &rev, prefix);
487 rev.diff = 1;
488 rev.simplify_history = 0;
489 memset(&opt, 0, sizeof(opt));
490 opt.def = "HEAD";
491 opt.revarg_opt = REVARG_COMMITTISH;
492 cmd_log_init(argc, argv, prefix, &rev, &opt);
493 if (!rev.diffopt.output_format)
494 rev.diffopt.output_format = DIFF_FORMAT_RAW;
495 return cmd_log_walk(&rev);
498 static void show_tagger(const char *buf, struct rev_info *rev)
500 struct strbuf out = STRBUF_INIT;
501 struct pretty_print_context pp = {0};
503 pp.fmt = rev->commit_format;
504 pp.date_mode = rev->date_mode;
505 pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
506 fprintf(rev->diffopt.file, "%s", out.buf);
507 strbuf_release(&out);
510 static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
512 struct object_id oidc;
513 struct object_context obj_context;
514 char *buf;
515 unsigned long size;
517 fflush(rev->diffopt.file);
518 if (!rev->diffopt.flags.textconv_set_via_cmdline ||
519 !rev->diffopt.flags.allow_textconv)
520 return stream_blob_to_fd(1, oid, NULL, 0);
522 if (get_oid_with_context(the_repository, obj_name,
523 GET_OID_RECORD_PATH,
524 &oidc, &obj_context))
525 die(_("not a valid object name %s"), obj_name);
526 if (!obj_context.path ||
527 !textconv_object(the_repository, obj_context.path,
528 obj_context.mode, &oidc, 1, &buf, &size)) {
529 free(obj_context.path);
530 return stream_blob_to_fd(1, oid, NULL, 0);
533 if (!buf)
534 die(_("git show %s: bad file"), obj_name);
536 write_or_die(1, buf, size);
537 free(obj_context.path);
538 return 0;
541 static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
543 unsigned long size;
544 enum object_type type;
545 char *buf = read_object_file(oid, &type, &size);
546 int offset = 0;
548 if (!buf)
549 return error(_("could not read object %s"), oid_to_hex(oid));
551 assert(type == OBJ_TAG);
552 while (offset < size && buf[offset] != '\n') {
553 int new_offset = offset + 1;
554 const char *ident;
555 while (new_offset < size && buf[new_offset++] != '\n')
556 ; /* do nothing */
557 if (skip_prefix(buf + offset, "tagger ", &ident))
558 show_tagger(ident, rev);
559 offset = new_offset;
562 if (offset < size)
563 fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
564 free(buf);
565 return 0;
568 static int show_tree_object(const struct object_id *oid,
569 struct strbuf *base,
570 const char *pathname, unsigned mode, int stage, void *context)
572 FILE *file = context;
573 fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
574 return 0;
577 static void show_setup_revisions_tweak(struct rev_info *rev,
578 struct setup_revision_opt *opt)
580 if (rev->ignore_merges) {
581 /* There was no "-m" on the command line */
582 rev->ignore_merges = 0;
583 if (!rev->first_parent_only && !rev->combine_merges) {
584 /* No "--first-parent", "-c", or "--cc" */
585 rev->combine_merges = 1;
586 rev->dense_combined_merges = 1;
589 if (!rev->diffopt.output_format)
590 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
593 int cmd_show(int argc, const char **argv, const char *prefix)
595 struct rev_info rev;
596 struct object_array_entry *objects;
597 struct setup_revision_opt opt;
598 struct pathspec match_all;
599 int i, count, ret = 0;
601 init_log_defaults();
602 git_config(git_log_config, NULL);
604 memset(&match_all, 0, sizeof(match_all));
605 repo_init_revisions(the_repository, &rev, prefix);
606 rev.diff = 1;
607 rev.always_show_header = 1;
608 rev.no_walk = REVISION_WALK_NO_WALK_SORTED;
609 rev.diffopt.stat_width = -1; /* Scale to real terminal size */
611 memset(&opt, 0, sizeof(opt));
612 opt.def = "HEAD";
613 opt.tweak = show_setup_revisions_tweak;
614 cmd_log_init(argc, argv, prefix, &rev, &opt);
616 if (!rev.no_walk)
617 return cmd_log_walk(&rev);
619 count = rev.pending.nr;
620 objects = rev.pending.objects;
621 for (i = 0; i < count && !ret; i++) {
622 struct object *o = objects[i].item;
623 const char *name = objects[i].name;
624 switch (o->type) {
625 case OBJ_BLOB:
626 ret = show_blob_object(&o->oid, &rev, name);
627 break;
628 case OBJ_TAG: {
629 struct tag *t = (struct tag *)o;
630 struct object_id *oid = get_tagged_oid(t);
632 if (rev.shown_one)
633 putchar('\n');
634 fprintf(rev.diffopt.file, "%stag %s%s\n",
635 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
636 t->tag,
637 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
638 ret = show_tag_object(&o->oid, &rev);
639 rev.shown_one = 1;
640 if (ret)
641 break;
642 o = parse_object(the_repository, oid);
643 if (!o)
644 ret = error(_("could not read object %s"),
645 oid_to_hex(oid));
646 objects[i].item = o;
647 i--;
648 break;
650 case OBJ_TREE:
651 if (rev.shown_one)
652 putchar('\n');
653 fprintf(rev.diffopt.file, "%stree %s%s\n\n",
654 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
655 name,
656 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
657 read_tree_recursive(the_repository, (struct tree *)o, "",
658 0, 0, &match_all, show_tree_object,
659 rev.diffopt.file);
660 rev.shown_one = 1;
661 break;
662 case OBJ_COMMIT:
663 rev.pending.nr = rev.pending.alloc = 0;
664 rev.pending.objects = NULL;
665 add_object_array(o, name, &rev.pending);
666 ret = cmd_log_walk(&rev);
667 break;
668 default:
669 ret = error(_("unknown type: %d"), o->type);
672 free(objects);
673 return ret;
677 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
679 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
681 struct rev_info rev;
682 struct setup_revision_opt opt;
684 init_log_defaults();
685 git_config(git_log_config, NULL);
687 repo_init_revisions(the_repository, &rev, prefix);
688 init_reflog_walk(&rev.reflog_info);
689 rev.verbose_header = 1;
690 memset(&opt, 0, sizeof(opt));
691 opt.def = "HEAD";
692 cmd_log_init_defaults(&rev);
693 rev.abbrev_commit = 1;
694 rev.commit_format = CMIT_FMT_ONELINE;
695 rev.use_terminator = 1;
696 rev.always_show_header = 1;
697 cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
699 return cmd_log_walk(&rev);
702 static void log_setup_revisions_tweak(struct rev_info *rev,
703 struct setup_revision_opt *opt)
705 if (rev->diffopt.flags.default_follow_renames &&
706 rev->prune_data.nr == 1)
707 rev->diffopt.flags.follow_renames = 1;
709 /* Turn --cc/-c into -p --cc/-c when -p was not given */
710 if (!rev->diffopt.output_format && rev->combine_merges)
711 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
713 /* Turn -m on when --cc/-c was given */
714 if (rev->combine_merges)
715 rev->ignore_merges = 0;
718 int cmd_log(int argc, const char **argv, const char *prefix)
720 struct rev_info rev;
721 struct setup_revision_opt opt;
723 init_log_defaults();
724 git_config(git_log_config, NULL);
726 repo_init_revisions(the_repository, &rev, prefix);
727 rev.always_show_header = 1;
728 memset(&opt, 0, sizeof(opt));
729 opt.def = "HEAD";
730 opt.revarg_opt = REVARG_COMMITTISH;
731 opt.tweak = log_setup_revisions_tweak;
732 cmd_log_init(argc, argv, prefix, &rev, &opt);
733 return cmd_log_walk(&rev);
736 /* format-patch */
738 static const char *fmt_patch_suffix = ".patch";
739 static int numbered = 0;
740 static int auto_number = 1;
742 static char *default_attach = NULL;
744 static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
745 static struct string_list extra_to = STRING_LIST_INIT_NODUP;
746 static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
748 static void add_header(const char *value)
750 struct string_list_item *item;
751 int len = strlen(value);
752 while (len && value[len - 1] == '\n')
753 len--;
755 if (!strncasecmp(value, "to: ", 4)) {
756 item = string_list_append(&extra_to, value + 4);
757 len -= 4;
758 } else if (!strncasecmp(value, "cc: ", 4)) {
759 item = string_list_append(&extra_cc, value + 4);
760 len -= 4;
761 } else {
762 item = string_list_append(&extra_hdr, value);
765 item->string[len] = '\0';
768 #define THREAD_SHALLOW 1
769 #define THREAD_DEEP 2
770 static int thread;
771 static int do_signoff;
772 static int base_auto;
773 static char *from;
774 static const char *signature = git_version_string;
775 static const char *signature_file;
776 static int config_cover_letter;
777 static const char *config_output_directory;
779 enum {
780 COVER_UNSET,
781 COVER_OFF,
782 COVER_ON,
783 COVER_AUTO
786 static int git_format_config(const char *var, const char *value, void *cb)
788 struct rev_info *rev = cb;
790 if (!strcmp(var, "format.headers")) {
791 if (!value)
792 die(_("format.headers without value"));
793 add_header(value);
794 return 0;
796 if (!strcmp(var, "format.suffix"))
797 return git_config_string(&fmt_patch_suffix, var, value);
798 if (!strcmp(var, "format.to")) {
799 if (!value)
800 return config_error_nonbool(var);
801 string_list_append(&extra_to, value);
802 return 0;
804 if (!strcmp(var, "format.cc")) {
805 if (!value)
806 return config_error_nonbool(var);
807 string_list_append(&extra_cc, value);
808 return 0;
810 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
811 !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
812 return 0;
814 if (!strcmp(var, "format.numbered")) {
815 if (value && !strcasecmp(value, "auto")) {
816 auto_number = 1;
817 return 0;
819 numbered = git_config_bool(var, value);
820 auto_number = auto_number && numbered;
821 return 0;
823 if (!strcmp(var, "format.attach")) {
824 if (value && *value)
825 default_attach = xstrdup(value);
826 else
827 default_attach = xstrdup(git_version_string);
828 return 0;
830 if (!strcmp(var, "format.thread")) {
831 if (value && !strcasecmp(value, "deep")) {
832 thread = THREAD_DEEP;
833 return 0;
835 if (value && !strcasecmp(value, "shallow")) {
836 thread = THREAD_SHALLOW;
837 return 0;
839 thread = git_config_bool(var, value) && THREAD_SHALLOW;
840 return 0;
842 if (!strcmp(var, "format.signoff")) {
843 do_signoff = git_config_bool(var, value);
844 return 0;
846 if (!strcmp(var, "format.signature"))
847 return git_config_string(&signature, var, value);
848 if (!strcmp(var, "format.signaturefile"))
849 return git_config_pathname(&signature_file, var, value);
850 if (!strcmp(var, "format.coverletter")) {
851 if (value && !strcasecmp(value, "auto")) {
852 config_cover_letter = COVER_AUTO;
853 return 0;
855 config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
856 return 0;
858 if (!strcmp(var, "format.outputdirectory"))
859 return git_config_string(&config_output_directory, var, value);
860 if (!strcmp(var, "format.useautobase")) {
861 base_auto = git_config_bool(var, value);
862 return 0;
864 if (!strcmp(var, "format.from")) {
865 int b = git_parse_maybe_bool(value);
866 free(from);
867 if (b < 0)
868 from = xstrdup(value);
869 else if (b)
870 from = xstrdup(git_committer_info(IDENT_NO_DATE));
871 else
872 from = NULL;
873 return 0;
875 if (!strcmp(var, "format.notes")) {
876 struct strbuf buf = STRBUF_INIT;
877 int b = git_parse_maybe_bool(value);
878 if (!b)
879 return 0;
880 rev->show_notes = 1;
881 if (b < 0) {
882 strbuf_addstr(&buf, value);
883 expand_notes_ref(&buf);
884 string_list_append(&rev->notes_opt.extra_notes_refs,
885 strbuf_detach(&buf, NULL));
886 } else {
887 rev->notes_opt.use_default_notes = 1;
889 return 0;
892 return git_log_config(var, value, cb);
895 static const char *output_directory = NULL;
896 static int outdir_offset;
898 static int open_next_file(struct commit *commit, const char *subject,
899 struct rev_info *rev, int quiet)
901 struct strbuf filename = STRBUF_INIT;
902 int suffix_len = strlen(rev->patch_suffix) + 1;
904 if (output_directory) {
905 strbuf_addstr(&filename, output_directory);
906 if (filename.len >=
907 PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len) {
908 strbuf_release(&filename);
909 return error(_("name of output directory is too long"));
911 strbuf_complete(&filename, '/');
914 if (rev->numbered_files)
915 strbuf_addf(&filename, "%d", rev->nr);
916 else if (commit)
917 fmt_output_commit(&filename, commit, rev);
918 else
919 fmt_output_subject(&filename, subject, rev);
921 if (!quiet)
922 printf("%s\n", filename.buf + outdir_offset);
924 if ((rev->diffopt.file = fopen(filename.buf, "w")) == NULL) {
925 error_errno(_("cannot open patch file %s"), filename.buf);
926 strbuf_release(&filename);
927 return -1;
930 strbuf_release(&filename);
931 return 0;
934 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
936 struct rev_info check_rev;
937 struct commit *commit, *c1, *c2;
938 struct object *o1, *o2;
939 unsigned flags1, flags2;
941 if (rev->pending.nr != 2)
942 die(_("need exactly one range"));
944 o1 = rev->pending.objects[0].item;
945 o2 = rev->pending.objects[1].item;
946 flags1 = o1->flags;
947 flags2 = o2->flags;
948 c1 = lookup_commit_reference(the_repository, &o1->oid);
949 c2 = lookup_commit_reference(the_repository, &o2->oid);
951 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
952 die(_("not a range"));
954 init_patch_ids(the_repository, ids);
956 /* given a range a..b get all patch ids for b..a */
957 repo_init_revisions(the_repository, &check_rev, rev->prefix);
958 check_rev.max_parents = 1;
959 o1->flags ^= UNINTERESTING;
960 o2->flags ^= UNINTERESTING;
961 add_pending_object(&check_rev, o1, "o1");
962 add_pending_object(&check_rev, o2, "o2");
963 if (prepare_revision_walk(&check_rev))
964 die(_("revision walk setup failed"));
966 while ((commit = get_revision(&check_rev)) != NULL) {
967 add_commit_patch_id(commit, ids);
970 /* reset for next revision walk */
971 clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
972 clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
973 o1->flags = flags1;
974 o2->flags = flags2;
977 static void gen_message_id(struct rev_info *info, char *base)
979 struct strbuf buf = STRBUF_INIT;
980 strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
981 (timestamp_t) time(NULL),
982 git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
983 info->message_id = strbuf_detach(&buf, NULL);
986 static void print_signature(FILE *file)
988 if (!signature || !*signature)
989 return;
991 fprintf(file, "-- \n%s", signature);
992 if (signature[strlen(signature)-1] != '\n')
993 putc('\n', file);
994 putc('\n', file);
997 static void add_branch_description(struct strbuf *buf, const char *branch_name)
999 struct strbuf desc = STRBUF_INIT;
1000 if (!branch_name || !*branch_name)
1001 return;
1002 read_branch_desc(&desc, branch_name);
1003 if (desc.len) {
1004 strbuf_addch(buf, '\n');
1005 strbuf_addbuf(buf, &desc);
1006 strbuf_addch(buf, '\n');
1008 strbuf_release(&desc);
1011 static char *find_branch_name(struct rev_info *rev)
1013 int i, positive = -1;
1014 struct object_id branch_oid;
1015 const struct object_id *tip_oid;
1016 const char *ref, *v;
1017 char *full_ref, *branch = NULL;
1019 for (i = 0; i < rev->cmdline.nr; i++) {
1020 if (rev->cmdline.rev[i].flags & UNINTERESTING)
1021 continue;
1022 if (positive < 0)
1023 positive = i;
1024 else
1025 return NULL;
1027 if (positive < 0)
1028 return NULL;
1029 ref = rev->cmdline.rev[positive].name;
1030 tip_oid = &rev->cmdline.rev[positive].item->oid;
1031 if (dwim_ref(ref, strlen(ref), &branch_oid, &full_ref) &&
1032 skip_prefix(full_ref, "refs/heads/", &v) &&
1033 oideq(tip_oid, &branch_oid))
1034 branch = xstrdup(v);
1035 free(full_ref);
1036 return branch;
1039 static void show_diffstat(struct rev_info *rev,
1040 struct commit *origin, struct commit *head)
1042 struct diff_options opts;
1044 memcpy(&opts, &rev->diffopt, sizeof(opts));
1045 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1046 diff_setup_done(&opts);
1048 diff_tree_oid(get_commit_tree_oid(origin),
1049 get_commit_tree_oid(head),
1050 "", &opts);
1051 diffcore_std(&opts);
1052 diff_flush(&opts);
1054 fprintf(rev->diffopt.file, "\n");
1057 static void make_cover_letter(struct rev_info *rev, int use_stdout,
1058 struct commit *origin,
1059 int nr, struct commit **list,
1060 const char *branch_name,
1061 int quiet)
1063 const char *committer;
1064 const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
1065 const char *msg;
1066 struct shortlog log;
1067 struct strbuf sb = STRBUF_INIT;
1068 int i;
1069 const char *encoding = "UTF-8";
1070 int need_8bit_cte = 0;
1071 struct pretty_print_context pp = {0};
1072 struct commit *head = list[0];
1074 if (!cmit_fmt_is_mail(rev->commit_format))
1075 die(_("cover letter needs email format"));
1077 committer = git_committer_info(0);
1079 if (!use_stdout &&
1080 open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1081 die(_("failed to create cover-letter file"));
1083 log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1085 for (i = 0; !need_8bit_cte && i < nr; i++) {
1086 const char *buf = get_commit_buffer(list[i], NULL);
1087 if (has_non_ascii(buf))
1088 need_8bit_cte = 1;
1089 unuse_commit_buffer(list[i], buf);
1092 if (!branch_name)
1093 branch_name = find_branch_name(rev);
1095 msg = body;
1096 pp.fmt = CMIT_FMT_EMAIL;
1097 pp.date_mode.type = DATE_RFC2822;
1098 pp.rev = rev;
1099 pp.print_email_subject = 1;
1100 pp_user_info(&pp, NULL, &sb, committer, encoding);
1101 pp_title_line(&pp, &msg, &sb, encoding, need_8bit_cte);
1102 pp_remainder(&pp, &msg, &sb, 0);
1103 add_branch_description(&sb, branch_name);
1104 fprintf(rev->diffopt.file, "%s\n", sb.buf);
1106 strbuf_release(&sb);
1108 shortlog_init(&log);
1109 log.wrap_lines = 1;
1110 log.wrap = MAIL_DEFAULT_WRAP;
1111 log.in1 = 2;
1112 log.in2 = 4;
1113 log.file = rev->diffopt.file;
1114 for (i = 0; i < nr; i++)
1115 shortlog_add_commit(&log, list[i]);
1117 shortlog_output(&log);
1119 /* We can only do diffstat with a unique reference point */
1120 if (origin)
1121 show_diffstat(rev, origin, head);
1123 if (rev->idiff_oid1) {
1124 fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1125 show_interdiff(rev, 0);
1128 if (rev->rdiff1) {
1130 * Pass minimum required diff-options to range-diff; others
1131 * can be added later if deemed desirable.
1133 struct diff_options opts;
1134 diff_setup(&opts);
1135 opts.file = rev->diffopt.file;
1136 opts.use_color = rev->diffopt.use_color;
1137 diff_setup_done(&opts);
1138 fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1139 show_range_diff(rev->rdiff1, rev->rdiff2,
1140 rev->creation_factor, 1, &opts);
1144 static const char *clean_message_id(const char *msg_id)
1146 char ch;
1147 const char *a, *z, *m;
1149 m = msg_id;
1150 while ((ch = *m) && (isspace(ch) || (ch == '<')))
1151 m++;
1152 a = m;
1153 z = NULL;
1154 while ((ch = *m)) {
1155 if (!isspace(ch) && (ch != '>'))
1156 z = m;
1157 m++;
1159 if (!z)
1160 die(_("insane in-reply-to: %s"), msg_id);
1161 if (++z == m)
1162 return a;
1163 return xmemdupz(a, z - a);
1166 static const char *set_outdir(const char *prefix, const char *output_directory)
1168 if (output_directory && is_absolute_path(output_directory))
1169 return output_directory;
1171 if (!prefix || !*prefix) {
1172 if (output_directory)
1173 return output_directory;
1174 /* The user did not explicitly ask for "./" */
1175 outdir_offset = 2;
1176 return "./";
1179 outdir_offset = strlen(prefix);
1180 if (!output_directory)
1181 return prefix;
1183 return prefix_filename(prefix, output_directory);
1186 static const char * const builtin_format_patch_usage[] = {
1187 N_("git format-patch [<options>] [<since> | <revision-range>]"),
1188 NULL
1191 static int keep_subject = 0;
1193 static int keep_callback(const struct option *opt, const char *arg, int unset)
1195 BUG_ON_OPT_NEG(unset);
1196 BUG_ON_OPT_ARG(arg);
1197 ((struct rev_info *)opt->value)->total = -1;
1198 keep_subject = 1;
1199 return 0;
1202 static int subject_prefix = 0;
1204 static int subject_prefix_callback(const struct option *opt, const char *arg,
1205 int unset)
1207 BUG_ON_OPT_NEG(unset);
1208 subject_prefix = 1;
1209 ((struct rev_info *)opt->value)->subject_prefix = arg;
1210 return 0;
1213 static int rfc_callback(const struct option *opt, const char *arg, int unset)
1215 BUG_ON_OPT_NEG(unset);
1216 BUG_ON_OPT_ARG(arg);
1217 return subject_prefix_callback(opt, "RFC PATCH", unset);
1220 static int numbered_cmdline_opt = 0;
1222 static int numbered_callback(const struct option *opt, const char *arg,
1223 int unset)
1225 BUG_ON_OPT_ARG(arg);
1226 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1227 if (unset)
1228 auto_number = 0;
1229 return 0;
1232 static int no_numbered_callback(const struct option *opt, const char *arg,
1233 int unset)
1235 BUG_ON_OPT_NEG(unset);
1236 return numbered_callback(opt, arg, 1);
1239 static int output_directory_callback(const struct option *opt, const char *arg,
1240 int unset)
1242 const char **dir = (const char **)opt->value;
1243 BUG_ON_OPT_NEG(unset);
1244 if (*dir)
1245 die(_("two output directories?"));
1246 *dir = arg;
1247 return 0;
1250 static int thread_callback(const struct option *opt, const char *arg, int unset)
1252 int *thread = (int *)opt->value;
1253 if (unset)
1254 *thread = 0;
1255 else if (!arg || !strcmp(arg, "shallow"))
1256 *thread = THREAD_SHALLOW;
1257 else if (!strcmp(arg, "deep"))
1258 *thread = THREAD_DEEP;
1260 * Please update _git_formatpatch() in git-completion.bash
1261 * when you add new options.
1263 else
1264 return 1;
1265 return 0;
1268 static int attach_callback(const struct option *opt, const char *arg, int unset)
1270 struct rev_info *rev = (struct rev_info *)opt->value;
1271 if (unset)
1272 rev->mime_boundary = NULL;
1273 else if (arg)
1274 rev->mime_boundary = arg;
1275 else
1276 rev->mime_boundary = git_version_string;
1277 rev->no_inline = unset ? 0 : 1;
1278 return 0;
1281 static int inline_callback(const struct option *opt, const char *arg, int unset)
1283 struct rev_info *rev = (struct rev_info *)opt->value;
1284 if (unset)
1285 rev->mime_boundary = NULL;
1286 else if (arg)
1287 rev->mime_boundary = arg;
1288 else
1289 rev->mime_boundary = git_version_string;
1290 rev->no_inline = 0;
1291 return 0;
1294 static int header_callback(const struct option *opt, const char *arg, int unset)
1296 if (unset) {
1297 string_list_clear(&extra_hdr, 0);
1298 string_list_clear(&extra_to, 0);
1299 string_list_clear(&extra_cc, 0);
1300 } else {
1301 add_header(arg);
1303 return 0;
1306 static int to_callback(const struct option *opt, const char *arg, int unset)
1308 if (unset)
1309 string_list_clear(&extra_to, 0);
1310 else
1311 string_list_append(&extra_to, arg);
1312 return 0;
1315 static int cc_callback(const struct option *opt, const char *arg, int unset)
1317 if (unset)
1318 string_list_clear(&extra_cc, 0);
1319 else
1320 string_list_append(&extra_cc, arg);
1321 return 0;
1324 static int from_callback(const struct option *opt, const char *arg, int unset)
1326 char **from = opt->value;
1328 free(*from);
1330 if (unset)
1331 *from = NULL;
1332 else if (arg)
1333 *from = xstrdup(arg);
1334 else
1335 *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1336 return 0;
1339 struct base_tree_info {
1340 struct object_id base_commit;
1341 int nr_patch_id, alloc_patch_id;
1342 struct object_id *patch_id;
1345 static struct commit *get_base_commit(const char *base_commit,
1346 struct commit **list,
1347 int total)
1349 struct commit *base = NULL;
1350 struct commit **rev;
1351 int i = 0, rev_nr = 0;
1353 if (base_commit && strcmp(base_commit, "auto")) {
1354 base = lookup_commit_reference_by_name(base_commit);
1355 if (!base)
1356 die(_("unknown commit %s"), base_commit);
1357 } else if ((base_commit && !strcmp(base_commit, "auto")) || base_auto) {
1358 struct branch *curr_branch = branch_get(NULL);
1359 const char *upstream = branch_get_upstream(curr_branch, NULL);
1360 if (upstream) {
1361 struct commit_list *base_list;
1362 struct commit *commit;
1363 struct object_id oid;
1365 if (get_oid(upstream, &oid))
1366 die(_("failed to resolve '%s' as a valid ref"), upstream);
1367 commit = lookup_commit_or_die(&oid, "upstream base");
1368 base_list = get_merge_bases_many(commit, total, list);
1369 /* There should be one and only one merge base. */
1370 if (!base_list || base_list->next)
1371 die(_("could not find exact merge base"));
1372 base = base_list->item;
1373 free_commit_list(base_list);
1374 } else {
1375 die(_("failed to get upstream, if you want to record base commit automatically,\n"
1376 "please use git branch --set-upstream-to to track a remote branch.\n"
1377 "Or you could specify base commit by --base=<base-commit-id> manually"));
1381 ALLOC_ARRAY(rev, total);
1382 for (i = 0; i < total; i++)
1383 rev[i] = list[i];
1385 rev_nr = total;
1387 * Get merge base through pair-wise computations
1388 * and store it in rev[0].
1390 while (rev_nr > 1) {
1391 for (i = 0; i < rev_nr / 2; i++) {
1392 struct commit_list *merge_base;
1393 merge_base = get_merge_bases(rev[2 * i], rev[2 * i + 1]);
1394 if (!merge_base || merge_base->next)
1395 die(_("failed to find exact merge base"));
1397 rev[i] = merge_base->item;
1400 if (rev_nr % 2)
1401 rev[i] = rev[2 * i];
1402 rev_nr = DIV_ROUND_UP(rev_nr, 2);
1405 if (!in_merge_bases(base, rev[0]))
1406 die(_("base commit should be the ancestor of revision list"));
1408 for (i = 0; i < total; i++) {
1409 if (base == list[i])
1410 die(_("base commit shouldn't be in revision list"));
1413 free(rev);
1414 return base;
1417 define_commit_slab(commit_base, int);
1419 static void prepare_bases(struct base_tree_info *bases,
1420 struct commit *base,
1421 struct commit **list,
1422 int total)
1424 struct commit *commit;
1425 struct rev_info revs;
1426 struct diff_options diffopt;
1427 struct commit_base commit_base;
1428 int i;
1430 if (!base)
1431 return;
1433 init_commit_base(&commit_base);
1434 repo_diff_setup(the_repository, &diffopt);
1435 diffopt.flags.recursive = 1;
1436 diff_setup_done(&diffopt);
1438 oidcpy(&bases->base_commit, &base->object.oid);
1440 repo_init_revisions(the_repository, &revs, NULL);
1441 revs.max_parents = 1;
1442 revs.topo_order = 1;
1443 for (i = 0; i < total; i++) {
1444 list[i]->object.flags &= ~UNINTERESTING;
1445 add_pending_object(&revs, &list[i]->object, "rev_list");
1446 *commit_base_at(&commit_base, list[i]) = 1;
1448 base->object.flags |= UNINTERESTING;
1449 add_pending_object(&revs, &base->object, "base");
1451 if (prepare_revision_walk(&revs))
1452 die(_("revision walk setup failed"));
1454 * Traverse the commits list, get prerequisite patch ids
1455 * and stuff them in bases structure.
1457 while ((commit = get_revision(&revs)) != NULL) {
1458 struct object_id oid;
1459 struct object_id *patch_id;
1460 if (*commit_base_at(&commit_base, commit))
1461 continue;
1462 if (commit_patch_id(commit, &diffopt, &oid, 0, 1))
1463 die(_("cannot get patch id"));
1464 ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1465 patch_id = bases->patch_id + bases->nr_patch_id;
1466 oidcpy(patch_id, &oid);
1467 bases->nr_patch_id++;
1469 clear_commit_base(&commit_base);
1472 static void print_bases(struct base_tree_info *bases, FILE *file)
1474 int i;
1476 /* Only do this once, either for the cover or for the first one */
1477 if (is_null_oid(&bases->base_commit))
1478 return;
1480 /* Show the base commit */
1481 fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1483 /* Show the prerequisite patches */
1484 for (i = bases->nr_patch_id - 1; i >= 0; i--)
1485 fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1487 free(bases->patch_id);
1488 bases->nr_patch_id = 0;
1489 bases->alloc_patch_id = 0;
1490 oidclr(&bases->base_commit);
1493 static const char *diff_title(struct strbuf *sb, int reroll_count,
1494 const char *generic, const char *rerolled)
1496 if (reroll_count <= 0)
1497 strbuf_addstr(sb, generic);
1498 else /* RFC may be v0, so allow -v1 to diff against v0 */
1499 strbuf_addf(sb, rerolled, reroll_count - 1);
1500 return sb->buf;
1503 static void infer_range_diff_ranges(struct strbuf *r1,
1504 struct strbuf *r2,
1505 const char *prev,
1506 struct commit *origin,
1507 struct commit *head)
1509 const char *head_oid = oid_to_hex(&head->object.oid);
1511 if (!strstr(prev, "..")) {
1512 strbuf_addf(r1, "%s..%s", head_oid, prev);
1513 strbuf_addf(r2, "%s..%s", prev, head_oid);
1514 } else if (!origin) {
1515 die(_("failed to infer range-diff ranges"));
1516 } else {
1517 strbuf_addstr(r1, prev);
1518 strbuf_addf(r2, "%s..%s",
1519 oid_to_hex(&origin->object.oid), head_oid);
1523 int cmd_format_patch(int argc, const char **argv, const char *prefix)
1525 struct commit *commit;
1526 struct commit **list = NULL;
1527 struct rev_info rev;
1528 struct setup_revision_opt s_r_opt;
1529 int nr = 0, total, i;
1530 int use_stdout = 0;
1531 int start_number = -1;
1532 int just_numbers = 0;
1533 int ignore_if_in_upstream = 0;
1534 int cover_letter = -1;
1535 int boundary_count = 0;
1536 int no_binary_diff = 0;
1537 int zero_commit = 0;
1538 struct commit *origin = NULL;
1539 const char *in_reply_to = NULL;
1540 struct patch_ids ids;
1541 struct strbuf buf = STRBUF_INIT;
1542 int use_patch_format = 0;
1543 int quiet = 0;
1544 int reroll_count = -1;
1545 char *branch_name = NULL;
1546 char *base_commit = NULL;
1547 struct base_tree_info bases;
1548 int show_progress = 0;
1549 struct progress *progress = NULL;
1550 struct oid_array idiff_prev = OID_ARRAY_INIT;
1551 struct strbuf idiff_title = STRBUF_INIT;
1552 const char *rdiff_prev = NULL;
1553 struct strbuf rdiff1 = STRBUF_INIT;
1554 struct strbuf rdiff2 = STRBUF_INIT;
1555 struct strbuf rdiff_title = STRBUF_INIT;
1556 int creation_factor = -1;
1558 const struct option builtin_format_patch_options[] = {
1559 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
1560 N_("use [PATCH n/m] even with a single patch"),
1561 PARSE_OPT_NOARG, numbered_callback },
1562 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
1563 N_("use [PATCH] even with multiple patches"),
1564 PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback },
1565 OPT_BOOL('s', "signoff", &do_signoff, N_("add Signed-off-by:")),
1566 OPT_BOOL(0, "stdout", &use_stdout,
1567 N_("print patches to standard out")),
1568 OPT_BOOL(0, "cover-letter", &cover_letter,
1569 N_("generate a cover letter")),
1570 OPT_BOOL(0, "numbered-files", &just_numbers,
1571 N_("use simple number sequence for output file names")),
1572 OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
1573 N_("use <sfx> instead of '.patch'")),
1574 OPT_INTEGER(0, "start-number", &start_number,
1575 N_("start numbering patches at <n> instead of 1")),
1576 OPT_INTEGER('v', "reroll-count", &reroll_count,
1577 N_("mark the series as Nth re-roll")),
1578 { OPTION_CALLBACK, 0, "rfc", &rev, NULL,
1579 N_("Use [RFC PATCH] instead of [PATCH]"),
1580 PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback },
1581 { OPTION_CALLBACK, 0, "subject-prefix", &rev, N_("prefix"),
1582 N_("Use [<prefix>] instead of [PATCH]"),
1583 PARSE_OPT_NONEG, subject_prefix_callback },
1584 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
1585 N_("dir"), N_("store resulting files in <dir>"),
1586 PARSE_OPT_NONEG, output_directory_callback },
1587 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
1588 N_("don't strip/add [PATCH]"),
1589 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
1590 OPT_BOOL(0, "no-binary", &no_binary_diff,
1591 N_("don't output binary diffs")),
1592 OPT_BOOL(0, "zero-commit", &zero_commit,
1593 N_("output all-zero hash in From header")),
1594 OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1595 N_("don't include a patch matching a commit upstream")),
1596 OPT_SET_INT_F('p', "no-stat", &use_patch_format,
1597 N_("show patch format instead of default (patch + stat)"),
1598 1, PARSE_OPT_NONEG),
1599 OPT_GROUP(N_("Messaging")),
1600 { OPTION_CALLBACK, 0, "add-header", NULL, N_("header"),
1601 N_("add email header"), 0, header_callback },
1602 { OPTION_CALLBACK, 0, "to", NULL, N_("email"), N_("add To: header"),
1603 0, to_callback },
1604 { OPTION_CALLBACK, 0, "cc", NULL, N_("email"), N_("add Cc: header"),
1605 0, cc_callback },
1606 { OPTION_CALLBACK, 0, "from", &from, N_("ident"),
1607 N_("set From address to <ident> (or committer ident if absent)"),
1608 PARSE_OPT_OPTARG, from_callback },
1609 OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
1610 N_("make first mail a reply to <message-id>")),
1611 { OPTION_CALLBACK, 0, "attach", &rev, N_("boundary"),
1612 N_("attach the patch"), PARSE_OPT_OPTARG,
1613 attach_callback },
1614 { OPTION_CALLBACK, 0, "inline", &rev, N_("boundary"),
1615 N_("inline the patch"),
1616 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1617 inline_callback },
1618 { OPTION_CALLBACK, 0, "thread", &thread, N_("style"),
1619 N_("enable message threading, styles: shallow, deep"),
1620 PARSE_OPT_OPTARG, thread_callback },
1621 OPT_STRING(0, "signature", &signature, N_("signature"),
1622 N_("add a signature")),
1623 OPT_STRING(0, "base", &base_commit, N_("base-commit"),
1624 N_("add prerequisite tree info to the patch series")),
1625 OPT_FILENAME(0, "signature-file", &signature_file,
1626 N_("add a signature from a file")),
1627 OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1628 OPT_BOOL(0, "progress", &show_progress,
1629 N_("show progress while generating patches")),
1630 OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
1631 N_("show changes against <rev> in cover letter or single patch"),
1632 parse_opt_object_name),
1633 OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
1634 N_("show changes against <refspec> in cover letter or single patch")),
1635 OPT_INTEGER(0, "creation-factor", &creation_factor,
1636 N_("percentage by which creation is weighted")),
1637 OPT_END()
1640 extra_hdr.strdup_strings = 1;
1641 extra_to.strdup_strings = 1;
1642 extra_cc.strdup_strings = 1;
1643 init_log_defaults();
1644 repo_init_revisions(the_repository, &rev, prefix);
1645 git_config(git_format_config, &rev);
1646 rev.commit_format = CMIT_FMT_EMAIL;
1647 rev.expand_tabs_in_log_default = 0;
1648 rev.verbose_header = 1;
1649 rev.diff = 1;
1650 rev.max_parents = 1;
1651 rev.diffopt.flags.recursive = 1;
1652 rev.subject_prefix = fmt_patch_subject_prefix;
1653 memset(&s_r_opt, 0, sizeof(s_r_opt));
1654 s_r_opt.def = "HEAD";
1655 s_r_opt.revarg_opt = REVARG_COMMITTISH;
1657 if (default_attach) {
1658 rev.mime_boundary = default_attach;
1659 rev.no_inline = 1;
1663 * Parse the arguments before setup_revisions(), or something
1664 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1665 * possibly a valid SHA1.
1667 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1668 builtin_format_patch_usage,
1669 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1670 PARSE_OPT_KEEP_DASHDASH);
1672 if (0 < reroll_count) {
1673 struct strbuf sprefix = STRBUF_INIT;
1674 strbuf_addf(&sprefix, "%s v%d",
1675 rev.subject_prefix, reroll_count);
1676 rev.reroll_count = reroll_count;
1677 rev.subject_prefix = strbuf_detach(&sprefix, NULL);
1680 for (i = 0; i < extra_hdr.nr; i++) {
1681 strbuf_addstr(&buf, extra_hdr.items[i].string);
1682 strbuf_addch(&buf, '\n');
1685 if (extra_to.nr)
1686 strbuf_addstr(&buf, "To: ");
1687 for (i = 0; i < extra_to.nr; i++) {
1688 if (i)
1689 strbuf_addstr(&buf, " ");
1690 strbuf_addstr(&buf, extra_to.items[i].string);
1691 if (i + 1 < extra_to.nr)
1692 strbuf_addch(&buf, ',');
1693 strbuf_addch(&buf, '\n');
1696 if (extra_cc.nr)
1697 strbuf_addstr(&buf, "Cc: ");
1698 for (i = 0; i < extra_cc.nr; i++) {
1699 if (i)
1700 strbuf_addstr(&buf, " ");
1701 strbuf_addstr(&buf, extra_cc.items[i].string);
1702 if (i + 1 < extra_cc.nr)
1703 strbuf_addch(&buf, ',');
1704 strbuf_addch(&buf, '\n');
1707 rev.extra_headers = strbuf_detach(&buf, NULL);
1709 if (from) {
1710 if (split_ident_line(&rev.from_ident, from, strlen(from)))
1711 die(_("invalid ident line: %s"), from);
1714 if (start_number < 0)
1715 start_number = 1;
1718 * If numbered is set solely due to format.numbered in config,
1719 * and it would conflict with --keep-subject (-k) from the
1720 * command line, reset "numbered".
1722 if (numbered && keep_subject && !numbered_cmdline_opt)
1723 numbered = 0;
1725 if (numbered && keep_subject)
1726 die(_("-n and -k are mutually exclusive"));
1727 if (keep_subject && subject_prefix)
1728 die(_("--subject-prefix/--rfc and -k are mutually exclusive"));
1729 rev.preserve_subject = keep_subject;
1731 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1732 if (argc > 1)
1733 die(_("unrecognized argument: %s"), argv[1]);
1735 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1736 die(_("--name-only does not make sense"));
1737 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1738 die(_("--name-status does not make sense"));
1739 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1740 die(_("--check does not make sense"));
1742 if (!use_patch_format &&
1743 (!rev.diffopt.output_format ||
1744 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1745 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1746 if (!rev.diffopt.stat_width)
1747 rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
1749 /* Always generate a patch */
1750 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1752 rev.zero_commit = zero_commit;
1754 if (!rev.diffopt.flags.text && !no_binary_diff)
1755 rev.diffopt.flags.binary = 1;
1757 if (rev.show_notes)
1758 init_display_notes(&rev.notes_opt);
1760 if (!output_directory && !use_stdout)
1761 output_directory = config_output_directory;
1763 if (!use_stdout)
1764 output_directory = set_outdir(prefix, output_directory);
1765 else
1766 setup_pager();
1768 if (output_directory) {
1769 if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
1770 rev.diffopt.use_color = GIT_COLOR_NEVER;
1771 if (use_stdout)
1772 die(_("standard output, or directory, which one?"));
1773 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1774 die_errno(_("could not create directory '%s'"),
1775 output_directory);
1778 if (rev.pending.nr == 1) {
1779 int check_head = 0;
1781 if (rev.max_count < 0 && !rev.show_root_diff) {
1783 * This is traditional behaviour of "git format-patch
1784 * origin" that prepares what the origin side still
1785 * does not have.
1787 rev.pending.objects[0].item->flags |= UNINTERESTING;
1788 add_head_to_pending(&rev);
1789 check_head = 1;
1792 * Otherwise, it is "format-patch -22 HEAD", and/or
1793 * "format-patch --root HEAD". The user wants
1794 * get_revision() to do the usual traversal.
1797 if (!strcmp(rev.pending.objects[0].name, "HEAD"))
1798 check_head = 1;
1800 if (check_head) {
1801 const char *ref, *v;
1802 ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1803 NULL, NULL);
1804 if (ref && skip_prefix(ref, "refs/heads/", &v))
1805 branch_name = xstrdup(v);
1806 else
1807 branch_name = xstrdup(""); /* no branch */
1812 * We cannot move this anywhere earlier because we do want to
1813 * know if --root was given explicitly from the command line.
1815 rev.show_root_diff = 1;
1817 if (ignore_if_in_upstream) {
1818 /* Don't say anything if head and upstream are the same. */
1819 if (rev.pending.nr == 2) {
1820 struct object_array_entry *o = rev.pending.objects;
1821 if (oideq(&o[0].item->oid, &o[1].item->oid))
1822 goto done;
1824 get_patch_ids(&rev, &ids);
1827 if (prepare_revision_walk(&rev))
1828 die(_("revision walk setup failed"));
1829 rev.boundary = 1;
1830 while ((commit = get_revision(&rev)) != NULL) {
1831 if (commit->object.flags & BOUNDARY) {
1832 boundary_count++;
1833 origin = (boundary_count == 1) ? commit : NULL;
1834 continue;
1837 if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
1838 continue;
1840 nr++;
1841 REALLOC_ARRAY(list, nr);
1842 list[nr - 1] = commit;
1844 if (nr == 0)
1845 /* nothing to do */
1846 goto done;
1847 total = nr;
1848 if (cover_letter == -1) {
1849 if (config_cover_letter == COVER_AUTO)
1850 cover_letter = (total > 1);
1851 else
1852 cover_letter = (config_cover_letter == COVER_ON);
1854 if (!keep_subject && auto_number && (total > 1 || cover_letter))
1855 numbered = 1;
1856 if (numbered)
1857 rev.total = total + start_number - 1;
1859 if (idiff_prev.nr) {
1860 if (!cover_letter && total != 1)
1861 die(_("--interdiff requires --cover-letter or single patch"));
1862 rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
1863 rev.idiff_oid2 = get_commit_tree_oid(list[0]);
1864 rev.idiff_title = diff_title(&idiff_title, reroll_count,
1865 _("Interdiff:"),
1866 _("Interdiff against v%d:"));
1869 if (creation_factor < 0)
1870 creation_factor = RANGE_DIFF_CREATION_FACTOR_DEFAULT;
1871 else if (!rdiff_prev)
1872 die(_("--creation-factor requires --range-diff"));
1874 if (rdiff_prev) {
1875 if (!cover_letter && total != 1)
1876 die(_("--range-diff requires --cover-letter or single patch"));
1878 infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
1879 origin, list[0]);
1880 rev.rdiff1 = rdiff1.buf;
1881 rev.rdiff2 = rdiff2.buf;
1882 rev.creation_factor = creation_factor;
1883 rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
1884 _("Range-diff:"),
1885 _("Range-diff against v%d:"));
1888 if (!signature) {
1889 ; /* --no-signature inhibits all signatures */
1890 } else if (signature && signature != git_version_string) {
1891 ; /* non-default signature already set */
1892 } else if (signature_file) {
1893 struct strbuf buf = STRBUF_INIT;
1895 if (strbuf_read_file(&buf, signature_file, 128) < 0)
1896 die_errno(_("unable to read signature file '%s'"), signature_file);
1897 signature = strbuf_detach(&buf, NULL);
1900 memset(&bases, 0, sizeof(bases));
1901 if (base_commit || base_auto) {
1902 struct commit *base = get_base_commit(base_commit, list, nr);
1903 reset_revision_walk();
1904 clear_object_flags(UNINTERESTING);
1905 prepare_bases(&bases, base, list, nr);
1908 if (in_reply_to || thread || cover_letter)
1909 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1910 if (in_reply_to) {
1911 const char *msgid = clean_message_id(in_reply_to);
1912 string_list_append(rev.ref_message_ids, msgid);
1914 rev.numbered_files = just_numbers;
1915 rev.patch_suffix = fmt_patch_suffix;
1916 if (cover_letter) {
1917 if (thread)
1918 gen_message_id(&rev, "cover");
1919 make_cover_letter(&rev, use_stdout,
1920 origin, nr, list, branch_name, quiet);
1921 print_bases(&bases, rev.diffopt.file);
1922 print_signature(rev.diffopt.file);
1923 total++;
1924 start_number--;
1925 /* interdiff/range-diff in cover-letter; omit from patches */
1926 rev.idiff_oid1 = NULL;
1927 rev.rdiff1 = NULL;
1929 rev.add_signoff = do_signoff;
1931 if (show_progress)
1932 progress = start_delayed_progress(_("Generating patches"), total);
1933 while (0 <= --nr) {
1934 int shown;
1935 display_progress(progress, total - nr);
1936 commit = list[nr];
1937 rev.nr = total - nr + (start_number - 1);
1938 /* Make the second and subsequent mails replies to the first */
1939 if (thread) {
1940 /* Have we already had a message ID? */
1941 if (rev.message_id) {
1943 * For deep threading: make every mail
1944 * a reply to the previous one, no
1945 * matter what other options are set.
1947 * For shallow threading:
1949 * Without --cover-letter and
1950 * --in-reply-to, make every mail a
1951 * reply to the one before.
1953 * With --in-reply-to but no
1954 * --cover-letter, make every mail a
1955 * reply to the <reply-to>.
1957 * With --cover-letter, make every
1958 * mail but the cover letter a reply
1959 * to the cover letter. The cover
1960 * letter is a reply to the
1961 * --in-reply-to, if specified.
1963 if (thread == THREAD_SHALLOW
1964 && rev.ref_message_ids->nr > 0
1965 && (!cover_letter || rev.nr > 1))
1966 free(rev.message_id);
1967 else
1968 string_list_append(rev.ref_message_ids,
1969 rev.message_id);
1971 gen_message_id(&rev, oid_to_hex(&commit->object.oid));
1974 if (!use_stdout &&
1975 open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
1976 die(_("failed to create output files"));
1977 shown = log_tree_commit(&rev, commit);
1978 free_commit_buffer(the_repository->parsed_objects,
1979 commit);
1981 /* We put one extra blank line between formatted
1982 * patches and this flag is used by log-tree code
1983 * to see if it needs to emit a LF before showing
1984 * the log; when using one file per patch, we do
1985 * not want the extra blank line.
1987 if (!use_stdout)
1988 rev.shown_one = 0;
1989 if (shown) {
1990 print_bases(&bases, rev.diffopt.file);
1991 if (rev.mime_boundary)
1992 fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
1993 mime_boundary_leader,
1994 rev.mime_boundary);
1995 else
1996 print_signature(rev.diffopt.file);
1998 if (!use_stdout)
1999 fclose(rev.diffopt.file);
2001 stop_progress(&progress);
2002 free(list);
2003 free(branch_name);
2004 string_list_clear(&extra_to, 0);
2005 string_list_clear(&extra_cc, 0);
2006 string_list_clear(&extra_hdr, 0);
2007 if (ignore_if_in_upstream)
2008 free_patch_ids(&ids);
2010 done:
2011 oid_array_clear(&idiff_prev);
2012 strbuf_release(&idiff_title);
2013 strbuf_release(&rdiff1);
2014 strbuf_release(&rdiff2);
2015 strbuf_release(&rdiff_title);
2016 return 0;
2019 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
2021 struct object_id oid;
2022 if (get_oid(arg, &oid) == 0) {
2023 struct commit *commit = lookup_commit_reference(the_repository,
2024 &oid);
2025 if (commit) {
2026 commit->object.flags |= flags;
2027 add_pending_object(revs, &commit->object, arg);
2028 return 0;
2031 return -1;
2034 static const char * const cherry_usage[] = {
2035 N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
2036 NULL
2039 static void print_commit(char sign, struct commit *commit, int verbose,
2040 int abbrev, FILE *file)
2042 if (!verbose) {
2043 fprintf(file, "%c %s\n", sign,
2044 find_unique_abbrev(&commit->object.oid, abbrev));
2045 } else {
2046 struct strbuf buf = STRBUF_INIT;
2047 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2048 fprintf(file, "%c %s %s\n", sign,
2049 find_unique_abbrev(&commit->object.oid, abbrev),
2050 buf.buf);
2051 strbuf_release(&buf);
2055 int cmd_cherry(int argc, const char **argv, const char *prefix)
2057 struct rev_info revs;
2058 struct patch_ids ids;
2059 struct commit *commit;
2060 struct commit_list *list = NULL;
2061 struct branch *current_branch;
2062 const char *upstream;
2063 const char *head = "HEAD";
2064 const char *limit = NULL;
2065 int verbose = 0, abbrev = 0;
2067 struct option options[] = {
2068 OPT__ABBREV(&abbrev),
2069 OPT__VERBOSE(&verbose, N_("be verbose")),
2070 OPT_END()
2073 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
2075 switch (argc) {
2076 case 3:
2077 limit = argv[2];
2078 /* FALLTHROUGH */
2079 case 2:
2080 head = argv[1];
2081 /* FALLTHROUGH */
2082 case 1:
2083 upstream = argv[0];
2084 break;
2085 default:
2086 current_branch = branch_get(NULL);
2087 upstream = branch_get_upstream(current_branch, NULL);
2088 if (!upstream) {
2089 fprintf(stderr, _("Could not find a tracked"
2090 " remote branch, please"
2091 " specify <upstream> manually.\n"));
2092 usage_with_options(cherry_usage, options);
2096 repo_init_revisions(the_repository, &revs, prefix);
2097 revs.max_parents = 1;
2099 if (add_pending_commit(head, &revs, 0))
2100 die(_("unknown commit %s"), head);
2101 if (add_pending_commit(upstream, &revs, UNINTERESTING))
2102 die(_("unknown commit %s"), upstream);
2104 /* Don't say anything if head and upstream are the same. */
2105 if (revs.pending.nr == 2) {
2106 struct object_array_entry *o = revs.pending.objects;
2107 if (oideq(&o[0].item->oid, &o[1].item->oid))
2108 return 0;
2111 get_patch_ids(&revs, &ids);
2113 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2114 die(_("unknown commit %s"), limit);
2116 /* reverse the list of commits */
2117 if (prepare_revision_walk(&revs))
2118 die(_("revision walk setup failed"));
2119 while ((commit = get_revision(&revs)) != NULL) {
2120 commit_list_insert(commit, &list);
2123 while (list) {
2124 char sign = '+';
2126 commit = list->item;
2127 if (has_commit_patch_id(commit, &ids))
2128 sign = '-';
2129 print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2130 list = list->next;
2133 free_patch_ids(&ids);
2134 return 0;