The sixth batch
[git.git] / builtin / log.c
blob516a1142ddf0bc9bfb532612acf390ec2e4149ca
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.diffmerges"))
485 return diff_merges_config(value);
486 if (!strcmp(var, "log.showroot")) {
487 default_show_root = git_config_bool(var, value);
488 return 0;
490 if (!strcmp(var, "log.follow")) {
491 default_follow = git_config_bool(var, value);
492 return 0;
494 if (skip_prefix(var, "color.decorate.", &slot_name))
495 return parse_decorate_color_config(var, slot_name, value);
496 if (!strcmp(var, "log.mailmap")) {
497 use_mailmap_config = git_config_bool(var, value);
498 return 0;
500 if (!strcmp(var, "log.showsignature")) {
501 default_show_signature = git_config_bool(var, value);
502 return 0;
505 if (grep_config(var, value, cb) < 0)
506 return -1;
507 if (git_gpg_config(var, value, cb) < 0)
508 return -1;
509 return git_diff_ui_config(var, value, cb);
512 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
514 struct rev_info rev;
515 struct setup_revision_opt opt;
517 init_log_defaults();
518 git_config(git_log_config, NULL);
520 repo_init_revisions(the_repository, &rev, prefix);
521 rev.diff = 1;
522 rev.simplify_history = 0;
523 memset(&opt, 0, sizeof(opt));
524 opt.def = "HEAD";
525 opt.revarg_opt = REVARG_COMMITTISH;
526 cmd_log_init(argc, argv, prefix, &rev, &opt);
527 if (!rev.diffopt.output_format)
528 rev.diffopt.output_format = DIFF_FORMAT_RAW;
529 return cmd_log_walk(&rev);
532 static void show_tagger(const char *buf, struct rev_info *rev)
534 struct strbuf out = STRBUF_INIT;
535 struct pretty_print_context pp = {0};
537 pp.fmt = rev->commit_format;
538 pp.date_mode = rev->date_mode;
539 pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
540 fprintf(rev->diffopt.file, "%s", out.buf);
541 strbuf_release(&out);
544 static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
546 struct object_id oidc;
547 struct object_context obj_context;
548 char *buf;
549 unsigned long size;
551 fflush(rev->diffopt.file);
552 if (!rev->diffopt.flags.textconv_set_via_cmdline ||
553 !rev->diffopt.flags.allow_textconv)
554 return stream_blob_to_fd(1, oid, NULL, 0);
556 if (get_oid_with_context(the_repository, obj_name,
557 GET_OID_RECORD_PATH,
558 &oidc, &obj_context))
559 die(_("not a valid object name %s"), obj_name);
560 if (!obj_context.path ||
561 !textconv_object(the_repository, obj_context.path,
562 obj_context.mode, &oidc, 1, &buf, &size)) {
563 free(obj_context.path);
564 return stream_blob_to_fd(1, oid, NULL, 0);
567 if (!buf)
568 die(_("git show %s: bad file"), obj_name);
570 write_or_die(1, buf, size);
571 free(obj_context.path);
572 return 0;
575 static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
577 unsigned long size;
578 enum object_type type;
579 char *buf = read_object_file(oid, &type, &size);
580 int offset = 0;
582 if (!buf)
583 return error(_("could not read object %s"), oid_to_hex(oid));
585 assert(type == OBJ_TAG);
586 while (offset < size && buf[offset] != '\n') {
587 int new_offset = offset + 1;
588 const char *ident;
589 while (new_offset < size && buf[new_offset++] != '\n')
590 ; /* do nothing */
591 if (skip_prefix(buf + offset, "tagger ", &ident))
592 show_tagger(ident, rev);
593 offset = new_offset;
596 if (offset < size)
597 fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
598 free(buf);
599 return 0;
602 static int show_tree_object(const struct object_id *oid,
603 struct strbuf *base,
604 const char *pathname, unsigned mode, void *context)
606 FILE *file = context;
607 fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
608 return 0;
611 static void show_setup_revisions_tweak(struct rev_info *rev,
612 struct setup_revision_opt *opt)
614 if (rev->first_parent_only)
615 diff_merges_default_to_first_parent(rev);
616 else
617 diff_merges_default_to_dense_combined(rev);
618 if (!rev->diffopt.output_format)
619 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
622 int cmd_show(int argc, const char **argv, const char *prefix)
624 struct rev_info rev;
625 struct object_array_entry *objects;
626 struct setup_revision_opt opt;
627 struct pathspec match_all;
628 int i, count, ret = 0;
630 init_log_defaults();
631 git_config(git_log_config, NULL);
633 memset(&match_all, 0, sizeof(match_all));
634 repo_init_revisions(the_repository, &rev, prefix);
635 rev.diff = 1;
636 rev.always_show_header = 1;
637 rev.no_walk = REVISION_WALK_NO_WALK_SORTED;
638 rev.diffopt.stat_width = -1; /* Scale to real terminal size */
640 memset(&opt, 0, sizeof(opt));
641 opt.def = "HEAD";
642 opt.tweak = show_setup_revisions_tweak;
643 cmd_log_init(argc, argv, prefix, &rev, &opt);
645 if (!rev.no_walk)
646 return cmd_log_walk(&rev);
648 count = rev.pending.nr;
649 objects = rev.pending.objects;
650 for (i = 0; i < count && !ret; i++) {
651 struct object *o = objects[i].item;
652 const char *name = objects[i].name;
653 switch (o->type) {
654 case OBJ_BLOB:
655 ret = show_blob_object(&o->oid, &rev, name);
656 break;
657 case OBJ_TAG: {
658 struct tag *t = (struct tag *)o;
659 struct object_id *oid = get_tagged_oid(t);
661 if (rev.shown_one)
662 putchar('\n');
663 fprintf(rev.diffopt.file, "%stag %s%s\n",
664 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
665 t->tag,
666 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
667 ret = show_tag_object(&o->oid, &rev);
668 rev.shown_one = 1;
669 if (ret)
670 break;
671 o = parse_object(the_repository, oid);
672 if (!o)
673 ret = error(_("could not read object %s"),
674 oid_to_hex(oid));
675 objects[i].item = o;
676 i--;
677 break;
679 case OBJ_TREE:
680 if (rev.shown_one)
681 putchar('\n');
682 fprintf(rev.diffopt.file, "%stree %s%s\n\n",
683 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
684 name,
685 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
686 read_tree(the_repository, (struct tree *)o,
687 &match_all, show_tree_object,
688 rev.diffopt.file);
689 rev.shown_one = 1;
690 break;
691 case OBJ_COMMIT:
692 rev.pending.nr = rev.pending.alloc = 0;
693 rev.pending.objects = NULL;
694 add_object_array(o, name, &rev.pending);
695 ret = cmd_log_walk(&rev);
696 break;
697 default:
698 ret = error(_("unknown type: %d"), o->type);
701 free(objects);
702 return ret;
706 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
708 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
710 struct rev_info rev;
711 struct setup_revision_opt opt;
713 init_log_defaults();
714 git_config(git_log_config, NULL);
716 repo_init_revisions(the_repository, &rev, prefix);
717 init_reflog_walk(&rev.reflog_info);
718 rev.verbose_header = 1;
719 memset(&opt, 0, sizeof(opt));
720 opt.def = "HEAD";
721 cmd_log_init_defaults(&rev);
722 rev.abbrev_commit = 1;
723 rev.commit_format = CMIT_FMT_ONELINE;
724 rev.use_terminator = 1;
725 rev.always_show_header = 1;
726 cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
728 return cmd_log_walk(&rev);
731 static void log_setup_revisions_tweak(struct rev_info *rev,
732 struct setup_revision_opt *opt)
734 if (rev->diffopt.flags.default_follow_renames &&
735 rev->prune_data.nr == 1)
736 rev->diffopt.flags.follow_renames = 1;
738 if (rev->first_parent_only)
739 diff_merges_default_to_first_parent(rev);
742 int cmd_log(int argc, const char **argv, const char *prefix)
744 struct rev_info rev;
745 struct setup_revision_opt opt;
747 init_log_defaults();
748 git_config(git_log_config, NULL);
750 repo_init_revisions(the_repository, &rev, prefix);
751 rev.always_show_header = 1;
752 memset(&opt, 0, sizeof(opt));
753 opt.def = "HEAD";
754 opt.revarg_opt = REVARG_COMMITTISH;
755 opt.tweak = log_setup_revisions_tweak;
756 cmd_log_init(argc, argv, prefix, &rev, &opt);
757 return cmd_log_walk(&rev);
760 /* format-patch */
762 static const char *fmt_patch_suffix = ".patch";
763 static int numbered = 0;
764 static int auto_number = 1;
766 static char *default_attach = NULL;
768 static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
769 static struct string_list extra_to = STRING_LIST_INIT_NODUP;
770 static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
772 static void add_header(const char *value)
774 struct string_list_item *item;
775 int len = strlen(value);
776 while (len && value[len - 1] == '\n')
777 len--;
779 if (!strncasecmp(value, "to: ", 4)) {
780 item = string_list_append(&extra_to, value + 4);
781 len -= 4;
782 } else if (!strncasecmp(value, "cc: ", 4)) {
783 item = string_list_append(&extra_cc, value + 4);
784 len -= 4;
785 } else {
786 item = string_list_append(&extra_hdr, value);
789 item->string[len] = '\0';
792 enum cover_setting {
793 COVER_UNSET,
794 COVER_OFF,
795 COVER_ON,
796 COVER_AUTO
799 enum thread_level {
800 THREAD_UNSET,
801 THREAD_SHALLOW,
802 THREAD_DEEP
805 enum cover_from_description {
806 COVER_FROM_NONE,
807 COVER_FROM_MESSAGE,
808 COVER_FROM_SUBJECT,
809 COVER_FROM_AUTO
812 enum auto_base_setting {
813 AUTO_BASE_NEVER,
814 AUTO_BASE_ALWAYS,
815 AUTO_BASE_WHEN_ABLE
818 static enum thread_level thread;
819 static int do_signoff;
820 static enum auto_base_setting auto_base;
821 static char *from;
822 static const char *signature = git_version_string;
823 static const char *signature_file;
824 static enum cover_setting config_cover_letter;
825 static const char *config_output_directory;
826 static enum cover_from_description cover_from_description_mode = COVER_FROM_MESSAGE;
827 static int show_notes;
828 static struct display_notes_opt notes_opt;
830 static enum cover_from_description parse_cover_from_description(const char *arg)
832 if (!arg || !strcmp(arg, "default"))
833 return COVER_FROM_MESSAGE;
834 else if (!strcmp(arg, "none"))
835 return COVER_FROM_NONE;
836 else if (!strcmp(arg, "message"))
837 return COVER_FROM_MESSAGE;
838 else if (!strcmp(arg, "subject"))
839 return COVER_FROM_SUBJECT;
840 else if (!strcmp(arg, "auto"))
841 return COVER_FROM_AUTO;
842 else
843 die(_("%s: invalid cover from description mode"), arg);
846 static int git_format_config(const char *var, const char *value, void *cb)
848 if (!strcmp(var, "format.headers")) {
849 if (!value)
850 die(_("format.headers without value"));
851 add_header(value);
852 return 0;
854 if (!strcmp(var, "format.suffix"))
855 return git_config_string(&fmt_patch_suffix, var, value);
856 if (!strcmp(var, "format.to")) {
857 if (!value)
858 return config_error_nonbool(var);
859 string_list_append(&extra_to, value);
860 return 0;
862 if (!strcmp(var, "format.cc")) {
863 if (!value)
864 return config_error_nonbool(var);
865 string_list_append(&extra_cc, value);
866 return 0;
868 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
869 !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
870 return 0;
872 if (!strcmp(var, "format.numbered")) {
873 if (value && !strcasecmp(value, "auto")) {
874 auto_number = 1;
875 return 0;
877 numbered = git_config_bool(var, value);
878 auto_number = auto_number && numbered;
879 return 0;
881 if (!strcmp(var, "format.attach")) {
882 if (value && *value)
883 default_attach = xstrdup(value);
884 else
885 default_attach = xstrdup(git_version_string);
886 return 0;
888 if (!strcmp(var, "format.thread")) {
889 if (value && !strcasecmp(value, "deep")) {
890 thread = THREAD_DEEP;
891 return 0;
893 if (value && !strcasecmp(value, "shallow")) {
894 thread = THREAD_SHALLOW;
895 return 0;
897 thread = git_config_bool(var, value) ? THREAD_SHALLOW : THREAD_UNSET;
898 return 0;
900 if (!strcmp(var, "format.signoff")) {
901 do_signoff = git_config_bool(var, value);
902 return 0;
904 if (!strcmp(var, "format.signature"))
905 return git_config_string(&signature, var, value);
906 if (!strcmp(var, "format.signaturefile"))
907 return git_config_pathname(&signature_file, var, value);
908 if (!strcmp(var, "format.coverletter")) {
909 if (value && !strcasecmp(value, "auto")) {
910 config_cover_letter = COVER_AUTO;
911 return 0;
913 config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
914 return 0;
916 if (!strcmp(var, "format.outputdirectory"))
917 return git_config_string(&config_output_directory, var, value);
918 if (!strcmp(var, "format.useautobase")) {
919 if (value && !strcasecmp(value, "whenAble")) {
920 auto_base = AUTO_BASE_WHEN_ABLE;
921 return 0;
923 auto_base = git_config_bool(var, value) ? AUTO_BASE_ALWAYS : AUTO_BASE_NEVER;
924 return 0;
926 if (!strcmp(var, "format.from")) {
927 int b = git_parse_maybe_bool(value);
928 free(from);
929 if (b < 0)
930 from = xstrdup(value);
931 else if (b)
932 from = xstrdup(git_committer_info(IDENT_NO_DATE));
933 else
934 from = NULL;
935 return 0;
937 if (!strcmp(var, "format.notes")) {
938 int b = git_parse_maybe_bool(value);
939 if (b < 0)
940 enable_ref_display_notes(&notes_opt, &show_notes, value);
941 else if (b)
942 enable_default_display_notes(&notes_opt, &show_notes);
943 else
944 disable_display_notes(&notes_opt, &show_notes);
945 return 0;
947 if (!strcmp(var, "format.coverfromdescription")) {
948 cover_from_description_mode = parse_cover_from_description(value);
949 return 0;
952 return git_log_config(var, value, cb);
955 static const char *output_directory = NULL;
956 static int outdir_offset;
958 static int open_next_file(struct commit *commit, const char *subject,
959 struct rev_info *rev, int quiet)
961 struct strbuf filename = STRBUF_INIT;
963 if (output_directory) {
964 strbuf_addstr(&filename, output_directory);
965 strbuf_complete(&filename, '/');
968 if (rev->numbered_files)
969 strbuf_addf(&filename, "%d", rev->nr);
970 else if (commit)
971 fmt_output_commit(&filename, commit, rev);
972 else
973 fmt_output_subject(&filename, subject, rev);
975 if (!quiet)
976 printf("%s\n", filename.buf + outdir_offset);
978 if ((rev->diffopt.file = fopen(filename.buf, "w")) == NULL) {
979 error_errno(_("cannot open patch file %s"), filename.buf);
980 strbuf_release(&filename);
981 return -1;
984 strbuf_release(&filename);
985 return 0;
988 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
990 struct rev_info check_rev;
991 struct commit *commit, *c1, *c2;
992 struct object *o1, *o2;
993 unsigned flags1, flags2;
995 if (rev->pending.nr != 2)
996 die(_("need exactly one range"));
998 o1 = rev->pending.objects[0].item;
999 o2 = rev->pending.objects[1].item;
1000 flags1 = o1->flags;
1001 flags2 = o2->flags;
1002 c1 = lookup_commit_reference(the_repository, &o1->oid);
1003 c2 = lookup_commit_reference(the_repository, &o2->oid);
1005 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
1006 die(_("not a range"));
1008 init_patch_ids(the_repository, ids);
1010 /* given a range a..b get all patch ids for b..a */
1011 repo_init_revisions(the_repository, &check_rev, rev->prefix);
1012 check_rev.max_parents = 1;
1013 o1->flags ^= UNINTERESTING;
1014 o2->flags ^= UNINTERESTING;
1015 add_pending_object(&check_rev, o1, "o1");
1016 add_pending_object(&check_rev, o2, "o2");
1017 if (prepare_revision_walk(&check_rev))
1018 die(_("revision walk setup failed"));
1020 while ((commit = get_revision(&check_rev)) != NULL) {
1021 add_commit_patch_id(commit, ids);
1024 /* reset for next revision walk */
1025 clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
1026 clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
1027 o1->flags = flags1;
1028 o2->flags = flags2;
1031 static void gen_message_id(struct rev_info *info, char *base)
1033 struct strbuf buf = STRBUF_INIT;
1034 strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
1035 (timestamp_t) time(NULL),
1036 git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
1037 info->message_id = strbuf_detach(&buf, NULL);
1040 static void print_signature(FILE *file)
1042 if (!signature || !*signature)
1043 return;
1045 fprintf(file, "-- \n%s", signature);
1046 if (signature[strlen(signature)-1] != '\n')
1047 putc('\n', file);
1048 putc('\n', file);
1051 static char *find_branch_name(struct rev_info *rev)
1053 int i, positive = -1;
1054 struct object_id branch_oid;
1055 const struct object_id *tip_oid;
1056 const char *ref, *v;
1057 char *full_ref, *branch = NULL;
1059 for (i = 0; i < rev->cmdline.nr; i++) {
1060 if (rev->cmdline.rev[i].flags & UNINTERESTING)
1061 continue;
1062 if (positive < 0)
1063 positive = i;
1064 else
1065 return NULL;
1067 if (positive < 0)
1068 return NULL;
1069 ref = rev->cmdline.rev[positive].name;
1070 tip_oid = &rev->cmdline.rev[positive].item->oid;
1071 if (dwim_ref(ref, strlen(ref), &branch_oid, &full_ref, 0) &&
1072 skip_prefix(full_ref, "refs/heads/", &v) &&
1073 oideq(tip_oid, &branch_oid))
1074 branch = xstrdup(v);
1075 free(full_ref);
1076 return branch;
1079 static void show_diffstat(struct rev_info *rev,
1080 struct commit *origin, struct commit *head)
1082 struct diff_options opts;
1084 memcpy(&opts, &rev->diffopt, sizeof(opts));
1085 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1086 diff_setup_done(&opts);
1088 diff_tree_oid(get_commit_tree_oid(origin),
1089 get_commit_tree_oid(head),
1090 "", &opts);
1091 diffcore_std(&opts);
1092 diff_flush(&opts);
1094 fprintf(rev->diffopt.file, "\n");
1097 static void prepare_cover_text(struct pretty_print_context *pp,
1098 const char *branch_name,
1099 struct strbuf *sb,
1100 const char *encoding,
1101 int need_8bit_cte)
1103 const char *subject = "*** SUBJECT HERE ***";
1104 const char *body = "*** BLURB HERE ***";
1105 struct strbuf description_sb = STRBUF_INIT;
1106 struct strbuf subject_sb = STRBUF_INIT;
1108 if (cover_from_description_mode == COVER_FROM_NONE)
1109 goto do_pp;
1111 if (branch_name && *branch_name)
1112 read_branch_desc(&description_sb, branch_name);
1113 if (!description_sb.len)
1114 goto do_pp;
1116 if (cover_from_description_mode == COVER_FROM_SUBJECT ||
1117 cover_from_description_mode == COVER_FROM_AUTO)
1118 body = format_subject(&subject_sb, description_sb.buf, " ");
1120 if (cover_from_description_mode == COVER_FROM_MESSAGE ||
1121 (cover_from_description_mode == COVER_FROM_AUTO &&
1122 subject_sb.len > COVER_FROM_AUTO_MAX_SUBJECT_LEN))
1123 body = description_sb.buf;
1124 else
1125 subject = subject_sb.buf;
1127 do_pp:
1128 pp_title_line(pp, &subject, sb, encoding, need_8bit_cte);
1129 pp_remainder(pp, &body, sb, 0);
1131 strbuf_release(&description_sb);
1132 strbuf_release(&subject_sb);
1135 static int get_notes_refs(struct string_list_item *item, void *arg)
1137 strvec_pushf(arg, "--notes=%s", item->string);
1138 return 0;
1141 static void get_notes_args(struct strvec *arg, struct rev_info *rev)
1143 if (!rev->show_notes) {
1144 strvec_push(arg, "--no-notes");
1145 } else if (rev->notes_opt.use_default_notes > 0 ||
1146 (rev->notes_opt.use_default_notes == -1 &&
1147 !rev->notes_opt.extra_notes_refs.nr)) {
1148 strvec_push(arg, "--notes");
1149 } else {
1150 for_each_string_list(&rev->notes_opt.extra_notes_refs, get_notes_refs, arg);
1154 static void make_cover_letter(struct rev_info *rev, int use_separate_file,
1155 struct commit *origin,
1156 int nr, struct commit **list,
1157 const char *branch_name,
1158 int quiet)
1160 const char *committer;
1161 struct shortlog log;
1162 struct strbuf sb = STRBUF_INIT;
1163 int i;
1164 const char *encoding = "UTF-8";
1165 int need_8bit_cte = 0;
1166 struct pretty_print_context pp = {0};
1167 struct commit *head = list[0];
1169 if (!cmit_fmt_is_mail(rev->commit_format))
1170 die(_("cover letter needs email format"));
1172 committer = git_committer_info(0);
1174 if (use_separate_file &&
1175 open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1176 die(_("failed to create cover-letter file"));
1178 log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1180 for (i = 0; !need_8bit_cte && i < nr; i++) {
1181 const char *buf = get_commit_buffer(list[i], NULL);
1182 if (has_non_ascii(buf))
1183 need_8bit_cte = 1;
1184 unuse_commit_buffer(list[i], buf);
1187 if (!branch_name)
1188 branch_name = find_branch_name(rev);
1190 pp.fmt = CMIT_FMT_EMAIL;
1191 pp.date_mode.type = DATE_RFC2822;
1192 pp.rev = rev;
1193 pp.print_email_subject = 1;
1194 pp_user_info(&pp, NULL, &sb, committer, encoding);
1195 prepare_cover_text(&pp, branch_name, &sb, encoding, need_8bit_cte);
1196 fprintf(rev->diffopt.file, "%s\n", sb.buf);
1198 strbuf_release(&sb);
1200 shortlog_init(&log);
1201 log.wrap_lines = 1;
1202 log.wrap = MAIL_DEFAULT_WRAP;
1203 log.in1 = 2;
1204 log.in2 = 4;
1205 log.file = rev->diffopt.file;
1206 log.groups = SHORTLOG_GROUP_AUTHOR;
1207 for (i = 0; i < nr; i++)
1208 shortlog_add_commit(&log, list[i]);
1210 shortlog_output(&log);
1212 /* We can only do diffstat with a unique reference point */
1213 if (origin)
1214 show_diffstat(rev, origin, head);
1216 if (rev->idiff_oid1) {
1217 fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1218 show_interdiff(rev->idiff_oid1, rev->idiff_oid2, 0,
1219 &rev->diffopt);
1222 if (rev->rdiff1) {
1224 * Pass minimum required diff-options to range-diff; others
1225 * can be added later if deemed desirable.
1227 struct diff_options opts;
1228 struct strvec other_arg = STRVEC_INIT;
1229 struct range_diff_options range_diff_opts = {
1230 .creation_factor = rev->creation_factor,
1231 .dual_color = 1,
1232 .diffopt = &opts,
1233 .other_arg = &other_arg
1236 diff_setup(&opts);
1237 opts.file = rev->diffopt.file;
1238 opts.use_color = rev->diffopt.use_color;
1239 diff_setup_done(&opts);
1240 fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1241 get_notes_args(&other_arg, rev);
1242 show_range_diff(rev->rdiff1, rev->rdiff2, &range_diff_opts);
1243 strvec_clear(&other_arg);
1247 static const char *clean_message_id(const char *msg_id)
1249 char ch;
1250 const char *a, *z, *m;
1252 m = msg_id;
1253 while ((ch = *m) && (isspace(ch) || (ch == '<')))
1254 m++;
1255 a = m;
1256 z = NULL;
1257 while ((ch = *m)) {
1258 if (!isspace(ch) && (ch != '>'))
1259 z = m;
1260 m++;
1262 if (!z)
1263 die(_("insane in-reply-to: %s"), msg_id);
1264 if (++z == m)
1265 return a;
1266 return xmemdupz(a, z - a);
1269 static const char *set_outdir(const char *prefix, const char *output_directory)
1271 if (output_directory && is_absolute_path(output_directory))
1272 return output_directory;
1274 if (!prefix || !*prefix) {
1275 if (output_directory)
1276 return output_directory;
1277 /* The user did not explicitly ask for "./" */
1278 outdir_offset = 2;
1279 return "./";
1282 outdir_offset = strlen(prefix);
1283 if (!output_directory)
1284 return prefix;
1286 return prefix_filename(prefix, output_directory);
1289 static const char * const builtin_format_patch_usage[] = {
1290 N_("git format-patch [<options>] [<since> | <revision-range>]"),
1291 NULL
1294 static int keep_subject = 0;
1296 static int keep_callback(const struct option *opt, const char *arg, int unset)
1298 BUG_ON_OPT_NEG(unset);
1299 BUG_ON_OPT_ARG(arg);
1300 ((struct rev_info *)opt->value)->total = -1;
1301 keep_subject = 1;
1302 return 0;
1305 static int subject_prefix = 0;
1307 static int subject_prefix_callback(const struct option *opt, const char *arg,
1308 int unset)
1310 BUG_ON_OPT_NEG(unset);
1311 subject_prefix = 1;
1312 ((struct rev_info *)opt->value)->subject_prefix = arg;
1313 return 0;
1316 static int rfc_callback(const struct option *opt, const char *arg, int unset)
1318 BUG_ON_OPT_NEG(unset);
1319 BUG_ON_OPT_ARG(arg);
1320 return subject_prefix_callback(opt, "RFC PATCH", unset);
1323 static int numbered_cmdline_opt = 0;
1325 static int numbered_callback(const struct option *opt, const char *arg,
1326 int unset)
1328 BUG_ON_OPT_ARG(arg);
1329 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1330 if (unset)
1331 auto_number = 0;
1332 return 0;
1335 static int no_numbered_callback(const struct option *opt, const char *arg,
1336 int unset)
1338 BUG_ON_OPT_NEG(unset);
1339 return numbered_callback(opt, arg, 1);
1342 static int output_directory_callback(const struct option *opt, const char *arg,
1343 int unset)
1345 const char **dir = (const char **)opt->value;
1346 BUG_ON_OPT_NEG(unset);
1347 if (*dir)
1348 die(_("two output directories?"));
1349 *dir = arg;
1350 return 0;
1353 static int thread_callback(const struct option *opt, const char *arg, int unset)
1355 enum thread_level *thread = (enum thread_level *)opt->value;
1356 if (unset)
1357 *thread = THREAD_UNSET;
1358 else if (!arg || !strcmp(arg, "shallow"))
1359 *thread = THREAD_SHALLOW;
1360 else if (!strcmp(arg, "deep"))
1361 *thread = THREAD_DEEP;
1363 * Please update _git_formatpatch() in git-completion.bash
1364 * when you add new options.
1366 else
1367 return 1;
1368 return 0;
1371 static int attach_callback(const struct option *opt, const char *arg, int unset)
1373 struct rev_info *rev = (struct rev_info *)opt->value;
1374 if (unset)
1375 rev->mime_boundary = NULL;
1376 else if (arg)
1377 rev->mime_boundary = arg;
1378 else
1379 rev->mime_boundary = git_version_string;
1380 rev->no_inline = unset ? 0 : 1;
1381 return 0;
1384 static int inline_callback(const struct option *opt, const char *arg, int unset)
1386 struct rev_info *rev = (struct rev_info *)opt->value;
1387 if (unset)
1388 rev->mime_boundary = NULL;
1389 else if (arg)
1390 rev->mime_boundary = arg;
1391 else
1392 rev->mime_boundary = git_version_string;
1393 rev->no_inline = 0;
1394 return 0;
1397 static int header_callback(const struct option *opt, const char *arg, int unset)
1399 if (unset) {
1400 string_list_clear(&extra_hdr, 0);
1401 string_list_clear(&extra_to, 0);
1402 string_list_clear(&extra_cc, 0);
1403 } else {
1404 add_header(arg);
1406 return 0;
1409 static int to_callback(const struct option *opt, const char *arg, int unset)
1411 if (unset)
1412 string_list_clear(&extra_to, 0);
1413 else
1414 string_list_append(&extra_to, arg);
1415 return 0;
1418 static int cc_callback(const struct option *opt, const char *arg, int unset)
1420 if (unset)
1421 string_list_clear(&extra_cc, 0);
1422 else
1423 string_list_append(&extra_cc, arg);
1424 return 0;
1427 static int from_callback(const struct option *opt, const char *arg, int unset)
1429 char **from = opt->value;
1431 free(*from);
1433 if (unset)
1434 *from = NULL;
1435 else if (arg)
1436 *from = xstrdup(arg);
1437 else
1438 *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1439 return 0;
1442 static int base_callback(const struct option *opt, const char *arg, int unset)
1444 const char **base_commit = opt->value;
1446 if (unset) {
1447 auto_base = AUTO_BASE_NEVER;
1448 *base_commit = NULL;
1449 } else if (!strcmp(arg, "auto")) {
1450 auto_base = AUTO_BASE_ALWAYS;
1451 *base_commit = NULL;
1452 } else {
1453 auto_base = AUTO_BASE_NEVER;
1454 *base_commit = arg;
1456 return 0;
1459 struct base_tree_info {
1460 struct object_id base_commit;
1461 int nr_patch_id, alloc_patch_id;
1462 struct object_id *patch_id;
1465 static struct commit *get_base_commit(const char *base_commit,
1466 struct commit **list,
1467 int total)
1469 struct commit *base = NULL;
1470 struct commit **rev;
1471 int i = 0, rev_nr = 0, auto_select, die_on_failure;
1473 switch (auto_base) {
1474 case AUTO_BASE_NEVER:
1475 if (base_commit) {
1476 auto_select = 0;
1477 die_on_failure = 1;
1478 } else {
1479 /* no base information is requested */
1480 return NULL;
1482 break;
1483 case AUTO_BASE_ALWAYS:
1484 case AUTO_BASE_WHEN_ABLE:
1485 if (base_commit) {
1486 BUG("requested automatic base selection but a commit was provided");
1487 } else {
1488 auto_select = 1;
1489 die_on_failure = auto_base == AUTO_BASE_ALWAYS;
1491 break;
1492 default:
1493 BUG("unexpected automatic base selection method");
1496 if (!auto_select) {
1497 base = lookup_commit_reference_by_name(base_commit);
1498 if (!base)
1499 die(_("unknown commit %s"), base_commit);
1500 } else {
1501 struct branch *curr_branch = branch_get(NULL);
1502 const char *upstream = branch_get_upstream(curr_branch, NULL);
1503 if (upstream) {
1504 struct commit_list *base_list;
1505 struct commit *commit;
1506 struct object_id oid;
1508 if (get_oid(upstream, &oid)) {
1509 if (die_on_failure)
1510 die(_("failed to resolve '%s' as a valid ref"), upstream);
1511 else
1512 return NULL;
1514 commit = lookup_commit_or_die(&oid, "upstream base");
1515 base_list = get_merge_bases_many(commit, total, list);
1516 /* There should be one and only one merge base. */
1517 if (!base_list || base_list->next) {
1518 if (die_on_failure) {
1519 die(_("could not find exact merge base"));
1520 } else {
1521 free_commit_list(base_list);
1522 return NULL;
1525 base = base_list->item;
1526 free_commit_list(base_list);
1527 } else {
1528 if (die_on_failure)
1529 die(_("failed to get upstream, if you want to record base commit automatically,\n"
1530 "please use git branch --set-upstream-to to track a remote branch.\n"
1531 "Or you could specify base commit by --base=<base-commit-id> manually"));
1532 else
1533 return NULL;
1537 ALLOC_ARRAY(rev, total);
1538 for (i = 0; i < total; i++)
1539 rev[i] = list[i];
1541 rev_nr = total;
1543 * Get merge base through pair-wise computations
1544 * and store it in rev[0].
1546 while (rev_nr > 1) {
1547 for (i = 0; i < rev_nr / 2; i++) {
1548 struct commit_list *merge_base;
1549 merge_base = get_merge_bases(rev[2 * i], rev[2 * i + 1]);
1550 if (!merge_base || merge_base->next) {
1551 if (die_on_failure) {
1552 die(_("failed to find exact merge base"));
1553 } else {
1554 free(rev);
1555 return NULL;
1559 rev[i] = merge_base->item;
1562 if (rev_nr % 2)
1563 rev[i] = rev[2 * i];
1564 rev_nr = DIV_ROUND_UP(rev_nr, 2);
1567 if (!in_merge_bases(base, rev[0])) {
1568 if (die_on_failure) {
1569 die(_("base commit should be the ancestor of revision list"));
1570 } else {
1571 free(rev);
1572 return NULL;
1576 for (i = 0; i < total; i++) {
1577 if (base == list[i]) {
1578 if (die_on_failure) {
1579 die(_("base commit shouldn't be in revision list"));
1580 } else {
1581 free(rev);
1582 return NULL;
1587 free(rev);
1588 return base;
1591 define_commit_slab(commit_base, int);
1593 static void prepare_bases(struct base_tree_info *bases,
1594 struct commit *base,
1595 struct commit **list,
1596 int total)
1598 struct commit *commit;
1599 struct rev_info revs;
1600 struct diff_options diffopt;
1601 struct commit_base commit_base;
1602 int i;
1604 if (!base)
1605 return;
1607 init_commit_base(&commit_base);
1608 repo_diff_setup(the_repository, &diffopt);
1609 diffopt.flags.recursive = 1;
1610 diff_setup_done(&diffopt);
1612 oidcpy(&bases->base_commit, &base->object.oid);
1614 repo_init_revisions(the_repository, &revs, NULL);
1615 revs.max_parents = 1;
1616 revs.topo_order = 1;
1617 for (i = 0; i < total; i++) {
1618 list[i]->object.flags &= ~UNINTERESTING;
1619 add_pending_object(&revs, &list[i]->object, "rev_list");
1620 *commit_base_at(&commit_base, list[i]) = 1;
1622 base->object.flags |= UNINTERESTING;
1623 add_pending_object(&revs, &base->object, "base");
1625 if (prepare_revision_walk(&revs))
1626 die(_("revision walk setup failed"));
1628 * Traverse the commits list, get prerequisite patch ids
1629 * and stuff them in bases structure.
1631 while ((commit = get_revision(&revs)) != NULL) {
1632 struct object_id oid;
1633 struct object_id *patch_id;
1634 if (*commit_base_at(&commit_base, commit))
1635 continue;
1636 if (commit_patch_id(commit, &diffopt, &oid, 0, 1))
1637 die(_("cannot get patch id"));
1638 ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1639 patch_id = bases->patch_id + bases->nr_patch_id;
1640 oidcpy(patch_id, &oid);
1641 bases->nr_patch_id++;
1643 clear_commit_base(&commit_base);
1646 static void print_bases(struct base_tree_info *bases, FILE *file)
1648 int i;
1650 /* Only do this once, either for the cover or for the first one */
1651 if (is_null_oid(&bases->base_commit))
1652 return;
1654 /* Show the base commit */
1655 fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1657 /* Show the prerequisite patches */
1658 for (i = bases->nr_patch_id - 1; i >= 0; i--)
1659 fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1661 free(bases->patch_id);
1662 bases->nr_patch_id = 0;
1663 bases->alloc_patch_id = 0;
1664 oidclr(&bases->base_commit);
1667 static const char *diff_title(struct strbuf *sb,
1668 const char *reroll_count,
1669 const char *generic,
1670 const char *rerolled)
1672 int v;
1674 /* RFC may be v0, so allow -v1 to diff against v0 */
1675 if (reroll_count && !strtol_i(reroll_count, 10, &v) &&
1676 v >= 1)
1677 strbuf_addf(sb, rerolled, v - 1);
1678 else
1679 strbuf_addstr(sb, generic);
1680 return sb->buf;
1683 static void infer_range_diff_ranges(struct strbuf *r1,
1684 struct strbuf *r2,
1685 const char *prev,
1686 struct commit *origin,
1687 struct commit *head)
1689 const char *head_oid = oid_to_hex(&head->object.oid);
1690 int prev_is_range = is_range_diff_range(prev);
1692 if (prev_is_range)
1693 strbuf_addstr(r1, prev);
1694 else
1695 strbuf_addf(r1, "%s..%s", head_oid, prev);
1697 if (origin)
1698 strbuf_addf(r2, "%s..%s", oid_to_hex(&origin->object.oid), head_oid);
1699 else if (prev_is_range)
1700 die(_("failed to infer range-diff origin of current series"));
1701 else {
1702 warning(_("using '%s' as range-diff origin of current series"), prev);
1703 strbuf_addf(r2, "%s..%s", prev, head_oid);
1707 int cmd_format_patch(int argc, const char **argv, const char *prefix)
1709 struct commit *commit;
1710 struct commit **list = NULL;
1711 struct rev_info rev;
1712 struct setup_revision_opt s_r_opt;
1713 int nr = 0, total, i;
1714 int use_stdout = 0;
1715 int start_number = -1;
1716 int just_numbers = 0;
1717 int ignore_if_in_upstream = 0;
1718 int cover_letter = -1;
1719 int boundary_count = 0;
1720 int no_binary_diff = 0;
1721 int zero_commit = 0;
1722 struct commit *origin = NULL;
1723 const char *in_reply_to = NULL;
1724 struct patch_ids ids;
1725 struct strbuf buf = STRBUF_INIT;
1726 int use_patch_format = 0;
1727 int quiet = 0;
1728 const char *reroll_count = NULL;
1729 char *cover_from_description_arg = NULL;
1730 char *branch_name = NULL;
1731 char *base_commit = NULL;
1732 struct base_tree_info bases;
1733 struct commit *base;
1734 int show_progress = 0;
1735 struct progress *progress = NULL;
1736 struct oid_array idiff_prev = OID_ARRAY_INIT;
1737 struct strbuf idiff_title = STRBUF_INIT;
1738 const char *rdiff_prev = NULL;
1739 struct strbuf rdiff1 = STRBUF_INIT;
1740 struct strbuf rdiff2 = STRBUF_INIT;
1741 struct strbuf rdiff_title = STRBUF_INIT;
1742 int creation_factor = -1;
1744 const struct option builtin_format_patch_options[] = {
1745 OPT_CALLBACK_F('n', "numbered", &numbered, NULL,
1746 N_("use [PATCH n/m] even with a single patch"),
1747 PARSE_OPT_NOARG, numbered_callback),
1748 OPT_CALLBACK_F('N', "no-numbered", &numbered, NULL,
1749 N_("use [PATCH] even with multiple patches"),
1750 PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback),
1751 OPT_BOOL('s', "signoff", &do_signoff, N_("add a Signed-off-by trailer")),
1752 OPT_BOOL(0, "stdout", &use_stdout,
1753 N_("print patches to standard out")),
1754 OPT_BOOL(0, "cover-letter", &cover_letter,
1755 N_("generate a cover letter")),
1756 OPT_BOOL(0, "numbered-files", &just_numbers,
1757 N_("use simple number sequence for output file names")),
1758 OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
1759 N_("use <sfx> instead of '.patch'")),
1760 OPT_INTEGER(0, "start-number", &start_number,
1761 N_("start numbering patches at <n> instead of 1")),
1762 OPT_STRING('v', "reroll-count", &reroll_count, N_("reroll-count"),
1763 N_("mark the series as Nth re-roll")),
1764 OPT_INTEGER(0, "filename-max-length", &fmt_patch_name_max,
1765 N_("max length of output filename")),
1766 OPT_CALLBACK_F(0, "rfc", &rev, NULL,
1767 N_("use [RFC PATCH] instead of [PATCH]"),
1768 PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback),
1769 OPT_STRING(0, "cover-from-description", &cover_from_description_arg,
1770 N_("cover-from-description-mode"),
1771 N_("generate parts of a cover letter based on a branch's description")),
1772 OPT_CALLBACK_F(0, "subject-prefix", &rev, N_("prefix"),
1773 N_("use [<prefix>] instead of [PATCH]"),
1774 PARSE_OPT_NONEG, subject_prefix_callback),
1775 OPT_CALLBACK_F('o', "output-directory", &output_directory,
1776 N_("dir"), N_("store resulting files in <dir>"),
1777 PARSE_OPT_NONEG, output_directory_callback),
1778 OPT_CALLBACK_F('k', "keep-subject", &rev, NULL,
1779 N_("don't strip/add [PATCH]"),
1780 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback),
1781 OPT_BOOL(0, "no-binary", &no_binary_diff,
1782 N_("don't output binary diffs")),
1783 OPT_BOOL(0, "zero-commit", &zero_commit,
1784 N_("output all-zero hash in From header")),
1785 OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1786 N_("don't include a patch matching a commit upstream")),
1787 OPT_SET_INT_F('p', "no-stat", &use_patch_format,
1788 N_("show patch format instead of default (patch + stat)"),
1789 1, PARSE_OPT_NONEG),
1790 OPT_GROUP(N_("Messaging")),
1791 OPT_CALLBACK(0, "add-header", NULL, N_("header"),
1792 N_("add email header"), header_callback),
1793 OPT_CALLBACK(0, "to", NULL, N_("email"), N_("add To: header"), to_callback),
1794 OPT_CALLBACK(0, "cc", NULL, N_("email"), N_("add Cc: header"), cc_callback),
1795 OPT_CALLBACK_F(0, "from", &from, N_("ident"),
1796 N_("set From address to <ident> (or committer ident if absent)"),
1797 PARSE_OPT_OPTARG, from_callback),
1798 OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
1799 N_("make first mail a reply to <message-id>")),
1800 OPT_CALLBACK_F(0, "attach", &rev, N_("boundary"),
1801 N_("attach the patch"), PARSE_OPT_OPTARG,
1802 attach_callback),
1803 OPT_CALLBACK_F(0, "inline", &rev, N_("boundary"),
1804 N_("inline the patch"),
1805 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1806 inline_callback),
1807 OPT_CALLBACK_F(0, "thread", &thread, N_("style"),
1808 N_("enable message threading, styles: shallow, deep"),
1809 PARSE_OPT_OPTARG, thread_callback),
1810 OPT_STRING(0, "signature", &signature, N_("signature"),
1811 N_("add a signature")),
1812 OPT_CALLBACK_F(0, "base", &base_commit, N_("base-commit"),
1813 N_("add prerequisite tree info to the patch series"),
1814 0, base_callback),
1815 OPT_FILENAME(0, "signature-file", &signature_file,
1816 N_("add a signature from a file")),
1817 OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1818 OPT_BOOL(0, "progress", &show_progress,
1819 N_("show progress while generating patches")),
1820 OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
1821 N_("show changes against <rev> in cover letter or single patch"),
1822 parse_opt_object_name),
1823 OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
1824 N_("show changes against <refspec> in cover letter or single patch")),
1825 OPT_INTEGER(0, "creation-factor", &creation_factor,
1826 N_("percentage by which creation is weighted")),
1827 OPT_END()
1830 extra_hdr.strdup_strings = 1;
1831 extra_to.strdup_strings = 1;
1832 extra_cc.strdup_strings = 1;
1833 init_log_defaults();
1834 init_display_notes(&notes_opt);
1835 git_config(git_format_config, NULL);
1836 repo_init_revisions(the_repository, &rev, prefix);
1837 rev.show_notes = show_notes;
1838 memcpy(&rev.notes_opt, &notes_opt, sizeof(notes_opt));
1839 rev.commit_format = CMIT_FMT_EMAIL;
1840 rev.encode_email_headers = default_encode_email_headers;
1841 rev.expand_tabs_in_log_default = 0;
1842 rev.verbose_header = 1;
1843 rev.diff = 1;
1844 rev.max_parents = 1;
1845 rev.diffopt.flags.recursive = 1;
1846 rev.subject_prefix = fmt_patch_subject_prefix;
1847 memset(&s_r_opt, 0, sizeof(s_r_opt));
1848 s_r_opt.def = "HEAD";
1849 s_r_opt.revarg_opt = REVARG_COMMITTISH;
1851 if (default_attach) {
1852 rev.mime_boundary = default_attach;
1853 rev.no_inline = 1;
1857 * Parse the arguments before setup_revisions(), or something
1858 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1859 * possibly a valid SHA1.
1861 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1862 builtin_format_patch_usage,
1863 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1864 PARSE_OPT_KEEP_DASHDASH);
1866 /* Make sure "0000-$sub.patch" gives non-negative length for $sub */
1867 if (fmt_patch_name_max <= strlen("0000-") + strlen(fmt_patch_suffix))
1868 fmt_patch_name_max = strlen("0000-") + strlen(fmt_patch_suffix);
1870 if (cover_from_description_arg)
1871 cover_from_description_mode = parse_cover_from_description(cover_from_description_arg);
1873 if (reroll_count) {
1874 struct strbuf sprefix = STRBUF_INIT;
1876 strbuf_addf(&sprefix, "%s v%s",
1877 rev.subject_prefix, reroll_count);
1878 rev.reroll_count = reroll_count;
1879 rev.subject_prefix = strbuf_detach(&sprefix, NULL);
1882 for (i = 0; i < extra_hdr.nr; i++) {
1883 strbuf_addstr(&buf, extra_hdr.items[i].string);
1884 strbuf_addch(&buf, '\n');
1887 if (extra_to.nr)
1888 strbuf_addstr(&buf, "To: ");
1889 for (i = 0; i < extra_to.nr; i++) {
1890 if (i)
1891 strbuf_addstr(&buf, " ");
1892 strbuf_addstr(&buf, extra_to.items[i].string);
1893 if (i + 1 < extra_to.nr)
1894 strbuf_addch(&buf, ',');
1895 strbuf_addch(&buf, '\n');
1898 if (extra_cc.nr)
1899 strbuf_addstr(&buf, "Cc: ");
1900 for (i = 0; i < extra_cc.nr; i++) {
1901 if (i)
1902 strbuf_addstr(&buf, " ");
1903 strbuf_addstr(&buf, extra_cc.items[i].string);
1904 if (i + 1 < extra_cc.nr)
1905 strbuf_addch(&buf, ',');
1906 strbuf_addch(&buf, '\n');
1909 rev.extra_headers = strbuf_detach(&buf, NULL);
1911 if (from) {
1912 if (split_ident_line(&rev.from_ident, from, strlen(from)))
1913 die(_("invalid ident line: %s"), from);
1916 if (start_number < 0)
1917 start_number = 1;
1920 * If numbered is set solely due to format.numbered in config,
1921 * and it would conflict with --keep-subject (-k) from the
1922 * command line, reset "numbered".
1924 if (numbered && keep_subject && !numbered_cmdline_opt)
1925 numbered = 0;
1927 if (numbered && keep_subject)
1928 die(_("-n and -k are mutually exclusive"));
1929 if (keep_subject && subject_prefix)
1930 die(_("--subject-prefix/--rfc and -k are mutually exclusive"));
1931 rev.preserve_subject = keep_subject;
1933 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1934 if (argc > 1)
1935 die(_("unrecognized argument: %s"), argv[1]);
1937 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1938 die(_("--name-only does not make sense"));
1939 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1940 die(_("--name-status does not make sense"));
1941 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1942 die(_("--check does not make sense"));
1944 if (!use_patch_format &&
1945 (!rev.diffopt.output_format ||
1946 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1947 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1948 if (!rev.diffopt.stat_width)
1949 rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
1951 /* Always generate a patch */
1952 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1954 rev.zero_commit = zero_commit;
1955 rev.patch_name_max = fmt_patch_name_max;
1957 if (!rev.diffopt.flags.text && !no_binary_diff)
1958 rev.diffopt.flags.binary = 1;
1960 if (rev.show_notes)
1961 load_display_notes(&rev.notes_opt);
1963 if (use_stdout + rev.diffopt.close_file + !!output_directory > 1)
1964 die(_("--stdout, --output, and --output-directory are mutually exclusive"));
1966 if (use_stdout) {
1967 setup_pager();
1968 } else if (rev.diffopt.close_file) {
1970 * The diff code parsed --output; it has already opened the
1971 * file, but we must instruct it not to close after each diff.
1973 rev.diffopt.no_free = 1;
1974 } else {
1975 int saved;
1977 if (!output_directory)
1978 output_directory = config_output_directory;
1979 output_directory = set_outdir(prefix, output_directory);
1981 if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
1982 rev.diffopt.use_color = GIT_COLOR_NEVER;
1984 * We consider <outdir> as 'outside of gitdir', therefore avoid
1985 * applying adjust_shared_perm in s-c-l-d.
1987 saved = get_shared_repository();
1988 set_shared_repository(0);
1989 switch (safe_create_leading_directories_const(output_directory)) {
1990 case SCLD_OK:
1991 case SCLD_EXISTS:
1992 break;
1993 default:
1994 die(_("could not create leading directories "
1995 "of '%s'"), output_directory);
1997 set_shared_repository(saved);
1998 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1999 die_errno(_("could not create directory '%s'"),
2000 output_directory);
2003 if (rev.pending.nr == 1) {
2004 int check_head = 0;
2006 if (rev.max_count < 0 && !rev.show_root_diff) {
2008 * This is traditional behaviour of "git format-patch
2009 * origin" that prepares what the origin side still
2010 * does not have.
2012 rev.pending.objects[0].item->flags |= UNINTERESTING;
2013 add_head_to_pending(&rev);
2014 check_head = 1;
2017 * Otherwise, it is "format-patch -22 HEAD", and/or
2018 * "format-patch --root HEAD". The user wants
2019 * get_revision() to do the usual traversal.
2022 if (!strcmp(rev.pending.objects[0].name, "HEAD"))
2023 check_head = 1;
2025 if (check_head) {
2026 const char *ref, *v;
2027 ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2028 NULL, NULL);
2029 if (ref && skip_prefix(ref, "refs/heads/", &v))
2030 branch_name = xstrdup(v);
2031 else
2032 branch_name = xstrdup(""); /* no branch */
2037 * We cannot move this anywhere earlier because we do want to
2038 * know if --root was given explicitly from the command line.
2040 rev.show_root_diff = 1;
2042 if (ignore_if_in_upstream) {
2043 /* Don't say anything if head and upstream are the same. */
2044 if (rev.pending.nr == 2) {
2045 struct object_array_entry *o = rev.pending.objects;
2046 if (oideq(&o[0].item->oid, &o[1].item->oid))
2047 goto done;
2049 get_patch_ids(&rev, &ids);
2052 if (prepare_revision_walk(&rev))
2053 die(_("revision walk setup failed"));
2054 rev.boundary = 1;
2055 while ((commit = get_revision(&rev)) != NULL) {
2056 if (commit->object.flags & BOUNDARY) {
2057 boundary_count++;
2058 origin = (boundary_count == 1) ? commit : NULL;
2059 continue;
2062 if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
2063 continue;
2065 nr++;
2066 REALLOC_ARRAY(list, nr);
2067 list[nr - 1] = commit;
2069 if (nr == 0)
2070 /* nothing to do */
2071 goto done;
2072 total = nr;
2073 if (cover_letter == -1) {
2074 if (config_cover_letter == COVER_AUTO)
2075 cover_letter = (total > 1);
2076 else
2077 cover_letter = (config_cover_letter == COVER_ON);
2079 if (!keep_subject && auto_number && (total > 1 || cover_letter))
2080 numbered = 1;
2081 if (numbered)
2082 rev.total = total + start_number - 1;
2084 if (idiff_prev.nr) {
2085 if (!cover_letter && total != 1)
2086 die(_("--interdiff requires --cover-letter or single patch"));
2087 rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
2088 rev.idiff_oid2 = get_commit_tree_oid(list[0]);
2089 rev.idiff_title = diff_title(&idiff_title, reroll_count,
2090 _("Interdiff:"),
2091 _("Interdiff against v%d:"));
2094 if (creation_factor < 0)
2095 creation_factor = RANGE_DIFF_CREATION_FACTOR_DEFAULT;
2096 else if (!rdiff_prev)
2097 die(_("--creation-factor requires --range-diff"));
2099 if (rdiff_prev) {
2100 if (!cover_letter && total != 1)
2101 die(_("--range-diff requires --cover-letter or single patch"));
2103 infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
2104 origin, list[0]);
2105 rev.rdiff1 = rdiff1.buf;
2106 rev.rdiff2 = rdiff2.buf;
2107 rev.creation_factor = creation_factor;
2108 rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
2109 _("Range-diff:"),
2110 _("Range-diff against v%d:"));
2113 if (!signature) {
2114 ; /* --no-signature inhibits all signatures */
2115 } else if (signature && signature != git_version_string) {
2116 ; /* non-default signature already set */
2117 } else if (signature_file) {
2118 struct strbuf buf = STRBUF_INIT;
2120 if (strbuf_read_file(&buf, signature_file, 128) < 0)
2121 die_errno(_("unable to read signature file '%s'"), signature_file);
2122 signature = strbuf_detach(&buf, NULL);
2125 memset(&bases, 0, sizeof(bases));
2126 base = get_base_commit(base_commit, list, nr);
2127 if (base) {
2128 reset_revision_walk();
2129 clear_object_flags(UNINTERESTING);
2130 prepare_bases(&bases, base, list, nr);
2133 if (in_reply_to || thread || cover_letter)
2134 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
2135 if (in_reply_to) {
2136 const char *msgid = clean_message_id(in_reply_to);
2137 string_list_append(rev.ref_message_ids, msgid);
2139 rev.numbered_files = just_numbers;
2140 rev.patch_suffix = fmt_patch_suffix;
2141 if (cover_letter) {
2142 if (thread)
2143 gen_message_id(&rev, "cover");
2144 make_cover_letter(&rev, !!output_directory,
2145 origin, nr, list, branch_name, quiet);
2146 print_bases(&bases, rev.diffopt.file);
2147 print_signature(rev.diffopt.file);
2148 total++;
2149 start_number--;
2150 /* interdiff/range-diff in cover-letter; omit from patches */
2151 rev.idiff_oid1 = NULL;
2152 rev.rdiff1 = NULL;
2154 rev.add_signoff = do_signoff;
2156 if (show_progress)
2157 progress = start_delayed_progress(_("Generating patches"), total);
2158 while (0 <= --nr) {
2159 int shown;
2160 display_progress(progress, total - nr);
2161 commit = list[nr];
2162 rev.nr = total - nr + (start_number - 1);
2163 /* Make the second and subsequent mails replies to the first */
2164 if (thread) {
2165 /* Have we already had a message ID? */
2166 if (rev.message_id) {
2168 * For deep threading: make every mail
2169 * a reply to the previous one, no
2170 * matter what other options are set.
2172 * For shallow threading:
2174 * Without --cover-letter and
2175 * --in-reply-to, make every mail a
2176 * reply to the one before.
2178 * With --in-reply-to but no
2179 * --cover-letter, make every mail a
2180 * reply to the <reply-to>.
2182 * With --cover-letter, make every
2183 * mail but the cover letter a reply
2184 * to the cover letter. The cover
2185 * letter is a reply to the
2186 * --in-reply-to, if specified.
2188 if (thread == THREAD_SHALLOW
2189 && rev.ref_message_ids->nr > 0
2190 && (!cover_letter || rev.nr > 1))
2191 free(rev.message_id);
2192 else
2193 string_list_append(rev.ref_message_ids,
2194 rev.message_id);
2196 gen_message_id(&rev, oid_to_hex(&commit->object.oid));
2199 if (output_directory &&
2200 open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
2201 die(_("failed to create output files"));
2202 shown = log_tree_commit(&rev, commit);
2203 free_commit_buffer(the_repository->parsed_objects,
2204 commit);
2206 /* We put one extra blank line between formatted
2207 * patches and this flag is used by log-tree code
2208 * to see if it needs to emit a LF before showing
2209 * the log; when using one file per patch, we do
2210 * not want the extra blank line.
2212 if (output_directory)
2213 rev.shown_one = 0;
2214 if (shown) {
2215 print_bases(&bases, rev.diffopt.file);
2216 if (rev.mime_boundary)
2217 fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
2218 mime_boundary_leader,
2219 rev.mime_boundary);
2220 else
2221 print_signature(rev.diffopt.file);
2223 if (output_directory)
2224 fclose(rev.diffopt.file);
2226 stop_progress(&progress);
2227 free(list);
2228 free(branch_name);
2229 string_list_clear(&extra_to, 0);
2230 string_list_clear(&extra_cc, 0);
2231 string_list_clear(&extra_hdr, 0);
2232 if (ignore_if_in_upstream)
2233 free_patch_ids(&ids);
2235 done:
2236 oid_array_clear(&idiff_prev);
2237 strbuf_release(&idiff_title);
2238 strbuf_release(&rdiff1);
2239 strbuf_release(&rdiff2);
2240 strbuf_release(&rdiff_title);
2241 return 0;
2244 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
2246 struct object_id oid;
2247 if (get_oid(arg, &oid) == 0) {
2248 struct commit *commit = lookup_commit_reference(the_repository,
2249 &oid);
2250 if (commit) {
2251 commit->object.flags |= flags;
2252 add_pending_object(revs, &commit->object, arg);
2253 return 0;
2256 return -1;
2259 static const char * const cherry_usage[] = {
2260 N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
2261 NULL
2264 static void print_commit(char sign, struct commit *commit, int verbose,
2265 int abbrev, FILE *file)
2267 if (!verbose) {
2268 fprintf(file, "%c %s\n", sign,
2269 find_unique_abbrev(&commit->object.oid, abbrev));
2270 } else {
2271 struct strbuf buf = STRBUF_INIT;
2272 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2273 fprintf(file, "%c %s %s\n", sign,
2274 find_unique_abbrev(&commit->object.oid, abbrev),
2275 buf.buf);
2276 strbuf_release(&buf);
2280 int cmd_cherry(int argc, const char **argv, const char *prefix)
2282 struct rev_info revs;
2283 struct patch_ids ids;
2284 struct commit *commit;
2285 struct commit_list *list = NULL;
2286 struct branch *current_branch;
2287 const char *upstream;
2288 const char *head = "HEAD";
2289 const char *limit = NULL;
2290 int verbose = 0, abbrev = 0;
2292 struct option options[] = {
2293 OPT__ABBREV(&abbrev),
2294 OPT__VERBOSE(&verbose, N_("be verbose")),
2295 OPT_END()
2298 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
2300 switch (argc) {
2301 case 3:
2302 limit = argv[2];
2303 /* FALLTHROUGH */
2304 case 2:
2305 head = argv[1];
2306 /* FALLTHROUGH */
2307 case 1:
2308 upstream = argv[0];
2309 break;
2310 default:
2311 current_branch = branch_get(NULL);
2312 upstream = branch_get_upstream(current_branch, NULL);
2313 if (!upstream) {
2314 fprintf(stderr, _("Could not find a tracked"
2315 " remote branch, please"
2316 " specify <upstream> manually.\n"));
2317 usage_with_options(cherry_usage, options);
2321 repo_init_revisions(the_repository, &revs, prefix);
2322 revs.max_parents = 1;
2324 if (add_pending_commit(head, &revs, 0))
2325 die(_("unknown commit %s"), head);
2326 if (add_pending_commit(upstream, &revs, UNINTERESTING))
2327 die(_("unknown commit %s"), upstream);
2329 /* Don't say anything if head and upstream are the same. */
2330 if (revs.pending.nr == 2) {
2331 struct object_array_entry *o = revs.pending.objects;
2332 if (oideq(&o[0].item->oid, &o[1].item->oid))
2333 return 0;
2336 get_patch_ids(&revs, &ids);
2338 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2339 die(_("unknown commit %s"), limit);
2341 /* reverse the list of commits */
2342 if (prepare_revision_walk(&revs))
2343 die(_("revision walk setup failed"));
2344 while ((commit = get_revision(&revs)) != NULL) {
2345 commit_list_insert(commit, &list);
2348 while (list) {
2349 char sign = '+';
2351 commit = list->item;
2352 if (has_commit_patch_id(commit, &ids))
2353 sign = '-';
2354 print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2355 list = list->next;
2358 free_patch_ids(&ids);
2359 return 0;