Sync with 2.32.7
[git.git] / builtin / log.c
blob3d7717ba5ca234c06595e74aaeeab7c5f91114dd
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 (rev->commit_format == CMIT_FMT_USERFORMAT && !w.decorate)
249 decoration_style = 0;
251 if (decoration_style) {
252 const struct string_list *config_exclude =
253 repo_config_get_value_multi(the_repository,
254 "log.excludeDecoration");
256 if (config_exclude) {
257 struct string_list_item *item;
258 for_each_string_list_item(item, config_exclude)
259 string_list_append(&decorate_refs_exclude_config,
260 item->string);
263 rev->show_decorations = 1;
265 load_ref_decorations(&decoration_filter, decoration_style);
268 if (rev->line_level_traverse)
269 line_log_init(rev, line_cb.prefix, &line_cb.args);
271 setup_pager();
274 static void cmd_log_init(int argc, const char **argv, const char *prefix,
275 struct rev_info *rev, struct setup_revision_opt *opt)
277 cmd_log_init_defaults(rev);
278 cmd_log_init_finish(argc, argv, prefix, rev, opt);
282 * This gives a rough estimate for how many commits we
283 * will print out in the list.
285 static int estimate_commit_count(struct commit_list *list)
287 int n = 0;
289 while (list) {
290 struct commit *commit = list->item;
291 unsigned int flags = commit->object.flags;
292 list = list->next;
293 if (!(flags & (TREESAME | UNINTERESTING)))
294 n++;
296 return n;
299 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
301 if (rev->shown_one) {
302 rev->shown_one = 0;
303 if (rev->commit_format != CMIT_FMT_ONELINE)
304 putchar(rev->diffopt.line_termination);
306 fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
309 static struct itimerval early_output_timer;
311 static void log_show_early(struct rev_info *revs, struct commit_list *list)
313 int i = revs->early_output;
314 int show_header = 1;
315 int no_free = revs->diffopt.no_free;
317 revs->diffopt.no_free = 0;
318 sort_in_topological_order(&list, revs->sort_order);
319 while (list && i) {
320 struct commit *commit = list->item;
321 switch (simplify_commit(revs, commit)) {
322 case commit_show:
323 if (show_header) {
324 int n = estimate_commit_count(list);
325 show_early_header(revs, "incomplete", n);
326 show_header = 0;
328 log_tree_commit(revs, commit);
329 i--;
330 break;
331 case commit_ignore:
332 break;
333 case commit_error:
334 revs->diffopt.no_free = no_free;
335 diff_free(&revs->diffopt);
336 return;
338 list = list->next;
341 /* Did we already get enough commits for the early output? */
342 if (!i) {
343 revs->diffopt.no_free = 0;
344 diff_free(&revs->diffopt);
345 return;
349 * ..if no, then repeat it twice a second until we
350 * do.
352 * NOTE! We don't use "it_interval", because if the
353 * reader isn't listening, we want our output to be
354 * throttled by the writing, and not have the timer
355 * trigger every second even if we're blocked on a
356 * reader!
358 early_output_timer.it_value.tv_sec = 0;
359 early_output_timer.it_value.tv_usec = 500000;
360 setitimer(ITIMER_REAL, &early_output_timer, NULL);
363 static void early_output(int signal)
365 show_early_output = log_show_early;
368 static void setup_early_output(void)
370 struct sigaction sa;
373 * Set up the signal handler, minimally intrusively:
374 * we only set a single volatile integer word (not
375 * using sigatomic_t - trying to avoid unnecessary
376 * system dependencies and headers), and using
377 * SA_RESTART.
379 memset(&sa, 0, sizeof(sa));
380 sa.sa_handler = early_output;
381 sigemptyset(&sa.sa_mask);
382 sa.sa_flags = SA_RESTART;
383 sigaction(SIGALRM, &sa, NULL);
386 * If we can get the whole output in less than a
387 * tenth of a second, don't even bother doing the
388 * early-output thing..
390 * This is a one-time-only trigger.
392 early_output_timer.it_value.tv_sec = 0;
393 early_output_timer.it_value.tv_usec = 100000;
394 setitimer(ITIMER_REAL, &early_output_timer, NULL);
397 static void finish_early_output(struct rev_info *rev)
399 int n = estimate_commit_count(rev->commits);
400 signal(SIGALRM, SIG_IGN);
401 show_early_header(rev, "done", n);
404 static int cmd_log_walk(struct rev_info *rev)
406 struct commit *commit;
407 int saved_nrl = 0;
408 int saved_dcctc = 0;
410 if (rev->early_output)
411 setup_early_output();
413 if (prepare_revision_walk(rev))
414 die(_("revision walk setup failed"));
416 if (rev->early_output)
417 finish_early_output(rev);
420 * For --check and --exit-code, the exit code is based on CHECK_FAILED
421 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
422 * retain that state information if replacing rev->diffopt in this loop
424 rev->diffopt.no_free = 1;
425 while ((commit = get_revision(rev)) != NULL) {
426 if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
428 * We decremented max_count in get_revision,
429 * but we didn't actually show the commit.
431 rev->max_count++;
432 if (!rev->reflog_info) {
434 * We may show a given commit multiple times when
435 * walking the reflogs.
437 free_commit_buffer(the_repository->parsed_objects,
438 commit);
439 free_commit_list(commit->parents);
440 commit->parents = NULL;
442 if (saved_nrl < rev->diffopt.needed_rename_limit)
443 saved_nrl = rev->diffopt.needed_rename_limit;
444 if (rev->diffopt.degraded_cc_to_c)
445 saved_dcctc = 1;
447 rev->diffopt.degraded_cc_to_c = saved_dcctc;
448 rev->diffopt.needed_rename_limit = saved_nrl;
449 rev->diffopt.no_free = 0;
450 diff_free(&rev->diffopt);
452 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
453 rev->diffopt.flags.check_failed) {
454 return 02;
456 return diff_result_code(&rev->diffopt, 0);
459 static int git_log_config(const char *var, const char *value, void *cb)
461 const char *slot_name;
463 if (!strcmp(var, "format.pretty"))
464 return git_config_string(&fmt_pretty, var, value);
465 if (!strcmp(var, "format.subjectprefix"))
466 return git_config_string(&fmt_patch_subject_prefix, var, value);
467 if (!strcmp(var, "format.filenamemaxlength")) {
468 fmt_patch_name_max = git_config_int(var, value);
469 return 0;
471 if (!strcmp(var, "format.encodeemailheaders")) {
472 default_encode_email_headers = git_config_bool(var, value);
473 return 0;
475 if (!strcmp(var, "log.abbrevcommit")) {
476 default_abbrev_commit = git_config_bool(var, value);
477 return 0;
479 if (!strcmp(var, "log.date"))
480 return git_config_string(&default_date_mode, var, value);
481 if (!strcmp(var, "log.decorate")) {
482 decoration_style = parse_decoration_style(value);
483 if (decoration_style < 0)
484 decoration_style = 0; /* maybe warn? */
485 return 0;
487 if (!strcmp(var, "log.diffmerges"))
488 return diff_merges_config(value);
489 if (!strcmp(var, "log.showroot")) {
490 default_show_root = git_config_bool(var, value);
491 return 0;
493 if (!strcmp(var, "log.follow")) {
494 default_follow = git_config_bool(var, value);
495 return 0;
497 if (skip_prefix(var, "color.decorate.", &slot_name))
498 return parse_decorate_color_config(var, slot_name, value);
499 if (!strcmp(var, "log.mailmap")) {
500 use_mailmap_config = git_config_bool(var, value);
501 return 0;
503 if (!strcmp(var, "log.showsignature")) {
504 default_show_signature = git_config_bool(var, value);
505 return 0;
508 if (grep_config(var, value, cb) < 0)
509 return -1;
510 if (git_gpg_config(var, value, cb) < 0)
511 return -1;
512 return git_diff_ui_config(var, value, cb);
515 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
517 struct rev_info rev;
518 struct setup_revision_opt opt;
520 init_log_defaults();
521 git_config(git_log_config, NULL);
523 repo_init_revisions(the_repository, &rev, prefix);
524 rev.diff = 1;
525 rev.simplify_history = 0;
526 memset(&opt, 0, sizeof(opt));
527 opt.def = "HEAD";
528 opt.revarg_opt = REVARG_COMMITTISH;
529 cmd_log_init(argc, argv, prefix, &rev, &opt);
530 if (!rev.diffopt.output_format)
531 rev.diffopt.output_format = DIFF_FORMAT_RAW;
532 return cmd_log_walk(&rev);
535 static void show_tagger(const char *buf, struct rev_info *rev)
537 struct strbuf out = STRBUF_INIT;
538 struct pretty_print_context pp = {0};
540 pp.fmt = rev->commit_format;
541 pp.date_mode = rev->date_mode;
542 pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
543 fprintf(rev->diffopt.file, "%s", out.buf);
544 strbuf_release(&out);
547 static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
549 struct object_id oidc;
550 struct object_context obj_context;
551 char *buf;
552 unsigned long size;
554 fflush(rev->diffopt.file);
555 if (!rev->diffopt.flags.textconv_set_via_cmdline ||
556 !rev->diffopt.flags.allow_textconv)
557 return stream_blob_to_fd(1, oid, NULL, 0);
559 if (get_oid_with_context(the_repository, obj_name,
560 GET_OID_RECORD_PATH,
561 &oidc, &obj_context))
562 die(_("not a valid object name %s"), obj_name);
563 if (!obj_context.path ||
564 !textconv_object(the_repository, obj_context.path,
565 obj_context.mode, &oidc, 1, &buf, &size)) {
566 free(obj_context.path);
567 return stream_blob_to_fd(1, oid, NULL, 0);
570 if (!buf)
571 die(_("git show %s: bad file"), obj_name);
573 write_or_die(1, buf, size);
574 free(obj_context.path);
575 return 0;
578 static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
580 unsigned long size;
581 enum object_type type;
582 char *buf = read_object_file(oid, &type, &size);
583 int offset = 0;
585 if (!buf)
586 return error(_("could not read object %s"), oid_to_hex(oid));
588 assert(type == OBJ_TAG);
589 while (offset < size && buf[offset] != '\n') {
590 int new_offset = offset + 1;
591 const char *ident;
592 while (new_offset < size && buf[new_offset++] != '\n')
593 ; /* do nothing */
594 if (skip_prefix(buf + offset, "tagger ", &ident))
595 show_tagger(ident, rev);
596 offset = new_offset;
599 if (offset < size)
600 fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
601 free(buf);
602 return 0;
605 static int show_tree_object(const struct object_id *oid,
606 struct strbuf *base,
607 const char *pathname, unsigned mode, void *context)
609 FILE *file = context;
610 fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
611 return 0;
614 static void show_setup_revisions_tweak(struct rev_info *rev,
615 struct setup_revision_opt *opt)
617 if (rev->first_parent_only)
618 diff_merges_default_to_first_parent(rev);
619 else
620 diff_merges_default_to_dense_combined(rev);
621 if (!rev->diffopt.output_format)
622 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
625 int cmd_show(int argc, const char **argv, const char *prefix)
627 struct rev_info rev;
628 struct object_array_entry *objects;
629 struct setup_revision_opt opt;
630 struct pathspec match_all;
631 int i, count, ret = 0;
633 init_log_defaults();
634 git_config(git_log_config, NULL);
636 memset(&match_all, 0, sizeof(match_all));
637 repo_init_revisions(the_repository, &rev, prefix);
638 rev.diff = 1;
639 rev.always_show_header = 1;
640 rev.no_walk = REVISION_WALK_NO_WALK_SORTED;
641 rev.diffopt.stat_width = -1; /* Scale to real terminal size */
643 memset(&opt, 0, sizeof(opt));
644 opt.def = "HEAD";
645 opt.tweak = show_setup_revisions_tweak;
646 cmd_log_init(argc, argv, prefix, &rev, &opt);
648 if (!rev.no_walk)
649 return cmd_log_walk(&rev);
651 count = rev.pending.nr;
652 objects = rev.pending.objects;
653 for (i = 0; i < count && !ret; i++) {
654 struct object *o = objects[i].item;
655 const char *name = objects[i].name;
656 switch (o->type) {
657 case OBJ_BLOB:
658 ret = show_blob_object(&o->oid, &rev, name);
659 break;
660 case OBJ_TAG: {
661 struct tag *t = (struct tag *)o;
662 struct object_id *oid = get_tagged_oid(t);
664 if (rev.shown_one)
665 putchar('\n');
666 fprintf(rev.diffopt.file, "%stag %s%s\n",
667 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
668 t->tag,
669 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
670 ret = show_tag_object(&o->oid, &rev);
671 rev.shown_one = 1;
672 if (ret)
673 break;
674 o = parse_object(the_repository, oid);
675 if (!o)
676 ret = error(_("could not read object %s"),
677 oid_to_hex(oid));
678 objects[i].item = o;
679 i--;
680 break;
682 case OBJ_TREE:
683 if (rev.shown_one)
684 putchar('\n');
685 fprintf(rev.diffopt.file, "%stree %s%s\n\n",
686 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
687 name,
688 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
689 read_tree(the_repository, (struct tree *)o,
690 &match_all, show_tree_object,
691 rev.diffopt.file);
692 rev.shown_one = 1;
693 break;
694 case OBJ_COMMIT:
695 rev.pending.nr = rev.pending.alloc = 0;
696 rev.pending.objects = NULL;
697 add_object_array(o, name, &rev.pending);
698 ret = cmd_log_walk(&rev);
699 break;
700 default:
701 ret = error(_("unknown type: %d"), o->type);
704 free(objects);
705 return ret;
709 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
711 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
713 struct rev_info rev;
714 struct setup_revision_opt opt;
716 init_log_defaults();
717 git_config(git_log_config, NULL);
719 repo_init_revisions(the_repository, &rev, prefix);
720 init_reflog_walk(&rev.reflog_info);
721 rev.verbose_header = 1;
722 memset(&opt, 0, sizeof(opt));
723 opt.def = "HEAD";
724 cmd_log_init_defaults(&rev);
725 rev.abbrev_commit = 1;
726 rev.commit_format = CMIT_FMT_ONELINE;
727 rev.use_terminator = 1;
728 rev.always_show_header = 1;
729 cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
731 return cmd_log_walk(&rev);
734 static void log_setup_revisions_tweak(struct rev_info *rev,
735 struct setup_revision_opt *opt)
737 if (rev->diffopt.flags.default_follow_renames &&
738 rev->prune_data.nr == 1)
739 rev->diffopt.flags.follow_renames = 1;
741 if (rev->first_parent_only)
742 diff_merges_default_to_first_parent(rev);
745 int cmd_log(int argc, const char **argv, const char *prefix)
747 struct rev_info rev;
748 struct setup_revision_opt opt;
750 init_log_defaults();
751 git_config(git_log_config, NULL);
753 repo_init_revisions(the_repository, &rev, prefix);
754 rev.always_show_header = 1;
755 memset(&opt, 0, sizeof(opt));
756 opt.def = "HEAD";
757 opt.revarg_opt = REVARG_COMMITTISH;
758 opt.tweak = log_setup_revisions_tweak;
759 cmd_log_init(argc, argv, prefix, &rev, &opt);
760 return cmd_log_walk(&rev);
763 /* format-patch */
765 static const char *fmt_patch_suffix = ".patch";
766 static int numbered = 0;
767 static int auto_number = 1;
769 static char *default_attach = NULL;
771 static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
772 static struct string_list extra_to = STRING_LIST_INIT_NODUP;
773 static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
775 static void add_header(const char *value)
777 struct string_list_item *item;
778 int len = strlen(value);
779 while (len && value[len - 1] == '\n')
780 len--;
782 if (!strncasecmp(value, "to: ", 4)) {
783 item = string_list_append(&extra_to, value + 4);
784 len -= 4;
785 } else if (!strncasecmp(value, "cc: ", 4)) {
786 item = string_list_append(&extra_cc, value + 4);
787 len -= 4;
788 } else {
789 item = string_list_append(&extra_hdr, value);
792 item->string[len] = '\0';
795 enum cover_setting {
796 COVER_UNSET,
797 COVER_OFF,
798 COVER_ON,
799 COVER_AUTO
802 enum thread_level {
803 THREAD_UNSET,
804 THREAD_SHALLOW,
805 THREAD_DEEP
808 enum cover_from_description {
809 COVER_FROM_NONE,
810 COVER_FROM_MESSAGE,
811 COVER_FROM_SUBJECT,
812 COVER_FROM_AUTO
815 enum auto_base_setting {
816 AUTO_BASE_NEVER,
817 AUTO_BASE_ALWAYS,
818 AUTO_BASE_WHEN_ABLE
821 static enum thread_level thread;
822 static int do_signoff;
823 static enum auto_base_setting auto_base;
824 static char *from;
825 static const char *signature = git_version_string;
826 static const char *signature_file;
827 static enum cover_setting config_cover_letter;
828 static const char *config_output_directory;
829 static enum cover_from_description cover_from_description_mode = COVER_FROM_MESSAGE;
830 static int show_notes;
831 static struct display_notes_opt notes_opt;
833 static enum cover_from_description parse_cover_from_description(const char *arg)
835 if (!arg || !strcmp(arg, "default"))
836 return COVER_FROM_MESSAGE;
837 else if (!strcmp(arg, "none"))
838 return COVER_FROM_NONE;
839 else if (!strcmp(arg, "message"))
840 return COVER_FROM_MESSAGE;
841 else if (!strcmp(arg, "subject"))
842 return COVER_FROM_SUBJECT;
843 else if (!strcmp(arg, "auto"))
844 return COVER_FROM_AUTO;
845 else
846 die(_("%s: invalid cover from description mode"), arg);
849 static int git_format_config(const char *var, const char *value, void *cb)
851 if (!strcmp(var, "format.headers")) {
852 if (!value)
853 die(_("format.headers without value"));
854 add_header(value);
855 return 0;
857 if (!strcmp(var, "format.suffix"))
858 return git_config_string(&fmt_patch_suffix, var, value);
859 if (!strcmp(var, "format.to")) {
860 if (!value)
861 return config_error_nonbool(var);
862 string_list_append(&extra_to, value);
863 return 0;
865 if (!strcmp(var, "format.cc")) {
866 if (!value)
867 return config_error_nonbool(var);
868 string_list_append(&extra_cc, value);
869 return 0;
871 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
872 !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
873 return 0;
875 if (!strcmp(var, "format.numbered")) {
876 if (value && !strcasecmp(value, "auto")) {
877 auto_number = 1;
878 return 0;
880 numbered = git_config_bool(var, value);
881 auto_number = auto_number && numbered;
882 return 0;
884 if (!strcmp(var, "format.attach")) {
885 if (value && *value)
886 default_attach = xstrdup(value);
887 else
888 default_attach = xstrdup(git_version_string);
889 return 0;
891 if (!strcmp(var, "format.thread")) {
892 if (value && !strcasecmp(value, "deep")) {
893 thread = THREAD_DEEP;
894 return 0;
896 if (value && !strcasecmp(value, "shallow")) {
897 thread = THREAD_SHALLOW;
898 return 0;
900 thread = git_config_bool(var, value) ? THREAD_SHALLOW : THREAD_UNSET;
901 return 0;
903 if (!strcmp(var, "format.signoff")) {
904 do_signoff = git_config_bool(var, value);
905 return 0;
907 if (!strcmp(var, "format.signature"))
908 return git_config_string(&signature, var, value);
909 if (!strcmp(var, "format.signaturefile"))
910 return git_config_pathname(&signature_file, var, value);
911 if (!strcmp(var, "format.coverletter")) {
912 if (value && !strcasecmp(value, "auto")) {
913 config_cover_letter = COVER_AUTO;
914 return 0;
916 config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
917 return 0;
919 if (!strcmp(var, "format.outputdirectory"))
920 return git_config_string(&config_output_directory, var, value);
921 if (!strcmp(var, "format.useautobase")) {
922 if (value && !strcasecmp(value, "whenAble")) {
923 auto_base = AUTO_BASE_WHEN_ABLE;
924 return 0;
926 auto_base = git_config_bool(var, value) ? AUTO_BASE_ALWAYS : AUTO_BASE_NEVER;
927 return 0;
929 if (!strcmp(var, "format.from")) {
930 int b = git_parse_maybe_bool(value);
931 free(from);
932 if (b < 0)
933 from = xstrdup(value);
934 else if (b)
935 from = xstrdup(git_committer_info(IDENT_NO_DATE));
936 else
937 from = NULL;
938 return 0;
940 if (!strcmp(var, "format.notes")) {
941 int b = git_parse_maybe_bool(value);
942 if (b < 0)
943 enable_ref_display_notes(&notes_opt, &show_notes, value);
944 else if (b)
945 enable_default_display_notes(&notes_opt, &show_notes);
946 else
947 disable_display_notes(&notes_opt, &show_notes);
948 return 0;
950 if (!strcmp(var, "format.coverfromdescription")) {
951 cover_from_description_mode = parse_cover_from_description(value);
952 return 0;
955 return git_log_config(var, value, cb);
958 static const char *output_directory = NULL;
959 static int outdir_offset;
961 static int open_next_file(struct commit *commit, const char *subject,
962 struct rev_info *rev, int quiet)
964 struct strbuf filename = STRBUF_INIT;
966 if (output_directory) {
967 strbuf_addstr(&filename, output_directory);
968 strbuf_complete(&filename, '/');
971 if (rev->numbered_files)
972 strbuf_addf(&filename, "%d", rev->nr);
973 else if (commit)
974 fmt_output_commit(&filename, commit, rev);
975 else
976 fmt_output_subject(&filename, subject, rev);
978 if (!quiet)
979 printf("%s\n", filename.buf + outdir_offset);
981 if ((rev->diffopt.file = fopen(filename.buf, "w")) == NULL) {
982 error_errno(_("cannot open patch file %s"), filename.buf);
983 strbuf_release(&filename);
984 return -1;
987 strbuf_release(&filename);
988 return 0;
991 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
993 struct rev_info check_rev;
994 struct commit *commit, *c1, *c2;
995 struct object *o1, *o2;
996 unsigned flags1, flags2;
998 if (rev->pending.nr != 2)
999 die(_("need exactly one range"));
1001 o1 = rev->pending.objects[0].item;
1002 o2 = rev->pending.objects[1].item;
1003 flags1 = o1->flags;
1004 flags2 = o2->flags;
1005 c1 = lookup_commit_reference(the_repository, &o1->oid);
1006 c2 = lookup_commit_reference(the_repository, &o2->oid);
1008 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
1009 die(_("not a range"));
1011 init_patch_ids(the_repository, ids);
1013 /* given a range a..b get all patch ids for b..a */
1014 repo_init_revisions(the_repository, &check_rev, rev->prefix);
1015 check_rev.max_parents = 1;
1016 o1->flags ^= UNINTERESTING;
1017 o2->flags ^= UNINTERESTING;
1018 add_pending_object(&check_rev, o1, "o1");
1019 add_pending_object(&check_rev, o2, "o2");
1020 if (prepare_revision_walk(&check_rev))
1021 die(_("revision walk setup failed"));
1023 while ((commit = get_revision(&check_rev)) != NULL) {
1024 add_commit_patch_id(commit, ids);
1027 /* reset for next revision walk */
1028 clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
1029 clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
1030 o1->flags = flags1;
1031 o2->flags = flags2;
1034 static void gen_message_id(struct rev_info *info, char *base)
1036 struct strbuf buf = STRBUF_INIT;
1037 strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
1038 (timestamp_t) time(NULL),
1039 git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
1040 info->message_id = strbuf_detach(&buf, NULL);
1043 static void print_signature(FILE *file)
1045 if (!signature || !*signature)
1046 return;
1048 fprintf(file, "-- \n%s", signature);
1049 if (signature[strlen(signature)-1] != '\n')
1050 putc('\n', file);
1051 putc('\n', file);
1054 static char *find_branch_name(struct rev_info *rev)
1056 int i, positive = -1;
1057 struct object_id branch_oid;
1058 const struct object_id *tip_oid;
1059 const char *ref, *v;
1060 char *full_ref, *branch = NULL;
1062 for (i = 0; i < rev->cmdline.nr; i++) {
1063 if (rev->cmdline.rev[i].flags & UNINTERESTING)
1064 continue;
1065 if (positive < 0)
1066 positive = i;
1067 else
1068 return NULL;
1070 if (positive < 0)
1071 return NULL;
1072 ref = rev->cmdline.rev[positive].name;
1073 tip_oid = &rev->cmdline.rev[positive].item->oid;
1074 if (dwim_ref(ref, strlen(ref), &branch_oid, &full_ref, 0) &&
1075 skip_prefix(full_ref, "refs/heads/", &v) &&
1076 oideq(tip_oid, &branch_oid))
1077 branch = xstrdup(v);
1078 free(full_ref);
1079 return branch;
1082 static void show_diffstat(struct rev_info *rev,
1083 struct commit *origin, struct commit *head)
1085 struct diff_options opts;
1087 memcpy(&opts, &rev->diffopt, sizeof(opts));
1088 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1089 diff_setup_done(&opts);
1091 diff_tree_oid(get_commit_tree_oid(origin),
1092 get_commit_tree_oid(head),
1093 "", &opts);
1094 diffcore_std(&opts);
1095 diff_flush(&opts);
1097 fprintf(rev->diffopt.file, "\n");
1100 static void prepare_cover_text(struct pretty_print_context *pp,
1101 const char *branch_name,
1102 struct strbuf *sb,
1103 const char *encoding,
1104 int need_8bit_cte)
1106 const char *subject = "*** SUBJECT HERE ***";
1107 const char *body = "*** BLURB HERE ***";
1108 struct strbuf description_sb = STRBUF_INIT;
1109 struct strbuf subject_sb = STRBUF_INIT;
1111 if (cover_from_description_mode == COVER_FROM_NONE)
1112 goto do_pp;
1114 if (branch_name && *branch_name)
1115 read_branch_desc(&description_sb, branch_name);
1116 if (!description_sb.len)
1117 goto do_pp;
1119 if (cover_from_description_mode == COVER_FROM_SUBJECT ||
1120 cover_from_description_mode == COVER_FROM_AUTO)
1121 body = format_subject(&subject_sb, description_sb.buf, " ");
1123 if (cover_from_description_mode == COVER_FROM_MESSAGE ||
1124 (cover_from_description_mode == COVER_FROM_AUTO &&
1125 subject_sb.len > COVER_FROM_AUTO_MAX_SUBJECT_LEN))
1126 body = description_sb.buf;
1127 else
1128 subject = subject_sb.buf;
1130 do_pp:
1131 pp_title_line(pp, &subject, sb, encoding, need_8bit_cte);
1132 pp_remainder(pp, &body, sb, 0);
1134 strbuf_release(&description_sb);
1135 strbuf_release(&subject_sb);
1138 static int get_notes_refs(struct string_list_item *item, void *arg)
1140 strvec_pushf(arg, "--notes=%s", item->string);
1141 return 0;
1144 static void get_notes_args(struct strvec *arg, struct rev_info *rev)
1146 if (!rev->show_notes) {
1147 strvec_push(arg, "--no-notes");
1148 } else if (rev->notes_opt.use_default_notes > 0 ||
1149 (rev->notes_opt.use_default_notes == -1 &&
1150 !rev->notes_opt.extra_notes_refs.nr)) {
1151 strvec_push(arg, "--notes");
1152 } else {
1153 for_each_string_list(&rev->notes_opt.extra_notes_refs, get_notes_refs, arg);
1157 static void make_cover_letter(struct rev_info *rev, int use_separate_file,
1158 struct commit *origin,
1159 int nr, struct commit **list,
1160 const char *branch_name,
1161 int quiet)
1163 const char *committer;
1164 struct shortlog log;
1165 struct strbuf sb = STRBUF_INIT;
1166 int i;
1167 const char *encoding = "UTF-8";
1168 int need_8bit_cte = 0;
1169 struct pretty_print_context pp = {0};
1170 struct commit *head = list[0];
1172 if (!cmit_fmt_is_mail(rev->commit_format))
1173 die(_("cover letter needs email format"));
1175 committer = git_committer_info(0);
1177 if (use_separate_file &&
1178 open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1179 die(_("failed to create cover-letter file"));
1181 log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1183 for (i = 0; !need_8bit_cte && i < nr; i++) {
1184 const char *buf = get_commit_buffer(list[i], NULL);
1185 if (has_non_ascii(buf))
1186 need_8bit_cte = 1;
1187 unuse_commit_buffer(list[i], buf);
1190 if (!branch_name)
1191 branch_name = find_branch_name(rev);
1193 pp.fmt = CMIT_FMT_EMAIL;
1194 pp.date_mode.type = DATE_RFC2822;
1195 pp.rev = rev;
1196 pp.print_email_subject = 1;
1197 pp_user_info(&pp, NULL, &sb, committer, encoding);
1198 prepare_cover_text(&pp, branch_name, &sb, encoding, need_8bit_cte);
1199 fprintf(rev->diffopt.file, "%s\n", sb.buf);
1201 strbuf_release(&sb);
1203 shortlog_init(&log);
1204 log.wrap_lines = 1;
1205 log.wrap = MAIL_DEFAULT_WRAP;
1206 log.in1 = 2;
1207 log.in2 = 4;
1208 log.file = rev->diffopt.file;
1209 log.groups = SHORTLOG_GROUP_AUTHOR;
1210 for (i = 0; i < nr; i++)
1211 shortlog_add_commit(&log, list[i]);
1213 shortlog_output(&log);
1215 /* We can only do diffstat with a unique reference point */
1216 if (origin)
1217 show_diffstat(rev, origin, head);
1219 if (rev->idiff_oid1) {
1220 fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1221 show_interdiff(rev->idiff_oid1, rev->idiff_oid2, 0,
1222 &rev->diffopt);
1225 if (rev->rdiff1) {
1227 * Pass minimum required diff-options to range-diff; others
1228 * can be added later if deemed desirable.
1230 struct diff_options opts;
1231 struct strvec other_arg = STRVEC_INIT;
1232 struct range_diff_options range_diff_opts = {
1233 .creation_factor = rev->creation_factor,
1234 .dual_color = 1,
1235 .diffopt = &opts,
1236 .other_arg = &other_arg
1239 diff_setup(&opts);
1240 opts.file = rev->diffopt.file;
1241 opts.use_color = rev->diffopt.use_color;
1242 diff_setup_done(&opts);
1243 fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1244 get_notes_args(&other_arg, rev);
1245 show_range_diff(rev->rdiff1, rev->rdiff2, &range_diff_opts);
1246 strvec_clear(&other_arg);
1250 static const char *clean_message_id(const char *msg_id)
1252 char ch;
1253 const char *a, *z, *m;
1255 m = msg_id;
1256 while ((ch = *m) && (isspace(ch) || (ch == '<')))
1257 m++;
1258 a = m;
1259 z = NULL;
1260 while ((ch = *m)) {
1261 if (!isspace(ch) && (ch != '>'))
1262 z = m;
1263 m++;
1265 if (!z)
1266 die(_("insane in-reply-to: %s"), msg_id);
1267 if (++z == m)
1268 return a;
1269 return xmemdupz(a, z - a);
1272 static const char *set_outdir(const char *prefix, const char *output_directory)
1274 if (output_directory && is_absolute_path(output_directory))
1275 return output_directory;
1277 if (!prefix || !*prefix) {
1278 if (output_directory)
1279 return output_directory;
1280 /* The user did not explicitly ask for "./" */
1281 outdir_offset = 2;
1282 return "./";
1285 outdir_offset = strlen(prefix);
1286 if (!output_directory)
1287 return prefix;
1289 return prefix_filename(prefix, output_directory);
1292 static const char * const builtin_format_patch_usage[] = {
1293 N_("git format-patch [<options>] [<since> | <revision-range>]"),
1294 NULL
1297 static int keep_subject = 0;
1299 static int keep_callback(const struct option *opt, const char *arg, int unset)
1301 BUG_ON_OPT_NEG(unset);
1302 BUG_ON_OPT_ARG(arg);
1303 ((struct rev_info *)opt->value)->total = -1;
1304 keep_subject = 1;
1305 return 0;
1308 static int subject_prefix = 0;
1310 static int subject_prefix_callback(const struct option *opt, const char *arg,
1311 int unset)
1313 BUG_ON_OPT_NEG(unset);
1314 subject_prefix = 1;
1315 ((struct rev_info *)opt->value)->subject_prefix = arg;
1316 return 0;
1319 static int rfc_callback(const struct option *opt, const char *arg, int unset)
1321 BUG_ON_OPT_NEG(unset);
1322 BUG_ON_OPT_ARG(arg);
1323 return subject_prefix_callback(opt, "RFC PATCH", unset);
1326 static int numbered_cmdline_opt = 0;
1328 static int numbered_callback(const struct option *opt, const char *arg,
1329 int unset)
1331 BUG_ON_OPT_ARG(arg);
1332 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1333 if (unset)
1334 auto_number = 0;
1335 return 0;
1338 static int no_numbered_callback(const struct option *opt, const char *arg,
1339 int unset)
1341 BUG_ON_OPT_NEG(unset);
1342 return numbered_callback(opt, arg, 1);
1345 static int output_directory_callback(const struct option *opt, const char *arg,
1346 int unset)
1348 const char **dir = (const char **)opt->value;
1349 BUG_ON_OPT_NEG(unset);
1350 if (*dir)
1351 die(_("two output directories?"));
1352 *dir = arg;
1353 return 0;
1356 static int thread_callback(const struct option *opt, const char *arg, int unset)
1358 enum thread_level *thread = (enum thread_level *)opt->value;
1359 if (unset)
1360 *thread = THREAD_UNSET;
1361 else if (!arg || !strcmp(arg, "shallow"))
1362 *thread = THREAD_SHALLOW;
1363 else if (!strcmp(arg, "deep"))
1364 *thread = THREAD_DEEP;
1366 * Please update _git_formatpatch() in git-completion.bash
1367 * when you add new options.
1369 else
1370 return 1;
1371 return 0;
1374 static int attach_callback(const struct option *opt, const char *arg, int unset)
1376 struct rev_info *rev = (struct rev_info *)opt->value;
1377 if (unset)
1378 rev->mime_boundary = NULL;
1379 else if (arg)
1380 rev->mime_boundary = arg;
1381 else
1382 rev->mime_boundary = git_version_string;
1383 rev->no_inline = unset ? 0 : 1;
1384 return 0;
1387 static int inline_callback(const struct option *opt, const char *arg, int unset)
1389 struct rev_info *rev = (struct rev_info *)opt->value;
1390 if (unset)
1391 rev->mime_boundary = NULL;
1392 else if (arg)
1393 rev->mime_boundary = arg;
1394 else
1395 rev->mime_boundary = git_version_string;
1396 rev->no_inline = 0;
1397 return 0;
1400 static int header_callback(const struct option *opt, const char *arg, int unset)
1402 if (unset) {
1403 string_list_clear(&extra_hdr, 0);
1404 string_list_clear(&extra_to, 0);
1405 string_list_clear(&extra_cc, 0);
1406 } else {
1407 add_header(arg);
1409 return 0;
1412 static int to_callback(const struct option *opt, const char *arg, int unset)
1414 if (unset)
1415 string_list_clear(&extra_to, 0);
1416 else
1417 string_list_append(&extra_to, arg);
1418 return 0;
1421 static int cc_callback(const struct option *opt, const char *arg, int unset)
1423 if (unset)
1424 string_list_clear(&extra_cc, 0);
1425 else
1426 string_list_append(&extra_cc, arg);
1427 return 0;
1430 static int from_callback(const struct option *opt, const char *arg, int unset)
1432 char **from = opt->value;
1434 free(*from);
1436 if (unset)
1437 *from = NULL;
1438 else if (arg)
1439 *from = xstrdup(arg);
1440 else
1441 *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1442 return 0;
1445 static int base_callback(const struct option *opt, const char *arg, int unset)
1447 const char **base_commit = opt->value;
1449 if (unset) {
1450 auto_base = AUTO_BASE_NEVER;
1451 *base_commit = NULL;
1452 } else if (!strcmp(arg, "auto")) {
1453 auto_base = AUTO_BASE_ALWAYS;
1454 *base_commit = NULL;
1455 } else {
1456 auto_base = AUTO_BASE_NEVER;
1457 *base_commit = arg;
1459 return 0;
1462 struct base_tree_info {
1463 struct object_id base_commit;
1464 int nr_patch_id, alloc_patch_id;
1465 struct object_id *patch_id;
1468 static struct commit *get_base_commit(const char *base_commit,
1469 struct commit **list,
1470 int total)
1472 struct commit *base = NULL;
1473 struct commit **rev;
1474 int i = 0, rev_nr = 0, auto_select, die_on_failure;
1476 switch (auto_base) {
1477 case AUTO_BASE_NEVER:
1478 if (base_commit) {
1479 auto_select = 0;
1480 die_on_failure = 1;
1481 } else {
1482 /* no base information is requested */
1483 return NULL;
1485 break;
1486 case AUTO_BASE_ALWAYS:
1487 case AUTO_BASE_WHEN_ABLE:
1488 if (base_commit) {
1489 BUG("requested automatic base selection but a commit was provided");
1490 } else {
1491 auto_select = 1;
1492 die_on_failure = auto_base == AUTO_BASE_ALWAYS;
1494 break;
1495 default:
1496 BUG("unexpected automatic base selection method");
1499 if (!auto_select) {
1500 base = lookup_commit_reference_by_name(base_commit);
1501 if (!base)
1502 die(_("unknown commit %s"), base_commit);
1503 } else {
1504 struct branch *curr_branch = branch_get(NULL);
1505 const char *upstream = branch_get_upstream(curr_branch, NULL);
1506 if (upstream) {
1507 struct commit_list *base_list;
1508 struct commit *commit;
1509 struct object_id oid;
1511 if (get_oid(upstream, &oid)) {
1512 if (die_on_failure)
1513 die(_("failed to resolve '%s' as a valid ref"), upstream);
1514 else
1515 return NULL;
1517 commit = lookup_commit_or_die(&oid, "upstream base");
1518 base_list = get_merge_bases_many(commit, total, list);
1519 /* There should be one and only one merge base. */
1520 if (!base_list || base_list->next) {
1521 if (die_on_failure) {
1522 die(_("could not find exact merge base"));
1523 } else {
1524 free_commit_list(base_list);
1525 return NULL;
1528 base = base_list->item;
1529 free_commit_list(base_list);
1530 } else {
1531 if (die_on_failure)
1532 die(_("failed to get upstream, if you want to record base commit automatically,\n"
1533 "please use git branch --set-upstream-to to track a remote branch.\n"
1534 "Or you could specify base commit by --base=<base-commit-id> manually"));
1535 else
1536 return NULL;
1540 ALLOC_ARRAY(rev, total);
1541 for (i = 0; i < total; i++)
1542 rev[i] = list[i];
1544 rev_nr = total;
1546 * Get merge base through pair-wise computations
1547 * and store it in rev[0].
1549 while (rev_nr > 1) {
1550 for (i = 0; i < rev_nr / 2; i++) {
1551 struct commit_list *merge_base;
1552 merge_base = get_merge_bases(rev[2 * i], rev[2 * i + 1]);
1553 if (!merge_base || merge_base->next) {
1554 if (die_on_failure) {
1555 die(_("failed to find exact merge base"));
1556 } else {
1557 free(rev);
1558 return NULL;
1562 rev[i] = merge_base->item;
1565 if (rev_nr % 2)
1566 rev[i] = rev[2 * i];
1567 rev_nr = DIV_ROUND_UP(rev_nr, 2);
1570 if (!in_merge_bases(base, rev[0])) {
1571 if (die_on_failure) {
1572 die(_("base commit should be the ancestor of revision list"));
1573 } else {
1574 free(rev);
1575 return NULL;
1579 for (i = 0; i < total; i++) {
1580 if (base == list[i]) {
1581 if (die_on_failure) {
1582 die(_("base commit shouldn't be in revision list"));
1583 } else {
1584 free(rev);
1585 return NULL;
1590 free(rev);
1591 return base;
1594 define_commit_slab(commit_base, int);
1596 static void prepare_bases(struct base_tree_info *bases,
1597 struct commit *base,
1598 struct commit **list,
1599 int total)
1601 struct commit *commit;
1602 struct rev_info revs;
1603 struct diff_options diffopt;
1604 struct commit_base commit_base;
1605 int i;
1607 if (!base)
1608 return;
1610 init_commit_base(&commit_base);
1611 repo_diff_setup(the_repository, &diffopt);
1612 diffopt.flags.recursive = 1;
1613 diff_setup_done(&diffopt);
1615 oidcpy(&bases->base_commit, &base->object.oid);
1617 repo_init_revisions(the_repository, &revs, NULL);
1618 revs.max_parents = 1;
1619 revs.topo_order = 1;
1620 for (i = 0; i < total; i++) {
1621 list[i]->object.flags &= ~UNINTERESTING;
1622 add_pending_object(&revs, &list[i]->object, "rev_list");
1623 *commit_base_at(&commit_base, list[i]) = 1;
1625 base->object.flags |= UNINTERESTING;
1626 add_pending_object(&revs, &base->object, "base");
1628 if (prepare_revision_walk(&revs))
1629 die(_("revision walk setup failed"));
1631 * Traverse the commits list, get prerequisite patch ids
1632 * and stuff them in bases structure.
1634 while ((commit = get_revision(&revs)) != NULL) {
1635 struct object_id oid;
1636 struct object_id *patch_id;
1637 if (*commit_base_at(&commit_base, commit))
1638 continue;
1639 if (commit_patch_id(commit, &diffopt, &oid, 0, 1))
1640 die(_("cannot get patch id"));
1641 ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1642 patch_id = bases->patch_id + bases->nr_patch_id;
1643 oidcpy(patch_id, &oid);
1644 bases->nr_patch_id++;
1646 clear_commit_base(&commit_base);
1649 static void print_bases(struct base_tree_info *bases, FILE *file)
1651 int i;
1653 /* Only do this once, either for the cover or for the first one */
1654 if (is_null_oid(&bases->base_commit))
1655 return;
1657 /* Show the base commit */
1658 fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1660 /* Show the prerequisite patches */
1661 for (i = bases->nr_patch_id - 1; i >= 0; i--)
1662 fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1664 free(bases->patch_id);
1665 bases->nr_patch_id = 0;
1666 bases->alloc_patch_id = 0;
1667 oidclr(&bases->base_commit);
1670 static const char *diff_title(struct strbuf *sb,
1671 const char *reroll_count,
1672 const char *generic,
1673 const char *rerolled)
1675 int v;
1677 /* RFC may be v0, so allow -v1 to diff against v0 */
1678 if (reroll_count && !strtol_i(reroll_count, 10, &v) &&
1679 v >= 1)
1680 strbuf_addf(sb, rerolled, v - 1);
1681 else
1682 strbuf_addstr(sb, generic);
1683 return sb->buf;
1686 static void infer_range_diff_ranges(struct strbuf *r1,
1687 struct strbuf *r2,
1688 const char *prev,
1689 struct commit *origin,
1690 struct commit *head)
1692 const char *head_oid = oid_to_hex(&head->object.oid);
1693 int prev_is_range = is_range_diff_range(prev);
1695 if (prev_is_range)
1696 strbuf_addstr(r1, prev);
1697 else
1698 strbuf_addf(r1, "%s..%s", head_oid, prev);
1700 if (origin)
1701 strbuf_addf(r2, "%s..%s", oid_to_hex(&origin->object.oid), head_oid);
1702 else if (prev_is_range)
1703 die(_("failed to infer range-diff origin of current series"));
1704 else {
1705 warning(_("using '%s' as range-diff origin of current series"), prev);
1706 strbuf_addf(r2, "%s..%s", prev, head_oid);
1710 int cmd_format_patch(int argc, const char **argv, const char *prefix)
1712 struct commit *commit;
1713 struct commit **list = NULL;
1714 struct rev_info rev;
1715 struct setup_revision_opt s_r_opt;
1716 int nr = 0, total, i;
1717 int use_stdout = 0;
1718 int start_number = -1;
1719 int just_numbers = 0;
1720 int ignore_if_in_upstream = 0;
1721 int cover_letter = -1;
1722 int boundary_count = 0;
1723 int no_binary_diff = 0;
1724 int zero_commit = 0;
1725 struct commit *origin = NULL;
1726 const char *in_reply_to = NULL;
1727 struct patch_ids ids;
1728 struct strbuf buf = STRBUF_INIT;
1729 int use_patch_format = 0;
1730 int quiet = 0;
1731 const char *reroll_count = NULL;
1732 char *cover_from_description_arg = NULL;
1733 char *branch_name = NULL;
1734 char *base_commit = NULL;
1735 struct base_tree_info bases;
1736 struct commit *base;
1737 int show_progress = 0;
1738 struct progress *progress = NULL;
1739 struct oid_array idiff_prev = OID_ARRAY_INIT;
1740 struct strbuf idiff_title = STRBUF_INIT;
1741 const char *rdiff_prev = NULL;
1742 struct strbuf rdiff1 = STRBUF_INIT;
1743 struct strbuf rdiff2 = STRBUF_INIT;
1744 struct strbuf rdiff_title = STRBUF_INIT;
1745 int creation_factor = -1;
1747 const struct option builtin_format_patch_options[] = {
1748 OPT_CALLBACK_F('n', "numbered", &numbered, NULL,
1749 N_("use [PATCH n/m] even with a single patch"),
1750 PARSE_OPT_NOARG, numbered_callback),
1751 OPT_CALLBACK_F('N', "no-numbered", &numbered, NULL,
1752 N_("use [PATCH] even with multiple patches"),
1753 PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback),
1754 OPT_BOOL('s', "signoff", &do_signoff, N_("add a Signed-off-by trailer")),
1755 OPT_BOOL(0, "stdout", &use_stdout,
1756 N_("print patches to standard out")),
1757 OPT_BOOL(0, "cover-letter", &cover_letter,
1758 N_("generate a cover letter")),
1759 OPT_BOOL(0, "numbered-files", &just_numbers,
1760 N_("use simple number sequence for output file names")),
1761 OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
1762 N_("use <sfx> instead of '.patch'")),
1763 OPT_INTEGER(0, "start-number", &start_number,
1764 N_("start numbering patches at <n> instead of 1")),
1765 OPT_STRING('v', "reroll-count", &reroll_count, N_("reroll-count"),
1766 N_("mark the series as Nth re-roll")),
1767 OPT_INTEGER(0, "filename-max-length", &fmt_patch_name_max,
1768 N_("max length of output filename")),
1769 OPT_CALLBACK_F(0, "rfc", &rev, NULL,
1770 N_("use [RFC PATCH] instead of [PATCH]"),
1771 PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback),
1772 OPT_STRING(0, "cover-from-description", &cover_from_description_arg,
1773 N_("cover-from-description-mode"),
1774 N_("generate parts of a cover letter based on a branch's description")),
1775 OPT_CALLBACK_F(0, "subject-prefix", &rev, N_("prefix"),
1776 N_("use [<prefix>] instead of [PATCH]"),
1777 PARSE_OPT_NONEG, subject_prefix_callback),
1778 OPT_CALLBACK_F('o', "output-directory", &output_directory,
1779 N_("dir"), N_("store resulting files in <dir>"),
1780 PARSE_OPT_NONEG, output_directory_callback),
1781 OPT_CALLBACK_F('k', "keep-subject", &rev, NULL,
1782 N_("don't strip/add [PATCH]"),
1783 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback),
1784 OPT_BOOL(0, "no-binary", &no_binary_diff,
1785 N_("don't output binary diffs")),
1786 OPT_BOOL(0, "zero-commit", &zero_commit,
1787 N_("output all-zero hash in From header")),
1788 OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1789 N_("don't include a patch matching a commit upstream")),
1790 OPT_SET_INT_F('p', "no-stat", &use_patch_format,
1791 N_("show patch format instead of default (patch + stat)"),
1792 1, PARSE_OPT_NONEG),
1793 OPT_GROUP(N_("Messaging")),
1794 OPT_CALLBACK(0, "add-header", NULL, N_("header"),
1795 N_("add email header"), header_callback),
1796 OPT_CALLBACK(0, "to", NULL, N_("email"), N_("add To: header"), to_callback),
1797 OPT_CALLBACK(0, "cc", NULL, N_("email"), N_("add Cc: header"), cc_callback),
1798 OPT_CALLBACK_F(0, "from", &from, N_("ident"),
1799 N_("set From address to <ident> (or committer ident if absent)"),
1800 PARSE_OPT_OPTARG, from_callback),
1801 OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
1802 N_("make first mail a reply to <message-id>")),
1803 OPT_CALLBACK_F(0, "attach", &rev, N_("boundary"),
1804 N_("attach the patch"), PARSE_OPT_OPTARG,
1805 attach_callback),
1806 OPT_CALLBACK_F(0, "inline", &rev, N_("boundary"),
1807 N_("inline the patch"),
1808 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1809 inline_callback),
1810 OPT_CALLBACK_F(0, "thread", &thread, N_("style"),
1811 N_("enable message threading, styles: shallow, deep"),
1812 PARSE_OPT_OPTARG, thread_callback),
1813 OPT_STRING(0, "signature", &signature, N_("signature"),
1814 N_("add a signature")),
1815 OPT_CALLBACK_F(0, "base", &base_commit, N_("base-commit"),
1816 N_("add prerequisite tree info to the patch series"),
1817 0, base_callback),
1818 OPT_FILENAME(0, "signature-file", &signature_file,
1819 N_("add a signature from a file")),
1820 OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1821 OPT_BOOL(0, "progress", &show_progress,
1822 N_("show progress while generating patches")),
1823 OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
1824 N_("show changes against <rev> in cover letter or single patch"),
1825 parse_opt_object_name),
1826 OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
1827 N_("show changes against <refspec> in cover letter or single patch")),
1828 OPT_INTEGER(0, "creation-factor", &creation_factor,
1829 N_("percentage by which creation is weighted")),
1830 OPT_END()
1833 extra_hdr.strdup_strings = 1;
1834 extra_to.strdup_strings = 1;
1835 extra_cc.strdup_strings = 1;
1836 init_log_defaults();
1837 init_display_notes(&notes_opt);
1838 git_config(git_format_config, NULL);
1839 repo_init_revisions(the_repository, &rev, prefix);
1840 rev.show_notes = show_notes;
1841 memcpy(&rev.notes_opt, &notes_opt, sizeof(notes_opt));
1842 rev.commit_format = CMIT_FMT_EMAIL;
1843 rev.encode_email_headers = default_encode_email_headers;
1844 rev.expand_tabs_in_log_default = 0;
1845 rev.verbose_header = 1;
1846 rev.diff = 1;
1847 rev.max_parents = 1;
1848 rev.diffopt.flags.recursive = 1;
1849 rev.subject_prefix = fmt_patch_subject_prefix;
1850 memset(&s_r_opt, 0, sizeof(s_r_opt));
1851 s_r_opt.def = "HEAD";
1852 s_r_opt.revarg_opt = REVARG_COMMITTISH;
1854 if (default_attach) {
1855 rev.mime_boundary = default_attach;
1856 rev.no_inline = 1;
1860 * Parse the arguments before setup_revisions(), or something
1861 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1862 * possibly a valid SHA1.
1864 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1865 builtin_format_patch_usage,
1866 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1867 PARSE_OPT_KEEP_DASHDASH);
1869 /* Make sure "0000-$sub.patch" gives non-negative length for $sub */
1870 if (fmt_patch_name_max <= strlen("0000-") + strlen(fmt_patch_suffix))
1871 fmt_patch_name_max = strlen("0000-") + strlen(fmt_patch_suffix);
1873 if (cover_from_description_arg)
1874 cover_from_description_mode = parse_cover_from_description(cover_from_description_arg);
1876 if (reroll_count) {
1877 struct strbuf sprefix = STRBUF_INIT;
1879 strbuf_addf(&sprefix, "%s v%s",
1880 rev.subject_prefix, reroll_count);
1881 rev.reroll_count = reroll_count;
1882 rev.subject_prefix = strbuf_detach(&sprefix, NULL);
1885 for (i = 0; i < extra_hdr.nr; i++) {
1886 strbuf_addstr(&buf, extra_hdr.items[i].string);
1887 strbuf_addch(&buf, '\n');
1890 if (extra_to.nr)
1891 strbuf_addstr(&buf, "To: ");
1892 for (i = 0; i < extra_to.nr; i++) {
1893 if (i)
1894 strbuf_addstr(&buf, " ");
1895 strbuf_addstr(&buf, extra_to.items[i].string);
1896 if (i + 1 < extra_to.nr)
1897 strbuf_addch(&buf, ',');
1898 strbuf_addch(&buf, '\n');
1901 if (extra_cc.nr)
1902 strbuf_addstr(&buf, "Cc: ");
1903 for (i = 0; i < extra_cc.nr; i++) {
1904 if (i)
1905 strbuf_addstr(&buf, " ");
1906 strbuf_addstr(&buf, extra_cc.items[i].string);
1907 if (i + 1 < extra_cc.nr)
1908 strbuf_addch(&buf, ',');
1909 strbuf_addch(&buf, '\n');
1912 rev.extra_headers = strbuf_detach(&buf, NULL);
1914 if (from) {
1915 if (split_ident_line(&rev.from_ident, from, strlen(from)))
1916 die(_("invalid ident line: %s"), from);
1919 if (start_number < 0)
1920 start_number = 1;
1923 * If numbered is set solely due to format.numbered in config,
1924 * and it would conflict with --keep-subject (-k) from the
1925 * command line, reset "numbered".
1927 if (numbered && keep_subject && !numbered_cmdline_opt)
1928 numbered = 0;
1930 if (numbered && keep_subject)
1931 die(_("-n and -k are mutually exclusive"));
1932 if (keep_subject && subject_prefix)
1933 die(_("--subject-prefix/--rfc and -k are mutually exclusive"));
1934 rev.preserve_subject = keep_subject;
1936 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1937 if (argc > 1)
1938 die(_("unrecognized argument: %s"), argv[1]);
1940 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1941 die(_("--name-only does not make sense"));
1942 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1943 die(_("--name-status does not make sense"));
1944 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1945 die(_("--check does not make sense"));
1947 if (!use_patch_format &&
1948 (!rev.diffopt.output_format ||
1949 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1950 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1951 if (!rev.diffopt.stat_width)
1952 rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
1954 /* Always generate a patch */
1955 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1957 rev.zero_commit = zero_commit;
1958 rev.patch_name_max = fmt_patch_name_max;
1960 if (!rev.diffopt.flags.text && !no_binary_diff)
1961 rev.diffopt.flags.binary = 1;
1963 if (rev.show_notes)
1964 load_display_notes(&rev.notes_opt);
1966 if (use_stdout + rev.diffopt.close_file + !!output_directory > 1)
1967 die(_("--stdout, --output, and --output-directory are mutually exclusive"));
1969 if (use_stdout) {
1970 setup_pager();
1971 } else if (rev.diffopt.close_file) {
1973 * The diff code parsed --output; it has already opened the
1974 * file, but we must instruct it not to close after each diff.
1976 rev.diffopt.no_free = 1;
1977 } else {
1978 int saved;
1980 if (!output_directory)
1981 output_directory = config_output_directory;
1982 output_directory = set_outdir(prefix, output_directory);
1984 if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
1985 rev.diffopt.use_color = GIT_COLOR_NEVER;
1987 * We consider <outdir> as 'outside of gitdir', therefore avoid
1988 * applying adjust_shared_perm in s-c-l-d.
1990 saved = get_shared_repository();
1991 set_shared_repository(0);
1992 switch (safe_create_leading_directories_const(output_directory)) {
1993 case SCLD_OK:
1994 case SCLD_EXISTS:
1995 break;
1996 default:
1997 die(_("could not create leading directories "
1998 "of '%s'"), output_directory);
2000 set_shared_repository(saved);
2001 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
2002 die_errno(_("could not create directory '%s'"),
2003 output_directory);
2006 if (rev.pending.nr == 1) {
2007 int check_head = 0;
2009 if (rev.max_count < 0 && !rev.show_root_diff) {
2011 * This is traditional behaviour of "git format-patch
2012 * origin" that prepares what the origin side still
2013 * does not have.
2015 rev.pending.objects[0].item->flags |= UNINTERESTING;
2016 add_head_to_pending(&rev);
2017 check_head = 1;
2020 * Otherwise, it is "format-patch -22 HEAD", and/or
2021 * "format-patch --root HEAD". The user wants
2022 * get_revision() to do the usual traversal.
2025 if (!strcmp(rev.pending.objects[0].name, "HEAD"))
2026 check_head = 1;
2028 if (check_head) {
2029 const char *ref, *v;
2030 ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2031 NULL, NULL);
2032 if (ref && skip_prefix(ref, "refs/heads/", &v))
2033 branch_name = xstrdup(v);
2034 else
2035 branch_name = xstrdup(""); /* no branch */
2040 * We cannot move this anywhere earlier because we do want to
2041 * know if --root was given explicitly from the command line.
2043 rev.show_root_diff = 1;
2045 if (ignore_if_in_upstream) {
2046 /* Don't say anything if head and upstream are the same. */
2047 if (rev.pending.nr == 2) {
2048 struct object_array_entry *o = rev.pending.objects;
2049 if (oideq(&o[0].item->oid, &o[1].item->oid))
2050 goto done;
2052 get_patch_ids(&rev, &ids);
2055 if (prepare_revision_walk(&rev))
2056 die(_("revision walk setup failed"));
2057 rev.boundary = 1;
2058 while ((commit = get_revision(&rev)) != NULL) {
2059 if (commit->object.flags & BOUNDARY) {
2060 boundary_count++;
2061 origin = (boundary_count == 1) ? commit : NULL;
2062 continue;
2065 if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
2066 continue;
2068 nr++;
2069 REALLOC_ARRAY(list, nr);
2070 list[nr - 1] = commit;
2072 if (nr == 0)
2073 /* nothing to do */
2074 goto done;
2075 total = nr;
2076 if (cover_letter == -1) {
2077 if (config_cover_letter == COVER_AUTO)
2078 cover_letter = (total > 1);
2079 else
2080 cover_letter = (config_cover_letter == COVER_ON);
2082 if (!keep_subject && auto_number && (total > 1 || cover_letter))
2083 numbered = 1;
2084 if (numbered)
2085 rev.total = total + start_number - 1;
2087 if (idiff_prev.nr) {
2088 if (!cover_letter && total != 1)
2089 die(_("--interdiff requires --cover-letter or single patch"));
2090 rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
2091 rev.idiff_oid2 = get_commit_tree_oid(list[0]);
2092 rev.idiff_title = diff_title(&idiff_title, reroll_count,
2093 _("Interdiff:"),
2094 _("Interdiff against v%d:"));
2097 if (creation_factor < 0)
2098 creation_factor = RANGE_DIFF_CREATION_FACTOR_DEFAULT;
2099 else if (!rdiff_prev)
2100 die(_("--creation-factor requires --range-diff"));
2102 if (rdiff_prev) {
2103 if (!cover_letter && total != 1)
2104 die(_("--range-diff requires --cover-letter or single patch"));
2106 infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
2107 origin, list[0]);
2108 rev.rdiff1 = rdiff1.buf;
2109 rev.rdiff2 = rdiff2.buf;
2110 rev.creation_factor = creation_factor;
2111 rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
2112 _("Range-diff:"),
2113 _("Range-diff against v%d:"));
2116 if (!signature) {
2117 ; /* --no-signature inhibits all signatures */
2118 } else if (signature && signature != git_version_string) {
2119 ; /* non-default signature already set */
2120 } else if (signature_file) {
2121 struct strbuf buf = STRBUF_INIT;
2123 if (strbuf_read_file(&buf, signature_file, 128) < 0)
2124 die_errno(_("unable to read signature file '%s'"), signature_file);
2125 signature = strbuf_detach(&buf, NULL);
2128 memset(&bases, 0, sizeof(bases));
2129 base = get_base_commit(base_commit, list, nr);
2130 if (base) {
2131 reset_revision_walk();
2132 clear_object_flags(UNINTERESTING);
2133 prepare_bases(&bases, base, list, nr);
2136 if (in_reply_to || thread || cover_letter)
2137 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
2138 if (in_reply_to) {
2139 const char *msgid = clean_message_id(in_reply_to);
2140 string_list_append(rev.ref_message_ids, msgid);
2142 rev.numbered_files = just_numbers;
2143 rev.patch_suffix = fmt_patch_suffix;
2144 if (cover_letter) {
2145 if (thread)
2146 gen_message_id(&rev, "cover");
2147 make_cover_letter(&rev, !!output_directory,
2148 origin, nr, list, branch_name, quiet);
2149 print_bases(&bases, rev.diffopt.file);
2150 print_signature(rev.diffopt.file);
2151 total++;
2152 start_number--;
2153 /* interdiff/range-diff in cover-letter; omit from patches */
2154 rev.idiff_oid1 = NULL;
2155 rev.rdiff1 = NULL;
2157 rev.add_signoff = do_signoff;
2159 if (show_progress)
2160 progress = start_delayed_progress(_("Generating patches"), total);
2161 while (0 <= --nr) {
2162 int shown;
2163 display_progress(progress, total - nr);
2164 commit = list[nr];
2165 rev.nr = total - nr + (start_number - 1);
2166 /* Make the second and subsequent mails replies to the first */
2167 if (thread) {
2168 /* Have we already had a message ID? */
2169 if (rev.message_id) {
2171 * For deep threading: make every mail
2172 * a reply to the previous one, no
2173 * matter what other options are set.
2175 * For shallow threading:
2177 * Without --cover-letter and
2178 * --in-reply-to, make every mail a
2179 * reply to the one before.
2181 * With --in-reply-to but no
2182 * --cover-letter, make every mail a
2183 * reply to the <reply-to>.
2185 * With --cover-letter, make every
2186 * mail but the cover letter a reply
2187 * to the cover letter. The cover
2188 * letter is a reply to the
2189 * --in-reply-to, if specified.
2191 if (thread == THREAD_SHALLOW
2192 && rev.ref_message_ids->nr > 0
2193 && (!cover_letter || rev.nr > 1))
2194 free(rev.message_id);
2195 else
2196 string_list_append(rev.ref_message_ids,
2197 rev.message_id);
2199 gen_message_id(&rev, oid_to_hex(&commit->object.oid));
2202 if (output_directory &&
2203 open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
2204 die(_("failed to create output files"));
2205 shown = log_tree_commit(&rev, commit);
2206 free_commit_buffer(the_repository->parsed_objects,
2207 commit);
2209 /* We put one extra blank line between formatted
2210 * patches and this flag is used by log-tree code
2211 * to see if it needs to emit a LF before showing
2212 * the log; when using one file per patch, we do
2213 * not want the extra blank line.
2215 if (output_directory)
2216 rev.shown_one = 0;
2217 if (shown) {
2218 print_bases(&bases, rev.diffopt.file);
2219 if (rev.mime_boundary)
2220 fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
2221 mime_boundary_leader,
2222 rev.mime_boundary);
2223 else
2224 print_signature(rev.diffopt.file);
2226 if (output_directory)
2227 fclose(rev.diffopt.file);
2229 stop_progress(&progress);
2230 free(list);
2231 free(branch_name);
2232 string_list_clear(&extra_to, 0);
2233 string_list_clear(&extra_cc, 0);
2234 string_list_clear(&extra_hdr, 0);
2235 if (ignore_if_in_upstream)
2236 free_patch_ids(&ids);
2238 done:
2239 oid_array_clear(&idiff_prev);
2240 strbuf_release(&idiff_title);
2241 strbuf_release(&rdiff1);
2242 strbuf_release(&rdiff2);
2243 strbuf_release(&rdiff_title);
2244 return 0;
2247 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
2249 struct object_id oid;
2250 if (get_oid(arg, &oid) == 0) {
2251 struct commit *commit = lookup_commit_reference(the_repository,
2252 &oid);
2253 if (commit) {
2254 commit->object.flags |= flags;
2255 add_pending_object(revs, &commit->object, arg);
2256 return 0;
2259 return -1;
2262 static const char * const cherry_usage[] = {
2263 N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
2264 NULL
2267 static void print_commit(char sign, struct commit *commit, int verbose,
2268 int abbrev, FILE *file)
2270 if (!verbose) {
2271 fprintf(file, "%c %s\n", sign,
2272 find_unique_abbrev(&commit->object.oid, abbrev));
2273 } else {
2274 struct strbuf buf = STRBUF_INIT;
2275 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2276 fprintf(file, "%c %s %s\n", sign,
2277 find_unique_abbrev(&commit->object.oid, abbrev),
2278 buf.buf);
2279 strbuf_release(&buf);
2283 int cmd_cherry(int argc, const char **argv, const char *prefix)
2285 struct rev_info revs;
2286 struct patch_ids ids;
2287 struct commit *commit;
2288 struct commit_list *list = NULL;
2289 struct branch *current_branch;
2290 const char *upstream;
2291 const char *head = "HEAD";
2292 const char *limit = NULL;
2293 int verbose = 0, abbrev = 0;
2295 struct option options[] = {
2296 OPT__ABBREV(&abbrev),
2297 OPT__VERBOSE(&verbose, N_("be verbose")),
2298 OPT_END()
2301 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
2303 switch (argc) {
2304 case 3:
2305 limit = argv[2];
2306 /* FALLTHROUGH */
2307 case 2:
2308 head = argv[1];
2309 /* FALLTHROUGH */
2310 case 1:
2311 upstream = argv[0];
2312 break;
2313 default:
2314 current_branch = branch_get(NULL);
2315 upstream = branch_get_upstream(current_branch, NULL);
2316 if (!upstream) {
2317 fprintf(stderr, _("Could not find a tracked"
2318 " remote branch, please"
2319 " specify <upstream> manually.\n"));
2320 usage_with_options(cherry_usage, options);
2324 repo_init_revisions(the_repository, &revs, prefix);
2325 revs.max_parents = 1;
2327 if (add_pending_commit(head, &revs, 0))
2328 die(_("unknown commit %s"), head);
2329 if (add_pending_commit(upstream, &revs, UNINTERESTING))
2330 die(_("unknown commit %s"), upstream);
2332 /* Don't say anything if head and upstream are the same. */
2333 if (revs.pending.nr == 2) {
2334 struct object_array_entry *o = revs.pending.objects;
2335 if (oideq(&o[0].item->oid, &o[1].item->oid))
2336 return 0;
2339 get_patch_ids(&revs, &ids);
2341 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2342 die(_("unknown commit %s"), limit);
2344 /* reverse the list of commits */
2345 if (prepare_revision_walk(&revs))
2346 die(_("revision walk setup failed"));
2347 while ((commit = get_revision(&revs)) != NULL) {
2348 commit_list_insert(commit, &list);
2351 while (list) {
2352 char sign = '+';
2354 commit = list->item;
2355 if (has_commit_patch_id(commit, &ids))
2356 sign = '-';
2357 print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2358 list = list->next;
2361 free_patch_ids(&ids);
2362 return 0;