midx: allow marking a pack as preferred
[git/debian.git] / builtin / log.c
blobf67b67d80ed1e8d7cd95982a8da96b435b8a452b
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 "diff-merges.h"
16 #include "revision.h"
17 #include "log-tree.h"
18 #include "builtin.h"
19 #include "tag.h"
20 #include "reflog-walk.h"
21 #include "patch-ids.h"
22 #include "run-command.h"
23 #include "shortlog.h"
24 #include "remote.h"
25 #include "string-list.h"
26 #include "parse-options.h"
27 #include "line-log.h"
28 #include "branch.h"
29 #include "streaming.h"
30 #include "version.h"
31 #include "mailmap.h"
32 #include "gpg-interface.h"
33 #include "progress.h"
34 #include "commit-slab.h"
35 #include "repository.h"
36 #include "commit-reach.h"
37 #include "range-diff.h"
39 #define MAIL_DEFAULT_WRAP 72
40 #define COVER_FROM_AUTO_MAX_SUBJECT_LEN 100
41 #define FORMAT_PATCH_NAME_MAX_DEFAULT 64
43 /* Set a default date-time format for git log ("log.date" config variable) */
44 static const char *default_date_mode = NULL;
46 static int default_abbrev_commit;
47 static int default_show_root = 1;
48 static int default_follow;
49 static int default_show_signature;
50 static int default_encode_email_headers = 1;
51 static int decoration_style;
52 static int decoration_given;
53 static int use_mailmap_config = 1;
54 static const char *fmt_patch_subject_prefix = "PATCH";
55 static int fmt_patch_name_max = FORMAT_PATCH_NAME_MAX_DEFAULT;
56 static const char *fmt_pretty;
58 static const char * const builtin_log_usage[] = {
59 N_("git log [<options>] [<revision-range>] [[--] <path>...]"),
60 N_("git show [<options>] <object>..."),
61 NULL
64 struct line_opt_callback_data {
65 struct rev_info *rev;
66 const char *prefix;
67 struct string_list args;
70 static int session_is_interactive(void)
72 return isatty(1) || pager_in_use();
75 static int auto_decoration_style(void)
77 return session_is_interactive() ? DECORATE_SHORT_REFS : 0;
80 static int parse_decoration_style(const char *value)
82 switch (git_parse_maybe_bool(value)) {
83 case 1:
84 return DECORATE_SHORT_REFS;
85 case 0:
86 return 0;
87 default:
88 break;
90 if (!strcmp(value, "full"))
91 return DECORATE_FULL_REFS;
92 else if (!strcmp(value, "short"))
93 return DECORATE_SHORT_REFS;
94 else if (!strcmp(value, "auto"))
95 return auto_decoration_style();
97 * Please update _git_log() in git-completion.bash when you
98 * add new decoration styles.
100 return -1;
103 static int decorate_callback(const struct option *opt, const char *arg, int unset)
105 if (unset)
106 decoration_style = 0;
107 else if (arg)
108 decoration_style = parse_decoration_style(arg);
109 else
110 decoration_style = DECORATE_SHORT_REFS;
112 if (decoration_style < 0)
113 die(_("invalid --decorate option: %s"), arg);
115 decoration_given = 1;
117 return 0;
120 static int log_line_range_callback(const struct option *option, const char *arg, int unset)
122 struct line_opt_callback_data *data = option->value;
124 BUG_ON_OPT_NEG(unset);
126 if (!arg)
127 return -1;
129 data->rev->line_level_traverse = 1;
130 string_list_append(&data->args, arg);
132 return 0;
135 static void init_log_defaults(void)
137 init_diff_ui_defaults();
139 decoration_style = auto_decoration_style();
142 static void cmd_log_init_defaults(struct rev_info *rev)
144 if (fmt_pretty)
145 get_commit_format(fmt_pretty, rev);
146 if (default_follow)
147 rev->diffopt.flags.default_follow_renames = 1;
148 rev->verbose_header = 1;
149 rev->diffopt.flags.recursive = 1;
150 rev->diffopt.stat_width = -1; /* use full terminal width */
151 rev->diffopt.stat_graph_width = -1; /* respect statGraphWidth config */
152 rev->abbrev_commit = default_abbrev_commit;
153 rev->show_root_diff = default_show_root;
154 rev->subject_prefix = fmt_patch_subject_prefix;
155 rev->patch_name_max = fmt_patch_name_max;
156 rev->show_signature = default_show_signature;
157 rev->encode_email_headers = default_encode_email_headers;
158 rev->diffopt.flags.allow_textconv = 1;
160 if (default_date_mode)
161 parse_date_format(default_date_mode, &rev->date_mode);
164 static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
165 struct rev_info *rev, struct setup_revision_opt *opt)
167 struct userformat_want w;
168 int quiet = 0, source = 0, mailmap;
169 static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
170 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
171 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
172 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
173 struct decoration_filter decoration_filter = {&decorate_refs_include,
174 &decorate_refs_exclude,
175 &decorate_refs_exclude_config};
176 static struct revision_sources revision_sources;
178 const struct option builtin_log_options[] = {
179 OPT__QUIET(&quiet, N_("suppress diff output")),
180 OPT_BOOL(0, "source", &source, N_("show source")),
181 OPT_BOOL(0, "use-mailmap", &mailmap, N_("use mail map file")),
182 OPT_ALIAS(0, "mailmap", "use-mailmap"),
183 OPT_STRING_LIST(0, "decorate-refs", &decorate_refs_include,
184 N_("pattern"), N_("only decorate refs that match <pattern>")),
185 OPT_STRING_LIST(0, "decorate-refs-exclude", &decorate_refs_exclude,
186 N_("pattern"), N_("do not decorate refs that match <pattern>")),
187 OPT_CALLBACK_F(0, "decorate", NULL, NULL, N_("decorate options"),
188 PARSE_OPT_OPTARG, decorate_callback),
189 OPT_CALLBACK('L', NULL, &line_cb, "range:file",
190 N_("trace the evolution of line range <start>,<end> or function :<funcname> in <file>"),
191 log_line_range_callback),
192 OPT_END()
195 line_cb.rev = rev;
196 line_cb.prefix = prefix;
198 mailmap = use_mailmap_config;
199 argc = parse_options(argc, argv, prefix,
200 builtin_log_options, builtin_log_usage,
201 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
202 PARSE_OPT_KEEP_DASHDASH);
204 if (quiet)
205 rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
206 argc = setup_revisions(argc, argv, rev, opt);
208 /* Any arguments at this point are not recognized */
209 if (argc > 1)
210 die(_("unrecognized argument: %s"), argv[1]);
212 if (rev->line_level_traverse && rev->prune_data.nr)
213 die(_("-L<range>:<file> cannot be used with pathspec"));
215 memset(&w, 0, sizeof(w));
216 userformat_find_requirements(NULL, &w);
218 if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
219 rev->show_notes = 1;
220 if (rev->show_notes)
221 load_display_notes(&rev->notes_opt);
223 if ((rev->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
224 rev->diffopt.filter || rev->diffopt.flags.follow_renames)
225 rev->always_show_header = 0;
227 if (source || w.source) {
228 init_revision_sources(&revision_sources);
229 rev->sources = &revision_sources;
232 if (mailmap) {
233 rev->mailmap = xcalloc(1, sizeof(struct string_list));
234 read_mailmap(rev->mailmap);
237 if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
239 * "log --pretty=raw" is special; ignore UI oriented
240 * configuration variables such as decoration.
242 if (!decoration_given)
243 decoration_style = 0;
244 if (!rev->abbrev_commit_given)
245 rev->abbrev_commit = 0;
248 if (decoration_style) {
249 const struct string_list *config_exclude =
250 repo_config_get_value_multi(the_repository,
251 "log.excludeDecoration");
253 if (config_exclude) {
254 struct string_list_item *item;
255 for_each_string_list_item(item, config_exclude)
256 string_list_append(&decorate_refs_exclude_config,
257 item->string);
260 rev->show_decorations = 1;
262 load_ref_decorations(&decoration_filter, decoration_style);
265 if (rev->line_level_traverse)
266 line_log_init(rev, line_cb.prefix, &line_cb.args);
268 setup_pager();
271 static void cmd_log_init(int argc, const char **argv, const char *prefix,
272 struct rev_info *rev, struct setup_revision_opt *opt)
274 cmd_log_init_defaults(rev);
275 cmd_log_init_finish(argc, argv, prefix, rev, opt);
279 * This gives a rough estimate for how many commits we
280 * will print out in the list.
282 static int estimate_commit_count(struct commit_list *list)
284 int n = 0;
286 while (list) {
287 struct commit *commit = list->item;
288 unsigned int flags = commit->object.flags;
289 list = list->next;
290 if (!(flags & (TREESAME | UNINTERESTING)))
291 n++;
293 return n;
296 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
298 if (rev->shown_one) {
299 rev->shown_one = 0;
300 if (rev->commit_format != CMIT_FMT_ONELINE)
301 putchar(rev->diffopt.line_termination);
303 fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
306 static struct itimerval early_output_timer;
308 static void log_show_early(struct rev_info *revs, struct commit_list *list)
310 int i = revs->early_output;
311 int show_header = 1;
312 int no_free = revs->diffopt.no_free;
314 revs->diffopt.no_free = 0;
315 sort_in_topological_order(&list, revs->sort_order);
316 while (list && i) {
317 struct commit *commit = list->item;
318 switch (simplify_commit(revs, commit)) {
319 case commit_show:
320 if (show_header) {
321 int n = estimate_commit_count(list);
322 show_early_header(revs, "incomplete", n);
323 show_header = 0;
325 log_tree_commit(revs, commit);
326 i--;
327 break;
328 case commit_ignore:
329 break;
330 case commit_error:
331 revs->diffopt.no_free = no_free;
332 diff_free(&revs->diffopt);
333 return;
335 list = list->next;
338 /* Did we already get enough commits for the early output? */
339 if (!i) {
340 revs->diffopt.no_free = 0;
341 diff_free(&revs->diffopt);
342 return;
346 * ..if no, then repeat it twice a second until we
347 * do.
349 * NOTE! We don't use "it_interval", because if the
350 * reader isn't listening, we want our output to be
351 * throttled by the writing, and not have the timer
352 * trigger every second even if we're blocked on a
353 * reader!
355 early_output_timer.it_value.tv_sec = 0;
356 early_output_timer.it_value.tv_usec = 500000;
357 setitimer(ITIMER_REAL, &early_output_timer, NULL);
360 static void early_output(int signal)
362 show_early_output = log_show_early;
365 static void setup_early_output(void)
367 struct sigaction sa;
370 * Set up the signal handler, minimally intrusively:
371 * we only set a single volatile integer word (not
372 * using sigatomic_t - trying to avoid unnecessary
373 * system dependencies and headers), and using
374 * SA_RESTART.
376 memset(&sa, 0, sizeof(sa));
377 sa.sa_handler = early_output;
378 sigemptyset(&sa.sa_mask);
379 sa.sa_flags = SA_RESTART;
380 sigaction(SIGALRM, &sa, NULL);
383 * If we can get the whole output in less than a
384 * tenth of a second, don't even bother doing the
385 * early-output thing..
387 * This is a one-time-only trigger.
389 early_output_timer.it_value.tv_sec = 0;
390 early_output_timer.it_value.tv_usec = 100000;
391 setitimer(ITIMER_REAL, &early_output_timer, NULL);
394 static void finish_early_output(struct rev_info *rev)
396 int n = estimate_commit_count(rev->commits);
397 signal(SIGALRM, SIG_IGN);
398 show_early_header(rev, "done", n);
401 static int cmd_log_walk(struct rev_info *rev)
403 struct commit *commit;
404 int saved_nrl = 0;
405 int saved_dcctc = 0;
407 if (rev->early_output)
408 setup_early_output();
410 if (prepare_revision_walk(rev))
411 die(_("revision walk setup failed"));
413 if (rev->early_output)
414 finish_early_output(rev);
417 * For --check and --exit-code, the exit code is based on CHECK_FAILED
418 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
419 * retain that state information if replacing rev->diffopt in this loop
421 rev->diffopt.no_free = 1;
422 while ((commit = get_revision(rev)) != NULL) {
423 if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
425 * We decremented max_count in get_revision,
426 * but we didn't actually show the commit.
428 rev->max_count++;
429 if (!rev->reflog_info) {
431 * We may show a given commit multiple times when
432 * walking the reflogs.
434 free_commit_buffer(the_repository->parsed_objects,
435 commit);
436 free_commit_list(commit->parents);
437 commit->parents = NULL;
439 if (saved_nrl < rev->diffopt.needed_rename_limit)
440 saved_nrl = rev->diffopt.needed_rename_limit;
441 if (rev->diffopt.degraded_cc_to_c)
442 saved_dcctc = 1;
444 rev->diffopt.degraded_cc_to_c = saved_dcctc;
445 rev->diffopt.needed_rename_limit = saved_nrl;
446 rev->diffopt.no_free = 0;
447 diff_free(&rev->diffopt);
449 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
450 rev->diffopt.flags.check_failed) {
451 return 02;
453 return diff_result_code(&rev->diffopt, 0);
456 static int git_log_config(const char *var, const char *value, void *cb)
458 const char *slot_name;
460 if (!strcmp(var, "format.pretty"))
461 return git_config_string(&fmt_pretty, var, value);
462 if (!strcmp(var, "format.subjectprefix"))
463 return git_config_string(&fmt_patch_subject_prefix, var, value);
464 if (!strcmp(var, "format.filenamemaxlength")) {
465 fmt_patch_name_max = git_config_int(var, value);
466 return 0;
468 if (!strcmp(var, "format.encodeemailheaders")) {
469 default_encode_email_headers = git_config_bool(var, value);
470 return 0;
472 if (!strcmp(var, "log.abbrevcommit")) {
473 default_abbrev_commit = git_config_bool(var, value);
474 return 0;
476 if (!strcmp(var, "log.date"))
477 return git_config_string(&default_date_mode, var, value);
478 if (!strcmp(var, "log.decorate")) {
479 decoration_style = parse_decoration_style(value);
480 if (decoration_style < 0)
481 decoration_style = 0; /* maybe warn? */
482 return 0;
484 if (!strcmp(var, "log.showroot")) {
485 default_show_root = git_config_bool(var, value);
486 return 0;
488 if (!strcmp(var, "log.follow")) {
489 default_follow = git_config_bool(var, value);
490 return 0;
492 if (skip_prefix(var, "color.decorate.", &slot_name))
493 return parse_decorate_color_config(var, slot_name, value);
494 if (!strcmp(var, "log.mailmap")) {
495 use_mailmap_config = git_config_bool(var, value);
496 return 0;
498 if (!strcmp(var, "log.showsignature")) {
499 default_show_signature = git_config_bool(var, value);
500 return 0;
503 if (grep_config(var, value, cb) < 0)
504 return -1;
505 if (git_gpg_config(var, value, cb) < 0)
506 return -1;
507 return git_diff_ui_config(var, value, cb);
510 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
512 struct rev_info rev;
513 struct setup_revision_opt opt;
515 init_log_defaults();
516 git_config(git_log_config, NULL);
518 repo_init_revisions(the_repository, &rev, prefix);
519 rev.diff = 1;
520 rev.simplify_history = 0;
521 memset(&opt, 0, sizeof(opt));
522 opt.def = "HEAD";
523 opt.revarg_opt = REVARG_COMMITTISH;
524 cmd_log_init(argc, argv, prefix, &rev, &opt);
525 if (!rev.diffopt.output_format)
526 rev.diffopt.output_format = DIFF_FORMAT_RAW;
527 return cmd_log_walk(&rev);
530 static void show_tagger(const char *buf, struct rev_info *rev)
532 struct strbuf out = STRBUF_INIT;
533 struct pretty_print_context pp = {0};
535 pp.fmt = rev->commit_format;
536 pp.date_mode = rev->date_mode;
537 pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
538 fprintf(rev->diffopt.file, "%s", out.buf);
539 strbuf_release(&out);
542 static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
544 struct object_id oidc;
545 struct object_context obj_context;
546 char *buf;
547 unsigned long size;
549 fflush(rev->diffopt.file);
550 if (!rev->diffopt.flags.textconv_set_via_cmdline ||
551 !rev->diffopt.flags.allow_textconv)
552 return stream_blob_to_fd(1, oid, NULL, 0);
554 if (get_oid_with_context(the_repository, obj_name,
555 GET_OID_RECORD_PATH,
556 &oidc, &obj_context))
557 die(_("not a valid object name %s"), obj_name);
558 if (!obj_context.path ||
559 !textconv_object(the_repository, obj_context.path,
560 obj_context.mode, &oidc, 1, &buf, &size)) {
561 free(obj_context.path);
562 return stream_blob_to_fd(1, oid, NULL, 0);
565 if (!buf)
566 die(_("git show %s: bad file"), obj_name);
568 write_or_die(1, buf, size);
569 free(obj_context.path);
570 return 0;
573 static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
575 unsigned long size;
576 enum object_type type;
577 char *buf = read_object_file(oid, &type, &size);
578 int offset = 0;
580 if (!buf)
581 return error(_("could not read object %s"), oid_to_hex(oid));
583 assert(type == OBJ_TAG);
584 while (offset < size && buf[offset] != '\n') {
585 int new_offset = offset + 1;
586 const char *ident;
587 while (new_offset < size && buf[new_offset++] != '\n')
588 ; /* do nothing */
589 if (skip_prefix(buf + offset, "tagger ", &ident))
590 show_tagger(ident, rev);
591 offset = new_offset;
594 if (offset < size)
595 fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
596 free(buf);
597 return 0;
600 static int show_tree_object(const struct object_id *oid,
601 struct strbuf *base,
602 const char *pathname, unsigned mode, int stage, void *context)
604 FILE *file = context;
605 fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
606 return 0;
609 static void show_setup_revisions_tweak(struct rev_info *rev,
610 struct setup_revision_opt *opt)
612 if (rev->first_parent_only)
613 diff_merges_default_to_first_parent(rev);
614 else
615 diff_merges_default_to_dense_combined(rev);
616 if (!rev->diffopt.output_format)
617 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
620 int cmd_show(int argc, const char **argv, const char *prefix)
622 struct rev_info rev;
623 struct object_array_entry *objects;
624 struct setup_revision_opt opt;
625 struct pathspec match_all;
626 int i, count, ret = 0;
628 init_log_defaults();
629 git_config(git_log_config, NULL);
631 memset(&match_all, 0, sizeof(match_all));
632 repo_init_revisions(the_repository, &rev, prefix);
633 rev.diff = 1;
634 rev.always_show_header = 1;
635 rev.no_walk = REVISION_WALK_NO_WALK_SORTED;
636 rev.diffopt.stat_width = -1; /* Scale to real terminal size */
638 memset(&opt, 0, sizeof(opt));
639 opt.def = "HEAD";
640 opt.tweak = show_setup_revisions_tweak;
641 cmd_log_init(argc, argv, prefix, &rev, &opt);
643 if (!rev.no_walk)
644 return cmd_log_walk(&rev);
646 count = rev.pending.nr;
647 objects = rev.pending.objects;
648 for (i = 0; i < count && !ret; i++) {
649 struct object *o = objects[i].item;
650 const char *name = objects[i].name;
651 switch (o->type) {
652 case OBJ_BLOB:
653 ret = show_blob_object(&o->oid, &rev, name);
654 break;
655 case OBJ_TAG: {
656 struct tag *t = (struct tag *)o;
657 struct object_id *oid = get_tagged_oid(t);
659 if (rev.shown_one)
660 putchar('\n');
661 fprintf(rev.diffopt.file, "%stag %s%s\n",
662 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
663 t->tag,
664 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
665 ret = show_tag_object(&o->oid, &rev);
666 rev.shown_one = 1;
667 if (ret)
668 break;
669 o = parse_object(the_repository, oid);
670 if (!o)
671 ret = error(_("could not read object %s"),
672 oid_to_hex(oid));
673 objects[i].item = o;
674 i--;
675 break;
677 case OBJ_TREE:
678 if (rev.shown_one)
679 putchar('\n');
680 fprintf(rev.diffopt.file, "%stree %s%s\n\n",
681 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
682 name,
683 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
684 read_tree_recursive(the_repository, (struct tree *)o, "",
685 0, 0, &match_all, show_tree_object,
686 rev.diffopt.file);
687 rev.shown_one = 1;
688 break;
689 case OBJ_COMMIT:
690 rev.pending.nr = rev.pending.alloc = 0;
691 rev.pending.objects = NULL;
692 add_object_array(o, name, &rev.pending);
693 ret = cmd_log_walk(&rev);
694 break;
695 default:
696 ret = error(_("unknown type: %d"), o->type);
699 free(objects);
700 return ret;
704 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
706 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
708 struct rev_info rev;
709 struct setup_revision_opt opt;
711 init_log_defaults();
712 git_config(git_log_config, NULL);
714 repo_init_revisions(the_repository, &rev, prefix);
715 init_reflog_walk(&rev.reflog_info);
716 rev.verbose_header = 1;
717 memset(&opt, 0, sizeof(opt));
718 opt.def = "HEAD";
719 cmd_log_init_defaults(&rev);
720 rev.abbrev_commit = 1;
721 rev.commit_format = CMIT_FMT_ONELINE;
722 rev.use_terminator = 1;
723 rev.always_show_header = 1;
724 cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
726 return cmd_log_walk(&rev);
729 static void log_setup_revisions_tweak(struct rev_info *rev,
730 struct setup_revision_opt *opt)
732 if (rev->diffopt.flags.default_follow_renames &&
733 rev->prune_data.nr == 1)
734 rev->diffopt.flags.follow_renames = 1;
736 if (rev->first_parent_only)
737 diff_merges_default_to_first_parent(rev);
740 int cmd_log(int argc, const char **argv, const char *prefix)
742 struct rev_info rev;
743 struct setup_revision_opt opt;
745 init_log_defaults();
746 git_config(git_log_config, NULL);
748 repo_init_revisions(the_repository, &rev, prefix);
749 rev.always_show_header = 1;
750 memset(&opt, 0, sizeof(opt));
751 opt.def = "HEAD";
752 opt.revarg_opt = REVARG_COMMITTISH;
753 opt.tweak = log_setup_revisions_tweak;
754 cmd_log_init(argc, argv, prefix, &rev, &opt);
755 return cmd_log_walk(&rev);
758 /* format-patch */
760 static const char *fmt_patch_suffix = ".patch";
761 static int numbered = 0;
762 static int auto_number = 1;
764 static char *default_attach = NULL;
766 static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
767 static struct string_list extra_to = STRING_LIST_INIT_NODUP;
768 static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
770 static void add_header(const char *value)
772 struct string_list_item *item;
773 int len = strlen(value);
774 while (len && value[len - 1] == '\n')
775 len--;
777 if (!strncasecmp(value, "to: ", 4)) {
778 item = string_list_append(&extra_to, value + 4);
779 len -= 4;
780 } else if (!strncasecmp(value, "cc: ", 4)) {
781 item = string_list_append(&extra_cc, value + 4);
782 len -= 4;
783 } else {
784 item = string_list_append(&extra_hdr, value);
787 item->string[len] = '\0';
790 enum cover_setting {
791 COVER_UNSET,
792 COVER_OFF,
793 COVER_ON,
794 COVER_AUTO
797 enum thread_level {
798 THREAD_UNSET,
799 THREAD_SHALLOW,
800 THREAD_DEEP
803 enum cover_from_description {
804 COVER_FROM_NONE,
805 COVER_FROM_MESSAGE,
806 COVER_FROM_SUBJECT,
807 COVER_FROM_AUTO
810 enum auto_base_setting {
811 AUTO_BASE_NEVER,
812 AUTO_BASE_ALWAYS,
813 AUTO_BASE_WHEN_ABLE
816 static enum thread_level thread;
817 static int do_signoff;
818 static enum auto_base_setting auto_base;
819 static char *from;
820 static const char *signature = git_version_string;
821 static const char *signature_file;
822 static enum cover_setting config_cover_letter;
823 static const char *config_output_directory;
824 static enum cover_from_description cover_from_description_mode = COVER_FROM_MESSAGE;
825 static int show_notes;
826 static struct display_notes_opt notes_opt;
828 static enum cover_from_description parse_cover_from_description(const char *arg)
830 if (!arg || !strcmp(arg, "default"))
831 return COVER_FROM_MESSAGE;
832 else if (!strcmp(arg, "none"))
833 return COVER_FROM_NONE;
834 else if (!strcmp(arg, "message"))
835 return COVER_FROM_MESSAGE;
836 else if (!strcmp(arg, "subject"))
837 return COVER_FROM_SUBJECT;
838 else if (!strcmp(arg, "auto"))
839 return COVER_FROM_AUTO;
840 else
841 die(_("%s: invalid cover from description mode"), arg);
844 static int git_format_config(const char *var, const char *value, void *cb)
846 if (!strcmp(var, "format.headers")) {
847 if (!value)
848 die(_("format.headers without value"));
849 add_header(value);
850 return 0;
852 if (!strcmp(var, "format.suffix"))
853 return git_config_string(&fmt_patch_suffix, var, value);
854 if (!strcmp(var, "format.to")) {
855 if (!value)
856 return config_error_nonbool(var);
857 string_list_append(&extra_to, value);
858 return 0;
860 if (!strcmp(var, "format.cc")) {
861 if (!value)
862 return config_error_nonbool(var);
863 string_list_append(&extra_cc, value);
864 return 0;
866 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
867 !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
868 return 0;
870 if (!strcmp(var, "format.numbered")) {
871 if (value && !strcasecmp(value, "auto")) {
872 auto_number = 1;
873 return 0;
875 numbered = git_config_bool(var, value);
876 auto_number = auto_number && numbered;
877 return 0;
879 if (!strcmp(var, "format.attach")) {
880 if (value && *value)
881 default_attach = xstrdup(value);
882 else
883 default_attach = xstrdup(git_version_string);
884 return 0;
886 if (!strcmp(var, "format.thread")) {
887 if (value && !strcasecmp(value, "deep")) {
888 thread = THREAD_DEEP;
889 return 0;
891 if (value && !strcasecmp(value, "shallow")) {
892 thread = THREAD_SHALLOW;
893 return 0;
895 thread = git_config_bool(var, value) ? THREAD_SHALLOW : THREAD_UNSET;
896 return 0;
898 if (!strcmp(var, "format.signoff")) {
899 do_signoff = git_config_bool(var, value);
900 return 0;
902 if (!strcmp(var, "format.signature"))
903 return git_config_string(&signature, var, value);
904 if (!strcmp(var, "format.signaturefile"))
905 return git_config_pathname(&signature_file, var, value);
906 if (!strcmp(var, "format.coverletter")) {
907 if (value && !strcasecmp(value, "auto")) {
908 config_cover_letter = COVER_AUTO;
909 return 0;
911 config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
912 return 0;
914 if (!strcmp(var, "format.outputdirectory"))
915 return git_config_string(&config_output_directory, var, value);
916 if (!strcmp(var, "format.useautobase")) {
917 if (value && !strcasecmp(value, "whenAble")) {
918 auto_base = AUTO_BASE_WHEN_ABLE;
919 return 0;
921 auto_base = git_config_bool(var, value) ? AUTO_BASE_ALWAYS : AUTO_BASE_NEVER;
922 return 0;
924 if (!strcmp(var, "format.from")) {
925 int b = git_parse_maybe_bool(value);
926 free(from);
927 if (b < 0)
928 from = xstrdup(value);
929 else if (b)
930 from = xstrdup(git_committer_info(IDENT_NO_DATE));
931 else
932 from = NULL;
933 return 0;
935 if (!strcmp(var, "format.notes")) {
936 int b = git_parse_maybe_bool(value);
937 if (b < 0)
938 enable_ref_display_notes(&notes_opt, &show_notes, value);
939 else if (b)
940 enable_default_display_notes(&notes_opt, &show_notes);
941 else
942 disable_display_notes(&notes_opt, &show_notes);
943 return 0;
945 if (!strcmp(var, "format.coverfromdescription")) {
946 cover_from_description_mode = parse_cover_from_description(value);
947 return 0;
950 return git_log_config(var, value, cb);
953 static const char *output_directory = NULL;
954 static int outdir_offset;
956 static int open_next_file(struct commit *commit, const char *subject,
957 struct rev_info *rev, int quiet)
959 struct strbuf filename = STRBUF_INIT;
961 if (output_directory) {
962 strbuf_addstr(&filename, output_directory);
963 strbuf_complete(&filename, '/');
966 if (rev->numbered_files)
967 strbuf_addf(&filename, "%d", rev->nr);
968 else if (commit)
969 fmt_output_commit(&filename, commit, rev);
970 else
971 fmt_output_subject(&filename, subject, rev);
973 if (!quiet)
974 printf("%s\n", filename.buf + outdir_offset);
976 if ((rev->diffopt.file = fopen(filename.buf, "w")) == NULL) {
977 error_errno(_("cannot open patch file %s"), filename.buf);
978 strbuf_release(&filename);
979 return -1;
982 strbuf_release(&filename);
983 return 0;
986 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
988 struct rev_info check_rev;
989 struct commit *commit, *c1, *c2;
990 struct object *o1, *o2;
991 unsigned flags1, flags2;
993 if (rev->pending.nr != 2)
994 die(_("need exactly one range"));
996 o1 = rev->pending.objects[0].item;
997 o2 = rev->pending.objects[1].item;
998 flags1 = o1->flags;
999 flags2 = o2->flags;
1000 c1 = lookup_commit_reference(the_repository, &o1->oid);
1001 c2 = lookup_commit_reference(the_repository, &o2->oid);
1003 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
1004 die(_("not a range"));
1006 init_patch_ids(the_repository, ids);
1008 /* given a range a..b get all patch ids for b..a */
1009 repo_init_revisions(the_repository, &check_rev, rev->prefix);
1010 check_rev.max_parents = 1;
1011 o1->flags ^= UNINTERESTING;
1012 o2->flags ^= UNINTERESTING;
1013 add_pending_object(&check_rev, o1, "o1");
1014 add_pending_object(&check_rev, o2, "o2");
1015 if (prepare_revision_walk(&check_rev))
1016 die(_("revision walk setup failed"));
1018 while ((commit = get_revision(&check_rev)) != NULL) {
1019 add_commit_patch_id(commit, ids);
1022 /* reset for next revision walk */
1023 clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
1024 clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
1025 o1->flags = flags1;
1026 o2->flags = flags2;
1029 static void gen_message_id(struct rev_info *info, char *base)
1031 struct strbuf buf = STRBUF_INIT;
1032 strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
1033 (timestamp_t) time(NULL),
1034 git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
1035 info->message_id = strbuf_detach(&buf, NULL);
1038 static void print_signature(FILE *file)
1040 if (!signature || !*signature)
1041 return;
1043 fprintf(file, "-- \n%s", signature);
1044 if (signature[strlen(signature)-1] != '\n')
1045 putc('\n', file);
1046 putc('\n', file);
1049 static char *find_branch_name(struct rev_info *rev)
1051 int i, positive = -1;
1052 struct object_id branch_oid;
1053 const struct object_id *tip_oid;
1054 const char *ref, *v;
1055 char *full_ref, *branch = NULL;
1057 for (i = 0; i < rev->cmdline.nr; i++) {
1058 if (rev->cmdline.rev[i].flags & UNINTERESTING)
1059 continue;
1060 if (positive < 0)
1061 positive = i;
1062 else
1063 return NULL;
1065 if (positive < 0)
1066 return NULL;
1067 ref = rev->cmdline.rev[positive].name;
1068 tip_oid = &rev->cmdline.rev[positive].item->oid;
1069 if (dwim_ref(ref, strlen(ref), &branch_oid, &full_ref, 0) &&
1070 skip_prefix(full_ref, "refs/heads/", &v) &&
1071 oideq(tip_oid, &branch_oid))
1072 branch = xstrdup(v);
1073 free(full_ref);
1074 return branch;
1077 static void show_diffstat(struct rev_info *rev,
1078 struct commit *origin, struct commit *head)
1080 struct diff_options opts;
1082 memcpy(&opts, &rev->diffopt, sizeof(opts));
1083 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1084 diff_setup_done(&opts);
1086 diff_tree_oid(get_commit_tree_oid(origin),
1087 get_commit_tree_oid(head),
1088 "", &opts);
1089 diffcore_std(&opts);
1090 diff_flush(&opts);
1092 fprintf(rev->diffopt.file, "\n");
1095 static void prepare_cover_text(struct pretty_print_context *pp,
1096 const char *branch_name,
1097 struct strbuf *sb,
1098 const char *encoding,
1099 int need_8bit_cte)
1101 const char *subject = "*** SUBJECT HERE ***";
1102 const char *body = "*** BLURB HERE ***";
1103 struct strbuf description_sb = STRBUF_INIT;
1104 struct strbuf subject_sb = STRBUF_INIT;
1106 if (cover_from_description_mode == COVER_FROM_NONE)
1107 goto do_pp;
1109 if (branch_name && *branch_name)
1110 read_branch_desc(&description_sb, branch_name);
1111 if (!description_sb.len)
1112 goto do_pp;
1114 if (cover_from_description_mode == COVER_FROM_SUBJECT ||
1115 cover_from_description_mode == COVER_FROM_AUTO)
1116 body = format_subject(&subject_sb, description_sb.buf, " ");
1118 if (cover_from_description_mode == COVER_FROM_MESSAGE ||
1119 (cover_from_description_mode == COVER_FROM_AUTO &&
1120 subject_sb.len > COVER_FROM_AUTO_MAX_SUBJECT_LEN))
1121 body = description_sb.buf;
1122 else
1123 subject = subject_sb.buf;
1125 do_pp:
1126 pp_title_line(pp, &subject, sb, encoding, need_8bit_cte);
1127 pp_remainder(pp, &body, sb, 0);
1129 strbuf_release(&description_sb);
1130 strbuf_release(&subject_sb);
1133 static int get_notes_refs(struct string_list_item *item, void *arg)
1135 strvec_pushf(arg, "--notes=%s", item->string);
1136 return 0;
1139 static void get_notes_args(struct strvec *arg, struct rev_info *rev)
1141 if (!rev->show_notes) {
1142 strvec_push(arg, "--no-notes");
1143 } else if (rev->notes_opt.use_default_notes > 0 ||
1144 (rev->notes_opt.use_default_notes == -1 &&
1145 !rev->notes_opt.extra_notes_refs.nr)) {
1146 strvec_push(arg, "--notes");
1147 } else {
1148 for_each_string_list(&rev->notes_opt.extra_notes_refs, get_notes_refs, arg);
1152 static void make_cover_letter(struct rev_info *rev, int use_separate_file,
1153 struct commit *origin,
1154 int nr, struct commit **list,
1155 const char *branch_name,
1156 int quiet)
1158 const char *committer;
1159 struct shortlog log;
1160 struct strbuf sb = STRBUF_INIT;
1161 int i;
1162 const char *encoding = "UTF-8";
1163 int need_8bit_cte = 0;
1164 struct pretty_print_context pp = {0};
1165 struct commit *head = list[0];
1167 if (!cmit_fmt_is_mail(rev->commit_format))
1168 die(_("cover letter needs email format"));
1170 committer = git_committer_info(0);
1172 if (use_separate_file &&
1173 open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1174 die(_("failed to create cover-letter file"));
1176 log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1178 for (i = 0; !need_8bit_cte && i < nr; i++) {
1179 const char *buf = get_commit_buffer(list[i], NULL);
1180 if (has_non_ascii(buf))
1181 need_8bit_cte = 1;
1182 unuse_commit_buffer(list[i], buf);
1185 if (!branch_name)
1186 branch_name = find_branch_name(rev);
1188 pp.fmt = CMIT_FMT_EMAIL;
1189 pp.date_mode.type = DATE_RFC2822;
1190 pp.rev = rev;
1191 pp.print_email_subject = 1;
1192 pp_user_info(&pp, NULL, &sb, committer, encoding);
1193 prepare_cover_text(&pp, branch_name, &sb, encoding, need_8bit_cte);
1194 fprintf(rev->diffopt.file, "%s\n", sb.buf);
1196 strbuf_release(&sb);
1198 shortlog_init(&log);
1199 log.wrap_lines = 1;
1200 log.wrap = MAIL_DEFAULT_WRAP;
1201 log.in1 = 2;
1202 log.in2 = 4;
1203 log.file = rev->diffopt.file;
1204 log.groups = SHORTLOG_GROUP_AUTHOR;
1205 for (i = 0; i < nr; i++)
1206 shortlog_add_commit(&log, list[i]);
1208 shortlog_output(&log);
1210 /* We can only do diffstat with a unique reference point */
1211 if (origin)
1212 show_diffstat(rev, origin, head);
1214 if (rev->idiff_oid1) {
1215 fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1216 show_interdiff(rev->idiff_oid1, rev->idiff_oid2, 0,
1217 &rev->diffopt);
1220 if (rev->rdiff1) {
1222 * Pass minimum required diff-options to range-diff; others
1223 * can be added later if deemed desirable.
1225 struct diff_options opts;
1226 struct strvec other_arg = STRVEC_INIT;
1227 struct range_diff_options range_diff_opts = {
1228 .creation_factor = rev->creation_factor,
1229 .dual_color = 1,
1230 .diffopt = &opts,
1231 .other_arg = &other_arg
1234 diff_setup(&opts);
1235 opts.file = rev->diffopt.file;
1236 opts.use_color = rev->diffopt.use_color;
1237 diff_setup_done(&opts);
1238 fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1239 get_notes_args(&other_arg, rev);
1240 show_range_diff(rev->rdiff1, rev->rdiff2, &range_diff_opts);
1241 strvec_clear(&other_arg);
1245 static const char *clean_message_id(const char *msg_id)
1247 char ch;
1248 const char *a, *z, *m;
1250 m = msg_id;
1251 while ((ch = *m) && (isspace(ch) || (ch == '<')))
1252 m++;
1253 a = m;
1254 z = NULL;
1255 while ((ch = *m)) {
1256 if (!isspace(ch) && (ch != '>'))
1257 z = m;
1258 m++;
1260 if (!z)
1261 die(_("insane in-reply-to: %s"), msg_id);
1262 if (++z == m)
1263 return a;
1264 return xmemdupz(a, z - a);
1267 static const char *set_outdir(const char *prefix, const char *output_directory)
1269 if (output_directory && is_absolute_path(output_directory))
1270 return output_directory;
1272 if (!prefix || !*prefix) {
1273 if (output_directory)
1274 return output_directory;
1275 /* The user did not explicitly ask for "./" */
1276 outdir_offset = 2;
1277 return "./";
1280 outdir_offset = strlen(prefix);
1281 if (!output_directory)
1282 return prefix;
1284 return prefix_filename(prefix, output_directory);
1287 static const char * const builtin_format_patch_usage[] = {
1288 N_("git format-patch [<options>] [<since> | <revision-range>]"),
1289 NULL
1292 static int keep_subject = 0;
1294 static int keep_callback(const struct option *opt, const char *arg, int unset)
1296 BUG_ON_OPT_NEG(unset);
1297 BUG_ON_OPT_ARG(arg);
1298 ((struct rev_info *)opt->value)->total = -1;
1299 keep_subject = 1;
1300 return 0;
1303 static int subject_prefix = 0;
1305 static int subject_prefix_callback(const struct option *opt, const char *arg,
1306 int unset)
1308 BUG_ON_OPT_NEG(unset);
1309 subject_prefix = 1;
1310 ((struct rev_info *)opt->value)->subject_prefix = arg;
1311 return 0;
1314 static int rfc_callback(const struct option *opt, const char *arg, int unset)
1316 BUG_ON_OPT_NEG(unset);
1317 BUG_ON_OPT_ARG(arg);
1318 return subject_prefix_callback(opt, "RFC PATCH", unset);
1321 static int numbered_cmdline_opt = 0;
1323 static int numbered_callback(const struct option *opt, const char *arg,
1324 int unset)
1326 BUG_ON_OPT_ARG(arg);
1327 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1328 if (unset)
1329 auto_number = 0;
1330 return 0;
1333 static int no_numbered_callback(const struct option *opt, const char *arg,
1334 int unset)
1336 BUG_ON_OPT_NEG(unset);
1337 return numbered_callback(opt, arg, 1);
1340 static int output_directory_callback(const struct option *opt, const char *arg,
1341 int unset)
1343 const char **dir = (const char **)opt->value;
1344 BUG_ON_OPT_NEG(unset);
1345 if (*dir)
1346 die(_("two output directories?"));
1347 *dir = arg;
1348 return 0;
1351 static int thread_callback(const struct option *opt, const char *arg, int unset)
1353 enum thread_level *thread = (enum thread_level *)opt->value;
1354 if (unset)
1355 *thread = THREAD_UNSET;
1356 else if (!arg || !strcmp(arg, "shallow"))
1357 *thread = THREAD_SHALLOW;
1358 else if (!strcmp(arg, "deep"))
1359 *thread = THREAD_DEEP;
1361 * Please update _git_formatpatch() in git-completion.bash
1362 * when you add new options.
1364 else
1365 return 1;
1366 return 0;
1369 static int attach_callback(const struct option *opt, const char *arg, int unset)
1371 struct rev_info *rev = (struct rev_info *)opt->value;
1372 if (unset)
1373 rev->mime_boundary = NULL;
1374 else if (arg)
1375 rev->mime_boundary = arg;
1376 else
1377 rev->mime_boundary = git_version_string;
1378 rev->no_inline = unset ? 0 : 1;
1379 return 0;
1382 static int inline_callback(const struct option *opt, const char *arg, int unset)
1384 struct rev_info *rev = (struct rev_info *)opt->value;
1385 if (unset)
1386 rev->mime_boundary = NULL;
1387 else if (arg)
1388 rev->mime_boundary = arg;
1389 else
1390 rev->mime_boundary = git_version_string;
1391 rev->no_inline = 0;
1392 return 0;
1395 static int header_callback(const struct option *opt, const char *arg, int unset)
1397 if (unset) {
1398 string_list_clear(&extra_hdr, 0);
1399 string_list_clear(&extra_to, 0);
1400 string_list_clear(&extra_cc, 0);
1401 } else {
1402 add_header(arg);
1404 return 0;
1407 static int to_callback(const struct option *opt, const char *arg, int unset)
1409 if (unset)
1410 string_list_clear(&extra_to, 0);
1411 else
1412 string_list_append(&extra_to, arg);
1413 return 0;
1416 static int cc_callback(const struct option *opt, const char *arg, int unset)
1418 if (unset)
1419 string_list_clear(&extra_cc, 0);
1420 else
1421 string_list_append(&extra_cc, arg);
1422 return 0;
1425 static int from_callback(const struct option *opt, const char *arg, int unset)
1427 char **from = opt->value;
1429 free(*from);
1431 if (unset)
1432 *from = NULL;
1433 else if (arg)
1434 *from = xstrdup(arg);
1435 else
1436 *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1437 return 0;
1440 static int base_callback(const struct option *opt, const char *arg, int unset)
1442 const char **base_commit = opt->value;
1444 if (unset) {
1445 auto_base = AUTO_BASE_NEVER;
1446 *base_commit = NULL;
1447 } else if (!strcmp(arg, "auto")) {
1448 auto_base = AUTO_BASE_ALWAYS;
1449 *base_commit = NULL;
1450 } else {
1451 auto_base = AUTO_BASE_NEVER;
1452 *base_commit = arg;
1454 return 0;
1457 struct base_tree_info {
1458 struct object_id base_commit;
1459 int nr_patch_id, alloc_patch_id;
1460 struct object_id *patch_id;
1463 static struct commit *get_base_commit(const char *base_commit,
1464 struct commit **list,
1465 int total)
1467 struct commit *base = NULL;
1468 struct commit **rev;
1469 int i = 0, rev_nr = 0, auto_select, die_on_failure;
1471 switch (auto_base) {
1472 case AUTO_BASE_NEVER:
1473 if (base_commit) {
1474 auto_select = 0;
1475 die_on_failure = 1;
1476 } else {
1477 /* no base information is requested */
1478 return NULL;
1480 break;
1481 case AUTO_BASE_ALWAYS:
1482 case AUTO_BASE_WHEN_ABLE:
1483 if (base_commit) {
1484 BUG("requested automatic base selection but a commit was provided");
1485 } else {
1486 auto_select = 1;
1487 die_on_failure = auto_base == AUTO_BASE_ALWAYS;
1489 break;
1490 default:
1491 BUG("unexpected automatic base selection method");
1494 if (!auto_select) {
1495 base = lookup_commit_reference_by_name(base_commit);
1496 if (!base)
1497 die(_("unknown commit %s"), base_commit);
1498 } else {
1499 struct branch *curr_branch = branch_get(NULL);
1500 const char *upstream = branch_get_upstream(curr_branch, NULL);
1501 if (upstream) {
1502 struct commit_list *base_list;
1503 struct commit *commit;
1504 struct object_id oid;
1506 if (get_oid(upstream, &oid)) {
1507 if (die_on_failure)
1508 die(_("failed to resolve '%s' as a valid ref"), upstream);
1509 else
1510 return NULL;
1512 commit = lookup_commit_or_die(&oid, "upstream base");
1513 base_list = get_merge_bases_many(commit, total, list);
1514 /* There should be one and only one merge base. */
1515 if (!base_list || base_list->next) {
1516 if (die_on_failure) {
1517 die(_("could not find exact merge base"));
1518 } else {
1519 free_commit_list(base_list);
1520 return NULL;
1523 base = base_list->item;
1524 free_commit_list(base_list);
1525 } else {
1526 if (die_on_failure)
1527 die(_("failed to get upstream, if you want to record base commit automatically,\n"
1528 "please use git branch --set-upstream-to to track a remote branch.\n"
1529 "Or you could specify base commit by --base=<base-commit-id> manually"));
1530 else
1531 return NULL;
1535 ALLOC_ARRAY(rev, total);
1536 for (i = 0; i < total; i++)
1537 rev[i] = list[i];
1539 rev_nr = total;
1541 * Get merge base through pair-wise computations
1542 * and store it in rev[0].
1544 while (rev_nr > 1) {
1545 for (i = 0; i < rev_nr / 2; i++) {
1546 struct commit_list *merge_base;
1547 merge_base = get_merge_bases(rev[2 * i], rev[2 * i + 1]);
1548 if (!merge_base || merge_base->next) {
1549 if (die_on_failure) {
1550 die(_("failed to find exact merge base"));
1551 } else {
1552 free(rev);
1553 return NULL;
1557 rev[i] = merge_base->item;
1560 if (rev_nr % 2)
1561 rev[i] = rev[2 * i];
1562 rev_nr = DIV_ROUND_UP(rev_nr, 2);
1565 if (!in_merge_bases(base, rev[0])) {
1566 if (die_on_failure) {
1567 die(_("base commit should be the ancestor of revision list"));
1568 } else {
1569 free(rev);
1570 return NULL;
1574 for (i = 0; i < total; i++) {
1575 if (base == list[i]) {
1576 if (die_on_failure) {
1577 die(_("base commit shouldn't be in revision list"));
1578 } else {
1579 free(rev);
1580 return NULL;
1585 free(rev);
1586 return base;
1589 define_commit_slab(commit_base, int);
1591 static void prepare_bases(struct base_tree_info *bases,
1592 struct commit *base,
1593 struct commit **list,
1594 int total)
1596 struct commit *commit;
1597 struct rev_info revs;
1598 struct diff_options diffopt;
1599 struct commit_base commit_base;
1600 int i;
1602 if (!base)
1603 return;
1605 init_commit_base(&commit_base);
1606 repo_diff_setup(the_repository, &diffopt);
1607 diffopt.flags.recursive = 1;
1608 diff_setup_done(&diffopt);
1610 oidcpy(&bases->base_commit, &base->object.oid);
1612 repo_init_revisions(the_repository, &revs, NULL);
1613 revs.max_parents = 1;
1614 revs.topo_order = 1;
1615 for (i = 0; i < total; i++) {
1616 list[i]->object.flags &= ~UNINTERESTING;
1617 add_pending_object(&revs, &list[i]->object, "rev_list");
1618 *commit_base_at(&commit_base, list[i]) = 1;
1620 base->object.flags |= UNINTERESTING;
1621 add_pending_object(&revs, &base->object, "base");
1623 if (prepare_revision_walk(&revs))
1624 die(_("revision walk setup failed"));
1626 * Traverse the commits list, get prerequisite patch ids
1627 * and stuff them in bases structure.
1629 while ((commit = get_revision(&revs)) != NULL) {
1630 struct object_id oid;
1631 struct object_id *patch_id;
1632 if (*commit_base_at(&commit_base, commit))
1633 continue;
1634 if (commit_patch_id(commit, &diffopt, &oid, 0, 1))
1635 die(_("cannot get patch id"));
1636 ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1637 patch_id = bases->patch_id + bases->nr_patch_id;
1638 oidcpy(patch_id, &oid);
1639 bases->nr_patch_id++;
1641 clear_commit_base(&commit_base);
1644 static void print_bases(struct base_tree_info *bases, FILE *file)
1646 int i;
1648 /* Only do this once, either for the cover or for the first one */
1649 if (is_null_oid(&bases->base_commit))
1650 return;
1652 /* Show the base commit */
1653 fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1655 /* Show the prerequisite patches */
1656 for (i = bases->nr_patch_id - 1; i >= 0; i--)
1657 fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1659 free(bases->patch_id);
1660 bases->nr_patch_id = 0;
1661 bases->alloc_patch_id = 0;
1662 oidclr(&bases->base_commit);
1665 static const char *diff_title(struct strbuf *sb, int reroll_count,
1666 const char *generic, const char *rerolled)
1668 if (reroll_count <= 0)
1669 strbuf_addstr(sb, generic);
1670 else /* RFC may be v0, so allow -v1 to diff against v0 */
1671 strbuf_addf(sb, rerolled, reroll_count - 1);
1672 return sb->buf;
1675 static void infer_range_diff_ranges(struct strbuf *r1,
1676 struct strbuf *r2,
1677 const char *prev,
1678 struct commit *origin,
1679 struct commit *head)
1681 const char *head_oid = oid_to_hex(&head->object.oid);
1682 int prev_is_range = is_range_diff_range(prev);
1684 if (prev_is_range)
1685 strbuf_addstr(r1, prev);
1686 else
1687 strbuf_addf(r1, "%s..%s", head_oid, prev);
1689 if (origin)
1690 strbuf_addf(r2, "%s..%s", oid_to_hex(&origin->object.oid), head_oid);
1691 else if (prev_is_range)
1692 die(_("failed to infer range-diff origin of current series"));
1693 else {
1694 warning(_("using '%s' as range-diff origin of current series"), prev);
1695 strbuf_addf(r2, "%s..%s", prev, head_oid);
1699 int cmd_format_patch(int argc, const char **argv, const char *prefix)
1701 struct commit *commit;
1702 struct commit **list = NULL;
1703 struct rev_info rev;
1704 struct setup_revision_opt s_r_opt;
1705 int nr = 0, total, i;
1706 int use_stdout = 0;
1707 int start_number = -1;
1708 int just_numbers = 0;
1709 int ignore_if_in_upstream = 0;
1710 int cover_letter = -1;
1711 int boundary_count = 0;
1712 int no_binary_diff = 0;
1713 int zero_commit = 0;
1714 struct commit *origin = NULL;
1715 const char *in_reply_to = NULL;
1716 struct patch_ids ids;
1717 struct strbuf buf = STRBUF_INIT;
1718 int use_patch_format = 0;
1719 int quiet = 0;
1720 int reroll_count = -1;
1721 char *cover_from_description_arg = NULL;
1722 char *branch_name = NULL;
1723 char *base_commit = NULL;
1724 struct base_tree_info bases;
1725 struct commit *base;
1726 int show_progress = 0;
1727 struct progress *progress = NULL;
1728 struct oid_array idiff_prev = OID_ARRAY_INIT;
1729 struct strbuf idiff_title = STRBUF_INIT;
1730 const char *rdiff_prev = NULL;
1731 struct strbuf rdiff1 = STRBUF_INIT;
1732 struct strbuf rdiff2 = STRBUF_INIT;
1733 struct strbuf rdiff_title = STRBUF_INIT;
1734 int creation_factor = -1;
1736 const struct option builtin_format_patch_options[] = {
1737 OPT_CALLBACK_F('n', "numbered", &numbered, NULL,
1738 N_("use [PATCH n/m] even with a single patch"),
1739 PARSE_OPT_NOARG, numbered_callback),
1740 OPT_CALLBACK_F('N', "no-numbered", &numbered, NULL,
1741 N_("use [PATCH] even with multiple patches"),
1742 PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback),
1743 OPT_BOOL('s', "signoff", &do_signoff, N_("add a Signed-off-by trailer")),
1744 OPT_BOOL(0, "stdout", &use_stdout,
1745 N_("print patches to standard out")),
1746 OPT_BOOL(0, "cover-letter", &cover_letter,
1747 N_("generate a cover letter")),
1748 OPT_BOOL(0, "numbered-files", &just_numbers,
1749 N_("use simple number sequence for output file names")),
1750 OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
1751 N_("use <sfx> instead of '.patch'")),
1752 OPT_INTEGER(0, "start-number", &start_number,
1753 N_("start numbering patches at <n> instead of 1")),
1754 OPT_INTEGER('v', "reroll-count", &reroll_count,
1755 N_("mark the series as Nth re-roll")),
1756 OPT_INTEGER(0, "filename-max-length", &fmt_patch_name_max,
1757 N_("max length of output filename")),
1758 OPT_CALLBACK_F(0, "rfc", &rev, NULL,
1759 N_("use [RFC PATCH] instead of [PATCH]"),
1760 PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback),
1761 OPT_STRING(0, "cover-from-description", &cover_from_description_arg,
1762 N_("cover-from-description-mode"),
1763 N_("generate parts of a cover letter based on a branch's description")),
1764 OPT_CALLBACK_F(0, "subject-prefix", &rev, N_("prefix"),
1765 N_("use [<prefix>] instead of [PATCH]"),
1766 PARSE_OPT_NONEG, subject_prefix_callback),
1767 OPT_CALLBACK_F('o', "output-directory", &output_directory,
1768 N_("dir"), N_("store resulting files in <dir>"),
1769 PARSE_OPT_NONEG, output_directory_callback),
1770 OPT_CALLBACK_F('k', "keep-subject", &rev, NULL,
1771 N_("don't strip/add [PATCH]"),
1772 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback),
1773 OPT_BOOL(0, "no-binary", &no_binary_diff,
1774 N_("don't output binary diffs")),
1775 OPT_BOOL(0, "zero-commit", &zero_commit,
1776 N_("output all-zero hash in From header")),
1777 OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1778 N_("don't include a patch matching a commit upstream")),
1779 OPT_SET_INT_F('p', "no-stat", &use_patch_format,
1780 N_("show patch format instead of default (patch + stat)"),
1781 1, PARSE_OPT_NONEG),
1782 OPT_GROUP(N_("Messaging")),
1783 OPT_CALLBACK(0, "add-header", NULL, N_("header"),
1784 N_("add email header"), header_callback),
1785 OPT_CALLBACK(0, "to", NULL, N_("email"), N_("add To: header"), to_callback),
1786 OPT_CALLBACK(0, "cc", NULL, N_("email"), N_("add Cc: header"), cc_callback),
1787 OPT_CALLBACK_F(0, "from", &from, N_("ident"),
1788 N_("set From address to <ident> (or committer ident if absent)"),
1789 PARSE_OPT_OPTARG, from_callback),
1790 OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
1791 N_("make first mail a reply to <message-id>")),
1792 OPT_CALLBACK_F(0, "attach", &rev, N_("boundary"),
1793 N_("attach the patch"), PARSE_OPT_OPTARG,
1794 attach_callback),
1795 OPT_CALLBACK_F(0, "inline", &rev, N_("boundary"),
1796 N_("inline the patch"),
1797 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1798 inline_callback),
1799 OPT_CALLBACK_F(0, "thread", &thread, N_("style"),
1800 N_("enable message threading, styles: shallow, deep"),
1801 PARSE_OPT_OPTARG, thread_callback),
1802 OPT_STRING(0, "signature", &signature, N_("signature"),
1803 N_("add a signature")),
1804 OPT_CALLBACK_F(0, "base", &base_commit, N_("base-commit"),
1805 N_("add prerequisite tree info to the patch series"),
1806 0, base_callback),
1807 OPT_FILENAME(0, "signature-file", &signature_file,
1808 N_("add a signature from a file")),
1809 OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1810 OPT_BOOL(0, "progress", &show_progress,
1811 N_("show progress while generating patches")),
1812 OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
1813 N_("show changes against <rev> in cover letter or single patch"),
1814 parse_opt_object_name),
1815 OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
1816 N_("show changes against <refspec> in cover letter or single patch")),
1817 OPT_INTEGER(0, "creation-factor", &creation_factor,
1818 N_("percentage by which creation is weighted")),
1819 OPT_END()
1822 extra_hdr.strdup_strings = 1;
1823 extra_to.strdup_strings = 1;
1824 extra_cc.strdup_strings = 1;
1825 init_log_defaults();
1826 init_display_notes(&notes_opt);
1827 git_config(git_format_config, NULL);
1828 repo_init_revisions(the_repository, &rev, prefix);
1829 rev.show_notes = show_notes;
1830 memcpy(&rev.notes_opt, &notes_opt, sizeof(notes_opt));
1831 rev.commit_format = CMIT_FMT_EMAIL;
1832 rev.encode_email_headers = default_encode_email_headers;
1833 rev.expand_tabs_in_log_default = 0;
1834 rev.verbose_header = 1;
1835 rev.diff = 1;
1836 rev.max_parents = 1;
1837 rev.diffopt.flags.recursive = 1;
1838 rev.subject_prefix = fmt_patch_subject_prefix;
1839 memset(&s_r_opt, 0, sizeof(s_r_opt));
1840 s_r_opt.def = "HEAD";
1841 s_r_opt.revarg_opt = REVARG_COMMITTISH;
1843 if (default_attach) {
1844 rev.mime_boundary = default_attach;
1845 rev.no_inline = 1;
1849 * Parse the arguments before setup_revisions(), or something
1850 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1851 * possibly a valid SHA1.
1853 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1854 builtin_format_patch_usage,
1855 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1856 PARSE_OPT_KEEP_DASHDASH);
1858 /* Make sure "0000-$sub.patch" gives non-negative length for $sub */
1859 if (fmt_patch_name_max <= strlen("0000-") + strlen(fmt_patch_suffix))
1860 fmt_patch_name_max = strlen("0000-") + strlen(fmt_patch_suffix);
1862 if (cover_from_description_arg)
1863 cover_from_description_mode = parse_cover_from_description(cover_from_description_arg);
1865 if (0 < reroll_count) {
1866 struct strbuf sprefix = STRBUF_INIT;
1867 strbuf_addf(&sprefix, "%s v%d",
1868 rev.subject_prefix, reroll_count);
1869 rev.reroll_count = reroll_count;
1870 rev.subject_prefix = strbuf_detach(&sprefix, NULL);
1873 for (i = 0; i < extra_hdr.nr; i++) {
1874 strbuf_addstr(&buf, extra_hdr.items[i].string);
1875 strbuf_addch(&buf, '\n');
1878 if (extra_to.nr)
1879 strbuf_addstr(&buf, "To: ");
1880 for (i = 0; i < extra_to.nr; i++) {
1881 if (i)
1882 strbuf_addstr(&buf, " ");
1883 strbuf_addstr(&buf, extra_to.items[i].string);
1884 if (i + 1 < extra_to.nr)
1885 strbuf_addch(&buf, ',');
1886 strbuf_addch(&buf, '\n');
1889 if (extra_cc.nr)
1890 strbuf_addstr(&buf, "Cc: ");
1891 for (i = 0; i < extra_cc.nr; i++) {
1892 if (i)
1893 strbuf_addstr(&buf, " ");
1894 strbuf_addstr(&buf, extra_cc.items[i].string);
1895 if (i + 1 < extra_cc.nr)
1896 strbuf_addch(&buf, ',');
1897 strbuf_addch(&buf, '\n');
1900 rev.extra_headers = strbuf_detach(&buf, NULL);
1902 if (from) {
1903 if (split_ident_line(&rev.from_ident, from, strlen(from)))
1904 die(_("invalid ident line: %s"), from);
1907 if (start_number < 0)
1908 start_number = 1;
1911 * If numbered is set solely due to format.numbered in config,
1912 * and it would conflict with --keep-subject (-k) from the
1913 * command line, reset "numbered".
1915 if (numbered && keep_subject && !numbered_cmdline_opt)
1916 numbered = 0;
1918 if (numbered && keep_subject)
1919 die(_("-n and -k are mutually exclusive"));
1920 if (keep_subject && subject_prefix)
1921 die(_("--subject-prefix/--rfc and -k are mutually exclusive"));
1922 rev.preserve_subject = keep_subject;
1924 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1925 if (argc > 1)
1926 die(_("unrecognized argument: %s"), argv[1]);
1928 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1929 die(_("--name-only does not make sense"));
1930 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1931 die(_("--name-status does not make sense"));
1932 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1933 die(_("--check does not make sense"));
1935 if (!use_patch_format &&
1936 (!rev.diffopt.output_format ||
1937 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1938 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1939 if (!rev.diffopt.stat_width)
1940 rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
1942 /* Always generate a patch */
1943 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1945 rev.zero_commit = zero_commit;
1946 rev.patch_name_max = fmt_patch_name_max;
1948 if (!rev.diffopt.flags.text && !no_binary_diff)
1949 rev.diffopt.flags.binary = 1;
1951 if (rev.show_notes)
1952 load_display_notes(&rev.notes_opt);
1954 if (use_stdout + rev.diffopt.close_file + !!output_directory > 1)
1955 die(_("--stdout, --output, and --output-directory are mutually exclusive"));
1957 if (use_stdout) {
1958 setup_pager();
1959 } else if (rev.diffopt.close_file) {
1961 * The diff code parsed --output; it has already opened the
1962 * file, but but we must instruct it not to close after each
1963 * diff.
1965 rev.diffopt.no_free = 1;
1966 } else {
1967 int saved;
1969 if (!output_directory)
1970 output_directory = config_output_directory;
1971 output_directory = set_outdir(prefix, output_directory);
1973 if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
1974 rev.diffopt.use_color = GIT_COLOR_NEVER;
1976 * We consider <outdir> as 'outside of gitdir', therefore avoid
1977 * applying adjust_shared_perm in s-c-l-d.
1979 saved = get_shared_repository();
1980 set_shared_repository(0);
1981 switch (safe_create_leading_directories_const(output_directory)) {
1982 case SCLD_OK:
1983 case SCLD_EXISTS:
1984 break;
1985 default:
1986 die(_("could not create leading directories "
1987 "of '%s'"), output_directory);
1989 set_shared_repository(saved);
1990 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1991 die_errno(_("could not create directory '%s'"),
1992 output_directory);
1995 if (rev.pending.nr == 1) {
1996 int check_head = 0;
1998 if (rev.max_count < 0 && !rev.show_root_diff) {
2000 * This is traditional behaviour of "git format-patch
2001 * origin" that prepares what the origin side still
2002 * does not have.
2004 rev.pending.objects[0].item->flags |= UNINTERESTING;
2005 add_head_to_pending(&rev);
2006 check_head = 1;
2009 * Otherwise, it is "format-patch -22 HEAD", and/or
2010 * "format-patch --root HEAD". The user wants
2011 * get_revision() to do the usual traversal.
2014 if (!strcmp(rev.pending.objects[0].name, "HEAD"))
2015 check_head = 1;
2017 if (check_head) {
2018 const char *ref, *v;
2019 ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2020 NULL, NULL);
2021 if (ref && skip_prefix(ref, "refs/heads/", &v))
2022 branch_name = xstrdup(v);
2023 else
2024 branch_name = xstrdup(""); /* no branch */
2029 * We cannot move this anywhere earlier because we do want to
2030 * know if --root was given explicitly from the command line.
2032 rev.show_root_diff = 1;
2034 if (ignore_if_in_upstream) {
2035 /* Don't say anything if head and upstream are the same. */
2036 if (rev.pending.nr == 2) {
2037 struct object_array_entry *o = rev.pending.objects;
2038 if (oideq(&o[0].item->oid, &o[1].item->oid))
2039 goto done;
2041 get_patch_ids(&rev, &ids);
2044 if (prepare_revision_walk(&rev))
2045 die(_("revision walk setup failed"));
2046 rev.boundary = 1;
2047 while ((commit = get_revision(&rev)) != NULL) {
2048 if (commit->object.flags & BOUNDARY) {
2049 boundary_count++;
2050 origin = (boundary_count == 1) ? commit : NULL;
2051 continue;
2054 if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
2055 continue;
2057 nr++;
2058 REALLOC_ARRAY(list, nr);
2059 list[nr - 1] = commit;
2061 if (nr == 0)
2062 /* nothing to do */
2063 goto done;
2064 total = nr;
2065 if (cover_letter == -1) {
2066 if (config_cover_letter == COVER_AUTO)
2067 cover_letter = (total > 1);
2068 else
2069 cover_letter = (config_cover_letter == COVER_ON);
2071 if (!keep_subject && auto_number && (total > 1 || cover_letter))
2072 numbered = 1;
2073 if (numbered)
2074 rev.total = total + start_number - 1;
2076 if (idiff_prev.nr) {
2077 if (!cover_letter && total != 1)
2078 die(_("--interdiff requires --cover-letter or single patch"));
2079 rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
2080 rev.idiff_oid2 = get_commit_tree_oid(list[0]);
2081 rev.idiff_title = diff_title(&idiff_title, reroll_count,
2082 _("Interdiff:"),
2083 _("Interdiff against v%d:"));
2086 if (creation_factor < 0)
2087 creation_factor = RANGE_DIFF_CREATION_FACTOR_DEFAULT;
2088 else if (!rdiff_prev)
2089 die(_("--creation-factor requires --range-diff"));
2091 if (rdiff_prev) {
2092 if (!cover_letter && total != 1)
2093 die(_("--range-diff requires --cover-letter or single patch"));
2095 infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
2096 origin, list[0]);
2097 rev.rdiff1 = rdiff1.buf;
2098 rev.rdiff2 = rdiff2.buf;
2099 rev.creation_factor = creation_factor;
2100 rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
2101 _("Range-diff:"),
2102 _("Range-diff against v%d:"));
2105 if (!signature) {
2106 ; /* --no-signature inhibits all signatures */
2107 } else if (signature && signature != git_version_string) {
2108 ; /* non-default signature already set */
2109 } else if (signature_file) {
2110 struct strbuf buf = STRBUF_INIT;
2112 if (strbuf_read_file(&buf, signature_file, 128) < 0)
2113 die_errno(_("unable to read signature file '%s'"), signature_file);
2114 signature = strbuf_detach(&buf, NULL);
2117 memset(&bases, 0, sizeof(bases));
2118 base = get_base_commit(base_commit, list, nr);
2119 if (base) {
2120 reset_revision_walk();
2121 clear_object_flags(UNINTERESTING);
2122 prepare_bases(&bases, base, list, nr);
2125 if (in_reply_to || thread || cover_letter)
2126 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
2127 if (in_reply_to) {
2128 const char *msgid = clean_message_id(in_reply_to);
2129 string_list_append(rev.ref_message_ids, msgid);
2131 rev.numbered_files = just_numbers;
2132 rev.patch_suffix = fmt_patch_suffix;
2133 if (cover_letter) {
2134 if (thread)
2135 gen_message_id(&rev, "cover");
2136 make_cover_letter(&rev, !!output_directory,
2137 origin, nr, list, branch_name, quiet);
2138 print_bases(&bases, rev.diffopt.file);
2139 print_signature(rev.diffopt.file);
2140 total++;
2141 start_number--;
2142 /* interdiff/range-diff in cover-letter; omit from patches */
2143 rev.idiff_oid1 = NULL;
2144 rev.rdiff1 = NULL;
2146 rev.add_signoff = do_signoff;
2148 if (show_progress)
2149 progress = start_delayed_progress(_("Generating patches"), total);
2150 while (0 <= --nr) {
2151 int shown;
2152 display_progress(progress, total - nr);
2153 commit = list[nr];
2154 rev.nr = total - nr + (start_number - 1);
2155 /* Make the second and subsequent mails replies to the first */
2156 if (thread) {
2157 /* Have we already had a message ID? */
2158 if (rev.message_id) {
2160 * For deep threading: make every mail
2161 * a reply to the previous one, no
2162 * matter what other options are set.
2164 * For shallow threading:
2166 * Without --cover-letter and
2167 * --in-reply-to, make every mail a
2168 * reply to the one before.
2170 * With --in-reply-to but no
2171 * --cover-letter, make every mail a
2172 * reply to the <reply-to>.
2174 * With --cover-letter, make every
2175 * mail but the cover letter a reply
2176 * to the cover letter. The cover
2177 * letter is a reply to the
2178 * --in-reply-to, if specified.
2180 if (thread == THREAD_SHALLOW
2181 && rev.ref_message_ids->nr > 0
2182 && (!cover_letter || rev.nr > 1))
2183 free(rev.message_id);
2184 else
2185 string_list_append(rev.ref_message_ids,
2186 rev.message_id);
2188 gen_message_id(&rev, oid_to_hex(&commit->object.oid));
2191 if (output_directory &&
2192 open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
2193 die(_("failed to create output files"));
2194 shown = log_tree_commit(&rev, commit);
2195 free_commit_buffer(the_repository->parsed_objects,
2196 commit);
2198 /* We put one extra blank line between formatted
2199 * patches and this flag is used by log-tree code
2200 * to see if it needs to emit a LF before showing
2201 * the log; when using one file per patch, we do
2202 * not want the extra blank line.
2204 if (output_directory)
2205 rev.shown_one = 0;
2206 if (shown) {
2207 print_bases(&bases, rev.diffopt.file);
2208 if (rev.mime_boundary)
2209 fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
2210 mime_boundary_leader,
2211 rev.mime_boundary);
2212 else
2213 print_signature(rev.diffopt.file);
2215 if (output_directory)
2216 fclose(rev.diffopt.file);
2218 stop_progress(&progress);
2219 free(list);
2220 free(branch_name);
2221 string_list_clear(&extra_to, 0);
2222 string_list_clear(&extra_cc, 0);
2223 string_list_clear(&extra_hdr, 0);
2224 if (ignore_if_in_upstream)
2225 free_patch_ids(&ids);
2227 done:
2228 oid_array_clear(&idiff_prev);
2229 strbuf_release(&idiff_title);
2230 strbuf_release(&rdiff1);
2231 strbuf_release(&rdiff2);
2232 strbuf_release(&rdiff_title);
2233 return 0;
2236 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
2238 struct object_id oid;
2239 if (get_oid(arg, &oid) == 0) {
2240 struct commit *commit = lookup_commit_reference(the_repository,
2241 &oid);
2242 if (commit) {
2243 commit->object.flags |= flags;
2244 add_pending_object(revs, &commit->object, arg);
2245 return 0;
2248 return -1;
2251 static const char * const cherry_usage[] = {
2252 N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
2253 NULL
2256 static void print_commit(char sign, struct commit *commit, int verbose,
2257 int abbrev, FILE *file)
2259 if (!verbose) {
2260 fprintf(file, "%c %s\n", sign,
2261 find_unique_abbrev(&commit->object.oid, abbrev));
2262 } else {
2263 struct strbuf buf = STRBUF_INIT;
2264 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2265 fprintf(file, "%c %s %s\n", sign,
2266 find_unique_abbrev(&commit->object.oid, abbrev),
2267 buf.buf);
2268 strbuf_release(&buf);
2272 int cmd_cherry(int argc, const char **argv, const char *prefix)
2274 struct rev_info revs;
2275 struct patch_ids ids;
2276 struct commit *commit;
2277 struct commit_list *list = NULL;
2278 struct branch *current_branch;
2279 const char *upstream;
2280 const char *head = "HEAD";
2281 const char *limit = NULL;
2282 int verbose = 0, abbrev = 0;
2284 struct option options[] = {
2285 OPT__ABBREV(&abbrev),
2286 OPT__VERBOSE(&verbose, N_("be verbose")),
2287 OPT_END()
2290 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
2292 switch (argc) {
2293 case 3:
2294 limit = argv[2];
2295 /* FALLTHROUGH */
2296 case 2:
2297 head = argv[1];
2298 /* FALLTHROUGH */
2299 case 1:
2300 upstream = argv[0];
2301 break;
2302 default:
2303 current_branch = branch_get(NULL);
2304 upstream = branch_get_upstream(current_branch, NULL);
2305 if (!upstream) {
2306 fprintf(stderr, _("Could not find a tracked"
2307 " remote branch, please"
2308 " specify <upstream> manually.\n"));
2309 usage_with_options(cherry_usage, options);
2313 repo_init_revisions(the_repository, &revs, prefix);
2314 revs.max_parents = 1;
2316 if (add_pending_commit(head, &revs, 0))
2317 die(_("unknown commit %s"), head);
2318 if (add_pending_commit(upstream, &revs, UNINTERESTING))
2319 die(_("unknown commit %s"), upstream);
2321 /* Don't say anything if head and upstream are the same. */
2322 if (revs.pending.nr == 2) {
2323 struct object_array_entry *o = revs.pending.objects;
2324 if (oideq(&o[0].item->oid, &o[1].item->oid))
2325 return 0;
2328 get_patch_ids(&revs, &ids);
2330 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2331 die(_("unknown commit %s"), limit);
2333 /* reverse the list of commits */
2334 if (prepare_revision_walk(&revs))
2335 die(_("revision walk setup failed"));
2336 while ((commit = get_revision(&revs)) != NULL) {
2337 commit_list_insert(commit, &list);
2340 while (list) {
2341 char sign = '+';
2343 commit = list->item;
2344 if (has_commit_patch_id(commit, &ids))
2345 sign = '-';
2346 print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2347 list = list->next;
2350 free_patch_ids(&ids);
2351 return 0;