Merge branch 'js/reflog-expire-stale-fix'
[alt-git.git] / builtin / log.c
blobbe29c3f89fc0b60ffa77aa0ebf0d083792f2ba8c
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, close_file = revs->diffopt.close_file;
311 int show_header = 1;
313 revs->diffopt.close_file = 0;
314 sort_in_topological_order(&list, revs->sort_order);
315 while (list && i) {
316 struct commit *commit = list->item;
317 switch (simplify_commit(revs, commit)) {
318 case commit_show:
319 if (show_header) {
320 int n = estimate_commit_count(list);
321 show_early_header(revs, "incomplete", n);
322 show_header = 0;
324 log_tree_commit(revs, commit);
325 i--;
326 break;
327 case commit_ignore:
328 break;
329 case commit_error:
330 if (close_file)
331 fclose(revs->diffopt.file);
332 return;
334 list = list->next;
337 /* Did we already get enough commits for the early output? */
338 if (!i) {
339 if (close_file)
340 fclose(revs->diffopt.file);
341 return;
345 * ..if no, then repeat it twice a second until we
346 * do.
348 * NOTE! We don't use "it_interval", because if the
349 * reader isn't listening, we want our output to be
350 * throttled by the writing, and not have the timer
351 * trigger every second even if we're blocked on a
352 * reader!
354 early_output_timer.it_value.tv_sec = 0;
355 early_output_timer.it_value.tv_usec = 500000;
356 setitimer(ITIMER_REAL, &early_output_timer, NULL);
359 static void early_output(int signal)
361 show_early_output = log_show_early;
364 static void setup_early_output(void)
366 struct sigaction sa;
369 * Set up the signal handler, minimally intrusively:
370 * we only set a single volatile integer word (not
371 * using sigatomic_t - trying to avoid unnecessary
372 * system dependencies and headers), and using
373 * SA_RESTART.
375 memset(&sa, 0, sizeof(sa));
376 sa.sa_handler = early_output;
377 sigemptyset(&sa.sa_mask);
378 sa.sa_flags = SA_RESTART;
379 sigaction(SIGALRM, &sa, NULL);
382 * If we can get the whole output in less than a
383 * tenth of a second, don't even bother doing the
384 * early-output thing..
386 * This is a one-time-only trigger.
388 early_output_timer.it_value.tv_sec = 0;
389 early_output_timer.it_value.tv_usec = 100000;
390 setitimer(ITIMER_REAL, &early_output_timer, NULL);
393 static void finish_early_output(struct rev_info *rev)
395 int n = estimate_commit_count(rev->commits);
396 signal(SIGALRM, SIG_IGN);
397 show_early_header(rev, "done", n);
400 static int cmd_log_walk(struct rev_info *rev)
402 struct commit *commit;
403 int saved_nrl = 0;
404 int saved_dcctc = 0, close_file = rev->diffopt.close_file;
406 if (rev->early_output)
407 setup_early_output();
409 if (prepare_revision_walk(rev))
410 die(_("revision walk setup failed"));
412 if (rev->early_output)
413 finish_early_output(rev);
416 * For --check and --exit-code, the exit code is based on CHECK_FAILED
417 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
418 * retain that state information if replacing rev->diffopt in this loop
420 rev->diffopt.close_file = 0;
421 while ((commit = get_revision(rev)) != NULL) {
422 if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
424 * We decremented max_count in get_revision,
425 * but we didn't actually show the commit.
427 rev->max_count++;
428 if (!rev->reflog_info) {
430 * We may show a given commit multiple times when
431 * walking the reflogs.
433 free_commit_buffer(the_repository->parsed_objects,
434 commit);
435 free_commit_list(commit->parents);
436 commit->parents = NULL;
438 if (saved_nrl < rev->diffopt.needed_rename_limit)
439 saved_nrl = rev->diffopt.needed_rename_limit;
440 if (rev->diffopt.degraded_cc_to_c)
441 saved_dcctc = 1;
443 rev->diffopt.degraded_cc_to_c = saved_dcctc;
444 rev->diffopt.needed_rename_limit = saved_nrl;
445 if (close_file)
446 fclose(rev->diffopt.file);
448 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
449 rev->diffopt.flags.check_failed) {
450 return 02;
452 return diff_result_code(&rev->diffopt, 0);
455 static int git_log_config(const char *var, const char *value, void *cb)
457 const char *slot_name;
459 if (!strcmp(var, "format.pretty"))
460 return git_config_string(&fmt_pretty, var, value);
461 if (!strcmp(var, "format.subjectprefix"))
462 return git_config_string(&fmt_patch_subject_prefix, var, value);
463 if (!strcmp(var, "format.filenamemaxlength")) {
464 fmt_patch_name_max = git_config_int(var, value);
465 return 0;
467 if (!strcmp(var, "format.encodeemailheaders")) {
468 default_encode_email_headers = git_config_bool(var, value);
469 return 0;
471 if (!strcmp(var, "log.abbrevcommit")) {
472 default_abbrev_commit = git_config_bool(var, value);
473 return 0;
475 if (!strcmp(var, "log.date"))
476 return git_config_string(&default_date_mode, var, value);
477 if (!strcmp(var, "log.decorate")) {
478 decoration_style = parse_decoration_style(value);
479 if (decoration_style < 0)
480 decoration_style = 0; /* maybe warn? */
481 return 0;
483 if (!strcmp(var, "log.showroot")) {
484 default_show_root = git_config_bool(var, value);
485 return 0;
487 if (!strcmp(var, "log.follow")) {
488 default_follow = git_config_bool(var, value);
489 return 0;
491 if (skip_prefix(var, "color.decorate.", &slot_name))
492 return parse_decorate_color_config(var, slot_name, value);
493 if (!strcmp(var, "log.mailmap")) {
494 use_mailmap_config = git_config_bool(var, value);
495 return 0;
497 if (!strcmp(var, "log.showsignature")) {
498 default_show_signature = git_config_bool(var, value);
499 return 0;
502 if (grep_config(var, value, cb) < 0)
503 return -1;
504 if (git_gpg_config(var, value, cb) < 0)
505 return -1;
506 return git_diff_ui_config(var, value, cb);
509 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
511 struct rev_info rev;
512 struct setup_revision_opt opt;
514 init_log_defaults();
515 git_config(git_log_config, NULL);
517 repo_init_revisions(the_repository, &rev, prefix);
518 rev.diff = 1;
519 rev.simplify_history = 0;
520 memset(&opt, 0, sizeof(opt));
521 opt.def = "HEAD";
522 opt.revarg_opt = REVARG_COMMITTISH;
523 cmd_log_init(argc, argv, prefix, &rev, &opt);
524 if (!rev.diffopt.output_format)
525 rev.diffopt.output_format = DIFF_FORMAT_RAW;
526 return cmd_log_walk(&rev);
529 static void show_tagger(const char *buf, struct rev_info *rev)
531 struct strbuf out = STRBUF_INIT;
532 struct pretty_print_context pp = {0};
534 pp.fmt = rev->commit_format;
535 pp.date_mode = rev->date_mode;
536 pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
537 fprintf(rev->diffopt.file, "%s", out.buf);
538 strbuf_release(&out);
541 static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
543 struct object_id oidc;
544 struct object_context obj_context;
545 char *buf;
546 unsigned long size;
548 fflush(rev->diffopt.file);
549 if (!rev->diffopt.flags.textconv_set_via_cmdline ||
550 !rev->diffopt.flags.allow_textconv)
551 return stream_blob_to_fd(1, oid, NULL, 0);
553 if (get_oid_with_context(the_repository, obj_name,
554 GET_OID_RECORD_PATH,
555 &oidc, &obj_context))
556 die(_("not a valid object name %s"), obj_name);
557 if (!obj_context.path ||
558 !textconv_object(the_repository, obj_context.path,
559 obj_context.mode, &oidc, 1, &buf, &size)) {
560 free(obj_context.path);
561 return stream_blob_to_fd(1, oid, NULL, 0);
564 if (!buf)
565 die(_("git show %s: bad file"), obj_name);
567 write_or_die(1, buf, size);
568 free(obj_context.path);
569 return 0;
572 static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
574 unsigned long size;
575 enum object_type type;
576 char *buf = read_object_file(oid, &type, &size);
577 int offset = 0;
579 if (!buf)
580 return error(_("could not read object %s"), oid_to_hex(oid));
582 assert(type == OBJ_TAG);
583 while (offset < size && buf[offset] != '\n') {
584 int new_offset = offset + 1;
585 const char *ident;
586 while (new_offset < size && buf[new_offset++] != '\n')
587 ; /* do nothing */
588 if (skip_prefix(buf + offset, "tagger ", &ident))
589 show_tagger(ident, rev);
590 offset = new_offset;
593 if (offset < size)
594 fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
595 free(buf);
596 return 0;
599 static int show_tree_object(const struct object_id *oid,
600 struct strbuf *base,
601 const char *pathname, unsigned mode, int stage, void *context)
603 FILE *file = context;
604 fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
605 return 0;
608 static void show_setup_revisions_tweak(struct rev_info *rev,
609 struct setup_revision_opt *opt)
611 if (rev->first_parent_only)
612 diff_merges_default_to_first_parent(rev);
613 else
614 diff_merges_default_to_dense_combined(rev);
615 if (!rev->diffopt.output_format)
616 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
619 int cmd_show(int argc, const char **argv, const char *prefix)
621 struct rev_info rev;
622 struct object_array_entry *objects;
623 struct setup_revision_opt opt;
624 struct pathspec match_all;
625 int i, count, ret = 0;
627 init_log_defaults();
628 git_config(git_log_config, NULL);
630 memset(&match_all, 0, sizeof(match_all));
631 repo_init_revisions(the_repository, &rev, prefix);
632 rev.diff = 1;
633 rev.always_show_header = 1;
634 rev.no_walk = REVISION_WALK_NO_WALK_SORTED;
635 rev.diffopt.stat_width = -1; /* Scale to real terminal size */
637 memset(&opt, 0, sizeof(opt));
638 opt.def = "HEAD";
639 opt.tweak = show_setup_revisions_tweak;
640 cmd_log_init(argc, argv, prefix, &rev, &opt);
642 if (!rev.no_walk)
643 return cmd_log_walk(&rev);
645 count = rev.pending.nr;
646 objects = rev.pending.objects;
647 for (i = 0; i < count && !ret; i++) {
648 struct object *o = objects[i].item;
649 const char *name = objects[i].name;
650 switch (o->type) {
651 case OBJ_BLOB:
652 ret = show_blob_object(&o->oid, &rev, name);
653 break;
654 case OBJ_TAG: {
655 struct tag *t = (struct tag *)o;
656 struct object_id *oid = get_tagged_oid(t);
658 if (rev.shown_one)
659 putchar('\n');
660 fprintf(rev.diffopt.file, "%stag %s%s\n",
661 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
662 t->tag,
663 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
664 ret = show_tag_object(&o->oid, &rev);
665 rev.shown_one = 1;
666 if (ret)
667 break;
668 o = parse_object(the_repository, oid);
669 if (!o)
670 ret = error(_("could not read object %s"),
671 oid_to_hex(oid));
672 objects[i].item = o;
673 i--;
674 break;
676 case OBJ_TREE:
677 if (rev.shown_one)
678 putchar('\n');
679 fprintf(rev.diffopt.file, "%stree %s%s\n\n",
680 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
681 name,
682 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
683 read_tree_recursive(the_repository, (struct tree *)o, "",
684 0, 0, &match_all, show_tree_object,
685 rev.diffopt.file);
686 rev.shown_one = 1;
687 break;
688 case OBJ_COMMIT:
689 rev.pending.nr = rev.pending.alloc = 0;
690 rev.pending.objects = NULL;
691 add_object_array(o, name, &rev.pending);
692 ret = cmd_log_walk(&rev);
693 break;
694 default:
695 ret = error(_("unknown type: %d"), o->type);
698 free(objects);
699 return ret;
703 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
705 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
707 struct rev_info rev;
708 struct setup_revision_opt opt;
710 init_log_defaults();
711 git_config(git_log_config, NULL);
713 repo_init_revisions(the_repository, &rev, prefix);
714 init_reflog_walk(&rev.reflog_info);
715 rev.verbose_header = 1;
716 memset(&opt, 0, sizeof(opt));
717 opt.def = "HEAD";
718 cmd_log_init_defaults(&rev);
719 rev.abbrev_commit = 1;
720 rev.commit_format = CMIT_FMT_ONELINE;
721 rev.use_terminator = 1;
722 rev.always_show_header = 1;
723 cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
725 return cmd_log_walk(&rev);
728 static void log_setup_revisions_tweak(struct rev_info *rev,
729 struct setup_revision_opt *opt)
731 if (rev->diffopt.flags.default_follow_renames &&
732 rev->prune_data.nr == 1)
733 rev->diffopt.flags.follow_renames = 1;
735 if (rev->first_parent_only)
736 diff_merges_default_to_first_parent(rev);
739 int cmd_log(int argc, const char **argv, const char *prefix)
741 struct rev_info rev;
742 struct setup_revision_opt opt;
744 init_log_defaults();
745 git_config(git_log_config, NULL);
747 repo_init_revisions(the_repository, &rev, prefix);
748 rev.always_show_header = 1;
749 memset(&opt, 0, sizeof(opt));
750 opt.def = "HEAD";
751 opt.revarg_opt = REVARG_COMMITTISH;
752 opt.tweak = log_setup_revisions_tweak;
753 cmd_log_init(argc, argv, prefix, &rev, &opt);
754 return cmd_log_walk(&rev);
757 /* format-patch */
759 static const char *fmt_patch_suffix = ".patch";
760 static int numbered = 0;
761 static int auto_number = 1;
763 static char *default_attach = NULL;
765 static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
766 static struct string_list extra_to = STRING_LIST_INIT_NODUP;
767 static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
769 static void add_header(const char *value)
771 struct string_list_item *item;
772 int len = strlen(value);
773 while (len && value[len - 1] == '\n')
774 len--;
776 if (!strncasecmp(value, "to: ", 4)) {
777 item = string_list_append(&extra_to, value + 4);
778 len -= 4;
779 } else if (!strncasecmp(value, "cc: ", 4)) {
780 item = string_list_append(&extra_cc, value + 4);
781 len -= 4;
782 } else {
783 item = string_list_append(&extra_hdr, value);
786 item->string[len] = '\0';
789 enum cover_setting {
790 COVER_UNSET,
791 COVER_OFF,
792 COVER_ON,
793 COVER_AUTO
796 enum thread_level {
797 THREAD_UNSET,
798 THREAD_SHALLOW,
799 THREAD_DEEP
802 enum cover_from_description {
803 COVER_FROM_NONE,
804 COVER_FROM_MESSAGE,
805 COVER_FROM_SUBJECT,
806 COVER_FROM_AUTO
809 enum auto_base_setting {
810 AUTO_BASE_NEVER,
811 AUTO_BASE_ALWAYS,
812 AUTO_BASE_WHEN_ABLE
815 static enum thread_level thread;
816 static int do_signoff;
817 static enum auto_base_setting auto_base;
818 static char *from;
819 static const char *signature = git_version_string;
820 static const char *signature_file;
821 static enum cover_setting config_cover_letter;
822 static const char *config_output_directory;
823 static enum cover_from_description cover_from_description_mode = COVER_FROM_MESSAGE;
824 static int show_notes;
825 static struct display_notes_opt notes_opt;
827 static enum cover_from_description parse_cover_from_description(const char *arg)
829 if (!arg || !strcmp(arg, "default"))
830 return COVER_FROM_MESSAGE;
831 else if (!strcmp(arg, "none"))
832 return COVER_FROM_NONE;
833 else if (!strcmp(arg, "message"))
834 return COVER_FROM_MESSAGE;
835 else if (!strcmp(arg, "subject"))
836 return COVER_FROM_SUBJECT;
837 else if (!strcmp(arg, "auto"))
838 return COVER_FROM_AUTO;
839 else
840 die(_("%s: invalid cover from description mode"), arg);
843 static int git_format_config(const char *var, const char *value, void *cb)
845 if (!strcmp(var, "format.headers")) {
846 if (!value)
847 die(_("format.headers without value"));
848 add_header(value);
849 return 0;
851 if (!strcmp(var, "format.suffix"))
852 return git_config_string(&fmt_patch_suffix, var, value);
853 if (!strcmp(var, "format.to")) {
854 if (!value)
855 return config_error_nonbool(var);
856 string_list_append(&extra_to, value);
857 return 0;
859 if (!strcmp(var, "format.cc")) {
860 if (!value)
861 return config_error_nonbool(var);
862 string_list_append(&extra_cc, value);
863 return 0;
865 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
866 !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
867 return 0;
869 if (!strcmp(var, "format.numbered")) {
870 if (value && !strcasecmp(value, "auto")) {
871 auto_number = 1;
872 return 0;
874 numbered = git_config_bool(var, value);
875 auto_number = auto_number && numbered;
876 return 0;
878 if (!strcmp(var, "format.attach")) {
879 if (value && *value)
880 default_attach = xstrdup(value);
881 else
882 default_attach = xstrdup(git_version_string);
883 return 0;
885 if (!strcmp(var, "format.thread")) {
886 if (value && !strcasecmp(value, "deep")) {
887 thread = THREAD_DEEP;
888 return 0;
890 if (value && !strcasecmp(value, "shallow")) {
891 thread = THREAD_SHALLOW;
892 return 0;
894 thread = git_config_bool(var, value) ? THREAD_SHALLOW : THREAD_UNSET;
895 return 0;
897 if (!strcmp(var, "format.signoff")) {
898 do_signoff = git_config_bool(var, value);
899 return 0;
901 if (!strcmp(var, "format.signature"))
902 return git_config_string(&signature, var, value);
903 if (!strcmp(var, "format.signaturefile"))
904 return git_config_pathname(&signature_file, var, value);
905 if (!strcmp(var, "format.coverletter")) {
906 if (value && !strcasecmp(value, "auto")) {
907 config_cover_letter = COVER_AUTO;
908 return 0;
910 config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
911 return 0;
913 if (!strcmp(var, "format.outputdirectory"))
914 return git_config_string(&config_output_directory, var, value);
915 if (!strcmp(var, "format.useautobase")) {
916 if (value && !strcasecmp(value, "whenAble")) {
917 auto_base = AUTO_BASE_WHEN_ABLE;
918 return 0;
920 auto_base = git_config_bool(var, value) ? AUTO_BASE_ALWAYS : AUTO_BASE_NEVER;
921 return 0;
923 if (!strcmp(var, "format.from")) {
924 int b = git_parse_maybe_bool(value);
925 free(from);
926 if (b < 0)
927 from = xstrdup(value);
928 else if (b)
929 from = xstrdup(git_committer_info(IDENT_NO_DATE));
930 else
931 from = NULL;
932 return 0;
934 if (!strcmp(var, "format.notes")) {
935 int b = git_parse_maybe_bool(value);
936 if (b < 0)
937 enable_ref_display_notes(&notes_opt, &show_notes, value);
938 else if (b)
939 enable_default_display_notes(&notes_opt, &show_notes);
940 else
941 disable_display_notes(&notes_opt, &show_notes);
942 return 0;
944 if (!strcmp(var, "format.coverfromdescription")) {
945 cover_from_description_mode = parse_cover_from_description(value);
946 return 0;
949 return git_log_config(var, value, cb);
952 static const char *output_directory = NULL;
953 static int outdir_offset;
955 static int open_next_file(struct commit *commit, const char *subject,
956 struct rev_info *rev, int quiet)
958 struct strbuf filename = STRBUF_INIT;
960 if (output_directory) {
961 strbuf_addstr(&filename, output_directory);
962 strbuf_complete(&filename, '/');
965 if (rev->numbered_files)
966 strbuf_addf(&filename, "%d", rev->nr);
967 else if (commit)
968 fmt_output_commit(&filename, commit, rev);
969 else
970 fmt_output_subject(&filename, subject, rev);
972 if (!quiet)
973 printf("%s\n", filename.buf + outdir_offset);
975 if ((rev->diffopt.file = fopen(filename.buf, "w")) == NULL) {
976 error_errno(_("cannot open patch file %s"), filename.buf);
977 strbuf_release(&filename);
978 return -1;
981 strbuf_release(&filename);
982 return 0;
985 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
987 struct rev_info check_rev;
988 struct commit *commit, *c1, *c2;
989 struct object *o1, *o2;
990 unsigned flags1, flags2;
992 if (rev->pending.nr != 2)
993 die(_("need exactly one range"));
995 o1 = rev->pending.objects[0].item;
996 o2 = rev->pending.objects[1].item;
997 flags1 = o1->flags;
998 flags2 = o2->flags;
999 c1 = lookup_commit_reference(the_repository, &o1->oid);
1000 c2 = lookup_commit_reference(the_repository, &o2->oid);
1002 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
1003 die(_("not a range"));
1005 init_patch_ids(the_repository, ids);
1007 /* given a range a..b get all patch ids for b..a */
1008 repo_init_revisions(the_repository, &check_rev, rev->prefix);
1009 check_rev.max_parents = 1;
1010 o1->flags ^= UNINTERESTING;
1011 o2->flags ^= UNINTERESTING;
1012 add_pending_object(&check_rev, o1, "o1");
1013 add_pending_object(&check_rev, o2, "o2");
1014 if (prepare_revision_walk(&check_rev))
1015 die(_("revision walk setup failed"));
1017 while ((commit = get_revision(&check_rev)) != NULL) {
1018 add_commit_patch_id(commit, ids);
1021 /* reset for next revision walk */
1022 clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
1023 clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
1024 o1->flags = flags1;
1025 o2->flags = flags2;
1028 static void gen_message_id(struct rev_info *info, char *base)
1030 struct strbuf buf = STRBUF_INIT;
1031 strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
1032 (timestamp_t) time(NULL),
1033 git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
1034 info->message_id = strbuf_detach(&buf, NULL);
1037 static void print_signature(FILE *file)
1039 if (!signature || !*signature)
1040 return;
1042 fprintf(file, "-- \n%s", signature);
1043 if (signature[strlen(signature)-1] != '\n')
1044 putc('\n', file);
1045 putc('\n', file);
1048 static char *find_branch_name(struct rev_info *rev)
1050 int i, positive = -1;
1051 struct object_id branch_oid;
1052 const struct object_id *tip_oid;
1053 const char *ref, *v;
1054 char *full_ref, *branch = NULL;
1056 for (i = 0; i < rev->cmdline.nr; i++) {
1057 if (rev->cmdline.rev[i].flags & UNINTERESTING)
1058 continue;
1059 if (positive < 0)
1060 positive = i;
1061 else
1062 return NULL;
1064 if (positive < 0)
1065 return NULL;
1066 ref = rev->cmdline.rev[positive].name;
1067 tip_oid = &rev->cmdline.rev[positive].item->oid;
1068 if (dwim_ref(ref, strlen(ref), &branch_oid, &full_ref, 0) &&
1069 skip_prefix(full_ref, "refs/heads/", &v) &&
1070 oideq(tip_oid, &branch_oid))
1071 branch = xstrdup(v);
1072 free(full_ref);
1073 return branch;
1076 static void show_diffstat(struct rev_info *rev,
1077 struct commit *origin, struct commit *head)
1079 struct diff_options opts;
1081 memcpy(&opts, &rev->diffopt, sizeof(opts));
1082 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1083 diff_setup_done(&opts);
1085 diff_tree_oid(get_commit_tree_oid(origin),
1086 get_commit_tree_oid(head),
1087 "", &opts);
1088 diffcore_std(&opts);
1089 diff_flush(&opts);
1091 fprintf(rev->diffopt.file, "\n");
1094 static void prepare_cover_text(struct pretty_print_context *pp,
1095 const char *branch_name,
1096 struct strbuf *sb,
1097 const char *encoding,
1098 int need_8bit_cte)
1100 const char *subject = "*** SUBJECT HERE ***";
1101 const char *body = "*** BLURB HERE ***";
1102 struct strbuf description_sb = STRBUF_INIT;
1103 struct strbuf subject_sb = STRBUF_INIT;
1105 if (cover_from_description_mode == COVER_FROM_NONE)
1106 goto do_pp;
1108 if (branch_name && *branch_name)
1109 read_branch_desc(&description_sb, branch_name);
1110 if (!description_sb.len)
1111 goto do_pp;
1113 if (cover_from_description_mode == COVER_FROM_SUBJECT ||
1114 cover_from_description_mode == COVER_FROM_AUTO)
1115 body = format_subject(&subject_sb, description_sb.buf, " ");
1117 if (cover_from_description_mode == COVER_FROM_MESSAGE ||
1118 (cover_from_description_mode == COVER_FROM_AUTO &&
1119 subject_sb.len > COVER_FROM_AUTO_MAX_SUBJECT_LEN))
1120 body = description_sb.buf;
1121 else
1122 subject = subject_sb.buf;
1124 do_pp:
1125 pp_title_line(pp, &subject, sb, encoding, need_8bit_cte);
1126 pp_remainder(pp, &body, sb, 0);
1128 strbuf_release(&description_sb);
1129 strbuf_release(&subject_sb);
1132 static int get_notes_refs(struct string_list_item *item, void *arg)
1134 strvec_pushf(arg, "--notes=%s", item->string);
1135 return 0;
1138 static void get_notes_args(struct strvec *arg, struct rev_info *rev)
1140 if (!rev->show_notes) {
1141 strvec_push(arg, "--no-notes");
1142 } else if (rev->notes_opt.use_default_notes > 0 ||
1143 (rev->notes_opt.use_default_notes == -1 &&
1144 !rev->notes_opt.extra_notes_refs.nr)) {
1145 strvec_push(arg, "--notes");
1146 } else {
1147 for_each_string_list(&rev->notes_opt.extra_notes_refs, get_notes_refs, arg);
1151 static void make_cover_letter(struct rev_info *rev, int use_separate_file,
1152 struct commit *origin,
1153 int nr, struct commit **list,
1154 const char *branch_name,
1155 int quiet)
1157 const char *committer;
1158 struct shortlog log;
1159 struct strbuf sb = STRBUF_INIT;
1160 int i;
1161 const char *encoding = "UTF-8";
1162 int need_8bit_cte = 0;
1163 struct pretty_print_context pp = {0};
1164 struct commit *head = list[0];
1166 if (!cmit_fmt_is_mail(rev->commit_format))
1167 die(_("cover letter needs email format"));
1169 committer = git_committer_info(0);
1171 if (use_separate_file &&
1172 open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1173 die(_("failed to create cover-letter file"));
1175 log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1177 for (i = 0; !need_8bit_cte && i < nr; i++) {
1178 const char *buf = get_commit_buffer(list[i], NULL);
1179 if (has_non_ascii(buf))
1180 need_8bit_cte = 1;
1181 unuse_commit_buffer(list[i], buf);
1184 if (!branch_name)
1185 branch_name = find_branch_name(rev);
1187 pp.fmt = CMIT_FMT_EMAIL;
1188 pp.date_mode.type = DATE_RFC2822;
1189 pp.rev = rev;
1190 pp.print_email_subject = 1;
1191 pp_user_info(&pp, NULL, &sb, committer, encoding);
1192 prepare_cover_text(&pp, branch_name, &sb, encoding, need_8bit_cte);
1193 fprintf(rev->diffopt.file, "%s\n", sb.buf);
1195 strbuf_release(&sb);
1197 shortlog_init(&log);
1198 log.wrap_lines = 1;
1199 log.wrap = MAIL_DEFAULT_WRAP;
1200 log.in1 = 2;
1201 log.in2 = 4;
1202 log.file = rev->diffopt.file;
1203 log.groups = SHORTLOG_GROUP_AUTHOR;
1204 for (i = 0; i < nr; i++)
1205 shortlog_add_commit(&log, list[i]);
1207 shortlog_output(&log);
1209 /* We can only do diffstat with a unique reference point */
1210 if (origin)
1211 show_diffstat(rev, origin, head);
1213 if (rev->idiff_oid1) {
1214 fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1215 show_interdiff(rev->idiff_oid1, rev->idiff_oid2, 0,
1216 &rev->diffopt);
1219 if (rev->rdiff1) {
1221 * Pass minimum required diff-options to range-diff; others
1222 * can be added later if deemed desirable.
1224 struct diff_options opts;
1225 struct strvec other_arg = STRVEC_INIT;
1226 struct range_diff_options range_diff_opts = {
1227 .creation_factor = rev->creation_factor,
1228 .dual_color = 1,
1229 .diffopt = &opts,
1230 .other_arg = &other_arg
1233 diff_setup(&opts);
1234 opts.file = rev->diffopt.file;
1235 opts.use_color = rev->diffopt.use_color;
1236 diff_setup_done(&opts);
1237 fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1238 get_notes_args(&other_arg, rev);
1239 show_range_diff(rev->rdiff1, rev->rdiff2, &range_diff_opts);
1240 strvec_clear(&other_arg);
1244 static const char *clean_message_id(const char *msg_id)
1246 char ch;
1247 const char *a, *z, *m;
1249 m = msg_id;
1250 while ((ch = *m) && (isspace(ch) || (ch == '<')))
1251 m++;
1252 a = m;
1253 z = NULL;
1254 while ((ch = *m)) {
1255 if (!isspace(ch) && (ch != '>'))
1256 z = m;
1257 m++;
1259 if (!z)
1260 die(_("insane in-reply-to: %s"), msg_id);
1261 if (++z == m)
1262 return a;
1263 return xmemdupz(a, z - a);
1266 static const char *set_outdir(const char *prefix, const char *output_directory)
1268 if (output_directory && is_absolute_path(output_directory))
1269 return output_directory;
1271 if (!prefix || !*prefix) {
1272 if (output_directory)
1273 return output_directory;
1274 /* The user did not explicitly ask for "./" */
1275 outdir_offset = 2;
1276 return "./";
1279 outdir_offset = strlen(prefix);
1280 if (!output_directory)
1281 return prefix;
1283 return prefix_filename(prefix, output_directory);
1286 static const char * const builtin_format_patch_usage[] = {
1287 N_("git format-patch [<options>] [<since> | <revision-range>]"),
1288 NULL
1291 static int keep_subject = 0;
1293 static int keep_callback(const struct option *opt, const char *arg, int unset)
1295 BUG_ON_OPT_NEG(unset);
1296 BUG_ON_OPT_ARG(arg);
1297 ((struct rev_info *)opt->value)->total = -1;
1298 keep_subject = 1;
1299 return 0;
1302 static int subject_prefix = 0;
1304 static int subject_prefix_callback(const struct option *opt, const char *arg,
1305 int unset)
1307 BUG_ON_OPT_NEG(unset);
1308 subject_prefix = 1;
1309 ((struct rev_info *)opt->value)->subject_prefix = arg;
1310 return 0;
1313 static int rfc_callback(const struct option *opt, const char *arg, int unset)
1315 BUG_ON_OPT_NEG(unset);
1316 BUG_ON_OPT_ARG(arg);
1317 return subject_prefix_callback(opt, "RFC PATCH", unset);
1320 static int numbered_cmdline_opt = 0;
1322 static int numbered_callback(const struct option *opt, const char *arg,
1323 int unset)
1325 BUG_ON_OPT_ARG(arg);
1326 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1327 if (unset)
1328 auto_number = 0;
1329 return 0;
1332 static int no_numbered_callback(const struct option *opt, const char *arg,
1333 int unset)
1335 BUG_ON_OPT_NEG(unset);
1336 return numbered_callback(opt, arg, 1);
1339 static int output_directory_callback(const struct option *opt, const char *arg,
1340 int unset)
1342 const char **dir = (const char **)opt->value;
1343 BUG_ON_OPT_NEG(unset);
1344 if (*dir)
1345 die(_("two output directories?"));
1346 *dir = arg;
1347 return 0;
1350 static int thread_callback(const struct option *opt, const char *arg, int unset)
1352 enum thread_level *thread = (enum thread_level *)opt->value;
1353 if (unset)
1354 *thread = THREAD_UNSET;
1355 else if (!arg || !strcmp(arg, "shallow"))
1356 *thread = THREAD_SHALLOW;
1357 else if (!strcmp(arg, "deep"))
1358 *thread = THREAD_DEEP;
1360 * Please update _git_formatpatch() in git-completion.bash
1361 * when you add new options.
1363 else
1364 return 1;
1365 return 0;
1368 static int attach_callback(const struct option *opt, const char *arg, int unset)
1370 struct rev_info *rev = (struct rev_info *)opt->value;
1371 if (unset)
1372 rev->mime_boundary = NULL;
1373 else if (arg)
1374 rev->mime_boundary = arg;
1375 else
1376 rev->mime_boundary = git_version_string;
1377 rev->no_inline = unset ? 0 : 1;
1378 return 0;
1381 static int inline_callback(const struct option *opt, const char *arg, int unset)
1383 struct rev_info *rev = (struct rev_info *)opt->value;
1384 if (unset)
1385 rev->mime_boundary = NULL;
1386 else if (arg)
1387 rev->mime_boundary = arg;
1388 else
1389 rev->mime_boundary = git_version_string;
1390 rev->no_inline = 0;
1391 return 0;
1394 static int header_callback(const struct option *opt, const char *arg, int unset)
1396 if (unset) {
1397 string_list_clear(&extra_hdr, 0);
1398 string_list_clear(&extra_to, 0);
1399 string_list_clear(&extra_cc, 0);
1400 } else {
1401 add_header(arg);
1403 return 0;
1406 static int to_callback(const struct option *opt, const char *arg, int unset)
1408 if (unset)
1409 string_list_clear(&extra_to, 0);
1410 else
1411 string_list_append(&extra_to, arg);
1412 return 0;
1415 static int cc_callback(const struct option *opt, const char *arg, int unset)
1417 if (unset)
1418 string_list_clear(&extra_cc, 0);
1419 else
1420 string_list_append(&extra_cc, arg);
1421 return 0;
1424 static int from_callback(const struct option *opt, const char *arg, int unset)
1426 char **from = opt->value;
1428 free(*from);
1430 if (unset)
1431 *from = NULL;
1432 else if (arg)
1433 *from = xstrdup(arg);
1434 else
1435 *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1436 return 0;
1439 static int base_callback(const struct option *opt, const char *arg, int unset)
1441 const char **base_commit = opt->value;
1443 if (unset) {
1444 auto_base = AUTO_BASE_NEVER;
1445 *base_commit = NULL;
1446 } else if (!strcmp(arg, "auto")) {
1447 auto_base = AUTO_BASE_ALWAYS;
1448 *base_commit = NULL;
1449 } else {
1450 auto_base = AUTO_BASE_NEVER;
1451 *base_commit = arg;
1453 return 0;
1456 struct base_tree_info {
1457 struct object_id base_commit;
1458 int nr_patch_id, alloc_patch_id;
1459 struct object_id *patch_id;
1462 static struct commit *get_base_commit(const char *base_commit,
1463 struct commit **list,
1464 int total)
1466 struct commit *base = NULL;
1467 struct commit **rev;
1468 int i = 0, rev_nr = 0, auto_select, die_on_failure;
1470 switch (auto_base) {
1471 case AUTO_BASE_NEVER:
1472 if (base_commit) {
1473 auto_select = 0;
1474 die_on_failure = 1;
1475 } else {
1476 /* no base information is requested */
1477 return NULL;
1479 break;
1480 case AUTO_BASE_ALWAYS:
1481 case AUTO_BASE_WHEN_ABLE:
1482 if (base_commit) {
1483 BUG("requested automatic base selection but a commit was provided");
1484 } else {
1485 auto_select = 1;
1486 die_on_failure = auto_base == AUTO_BASE_ALWAYS;
1488 break;
1489 default:
1490 BUG("unexpected automatic base selection method");
1493 if (!auto_select) {
1494 base = lookup_commit_reference_by_name(base_commit);
1495 if (!base)
1496 die(_("unknown commit %s"), base_commit);
1497 } else {
1498 struct branch *curr_branch = branch_get(NULL);
1499 const char *upstream = branch_get_upstream(curr_branch, NULL);
1500 if (upstream) {
1501 struct commit_list *base_list;
1502 struct commit *commit;
1503 struct object_id oid;
1505 if (get_oid(upstream, &oid)) {
1506 if (die_on_failure)
1507 die(_("failed to resolve '%s' as a valid ref"), upstream);
1508 else
1509 return NULL;
1511 commit = lookup_commit_or_die(&oid, "upstream base");
1512 base_list = get_merge_bases_many(commit, total, list);
1513 /* There should be one and only one merge base. */
1514 if (!base_list || base_list->next) {
1515 if (die_on_failure) {
1516 die(_("could not find exact merge base"));
1517 } else {
1518 free_commit_list(base_list);
1519 return NULL;
1522 base = base_list->item;
1523 free_commit_list(base_list);
1524 } else {
1525 if (die_on_failure)
1526 die(_("failed to get upstream, if you want to record base commit automatically,\n"
1527 "please use git branch --set-upstream-to to track a remote branch.\n"
1528 "Or you could specify base commit by --base=<base-commit-id> manually"));
1529 else
1530 return NULL;
1534 ALLOC_ARRAY(rev, total);
1535 for (i = 0; i < total; i++)
1536 rev[i] = list[i];
1538 rev_nr = total;
1540 * Get merge base through pair-wise computations
1541 * and store it in rev[0].
1543 while (rev_nr > 1) {
1544 for (i = 0; i < rev_nr / 2; i++) {
1545 struct commit_list *merge_base;
1546 merge_base = get_merge_bases(rev[2 * i], rev[2 * i + 1]);
1547 if (!merge_base || merge_base->next) {
1548 if (die_on_failure) {
1549 die(_("failed to find exact merge base"));
1550 } else {
1551 free(rev);
1552 return NULL;
1556 rev[i] = merge_base->item;
1559 if (rev_nr % 2)
1560 rev[i] = rev[2 * i];
1561 rev_nr = DIV_ROUND_UP(rev_nr, 2);
1564 if (!in_merge_bases(base, rev[0])) {
1565 if (die_on_failure) {
1566 die(_("base commit should be the ancestor of revision list"));
1567 } else {
1568 free(rev);
1569 return NULL;
1573 for (i = 0; i < total; i++) {
1574 if (base == list[i]) {
1575 if (die_on_failure) {
1576 die(_("base commit shouldn't be in revision list"));
1577 } else {
1578 free(rev);
1579 return NULL;
1584 free(rev);
1585 return base;
1588 define_commit_slab(commit_base, int);
1590 static void prepare_bases(struct base_tree_info *bases,
1591 struct commit *base,
1592 struct commit **list,
1593 int total)
1595 struct commit *commit;
1596 struct rev_info revs;
1597 struct diff_options diffopt;
1598 struct commit_base commit_base;
1599 int i;
1601 if (!base)
1602 return;
1604 init_commit_base(&commit_base);
1605 repo_diff_setup(the_repository, &diffopt);
1606 diffopt.flags.recursive = 1;
1607 diff_setup_done(&diffopt);
1609 oidcpy(&bases->base_commit, &base->object.oid);
1611 repo_init_revisions(the_repository, &revs, NULL);
1612 revs.max_parents = 1;
1613 revs.topo_order = 1;
1614 for (i = 0; i < total; i++) {
1615 list[i]->object.flags &= ~UNINTERESTING;
1616 add_pending_object(&revs, &list[i]->object, "rev_list");
1617 *commit_base_at(&commit_base, list[i]) = 1;
1619 base->object.flags |= UNINTERESTING;
1620 add_pending_object(&revs, &base->object, "base");
1622 if (prepare_revision_walk(&revs))
1623 die(_("revision walk setup failed"));
1625 * Traverse the commits list, get prerequisite patch ids
1626 * and stuff them in bases structure.
1628 while ((commit = get_revision(&revs)) != NULL) {
1629 struct object_id oid;
1630 struct object_id *patch_id;
1631 if (*commit_base_at(&commit_base, commit))
1632 continue;
1633 if (commit_patch_id(commit, &diffopt, &oid, 0, 1))
1634 die(_("cannot get patch id"));
1635 ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1636 patch_id = bases->patch_id + bases->nr_patch_id;
1637 oidcpy(patch_id, &oid);
1638 bases->nr_patch_id++;
1640 clear_commit_base(&commit_base);
1643 static void print_bases(struct base_tree_info *bases, FILE *file)
1645 int i;
1647 /* Only do this once, either for the cover or for the first one */
1648 if (is_null_oid(&bases->base_commit))
1649 return;
1651 /* Show the base commit */
1652 fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1654 /* Show the prerequisite patches */
1655 for (i = bases->nr_patch_id - 1; i >= 0; i--)
1656 fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1658 free(bases->patch_id);
1659 bases->nr_patch_id = 0;
1660 bases->alloc_patch_id = 0;
1661 oidclr(&bases->base_commit);
1664 static const char *diff_title(struct strbuf *sb, int reroll_count,
1665 const char *generic, const char *rerolled)
1667 if (reroll_count <= 0)
1668 strbuf_addstr(sb, generic);
1669 else /* RFC may be v0, so allow -v1 to diff against v0 */
1670 strbuf_addf(sb, rerolled, reroll_count - 1);
1671 return sb->buf;
1674 static void infer_range_diff_ranges(struct strbuf *r1,
1675 struct strbuf *r2,
1676 const char *prev,
1677 struct commit *origin,
1678 struct commit *head)
1680 const char *head_oid = oid_to_hex(&head->object.oid);
1681 int prev_is_range = is_range_diff_range(prev);
1683 if (prev_is_range)
1684 strbuf_addstr(r1, prev);
1685 else
1686 strbuf_addf(r1, "%s..%s", head_oid, prev);
1688 if (origin)
1689 strbuf_addf(r2, "%s..%s", oid_to_hex(&origin->object.oid), head_oid);
1690 else if (prev_is_range)
1691 die(_("failed to infer range-diff origin of current series"));
1692 else {
1693 warning(_("using '%s' as range-diff origin of current series"), prev);
1694 strbuf_addf(r2, "%s..%s", prev, head_oid);
1698 int cmd_format_patch(int argc, const char **argv, const char *prefix)
1700 struct commit *commit;
1701 struct commit **list = NULL;
1702 struct rev_info rev;
1703 struct setup_revision_opt s_r_opt;
1704 int nr = 0, total, i;
1705 int use_stdout = 0;
1706 int start_number = -1;
1707 int just_numbers = 0;
1708 int ignore_if_in_upstream = 0;
1709 int cover_letter = -1;
1710 int boundary_count = 0;
1711 int no_binary_diff = 0;
1712 int zero_commit = 0;
1713 struct commit *origin = NULL;
1714 const char *in_reply_to = NULL;
1715 struct patch_ids ids;
1716 struct strbuf buf = STRBUF_INIT;
1717 int use_patch_format = 0;
1718 int quiet = 0;
1719 int reroll_count = -1;
1720 char *cover_from_description_arg = NULL;
1721 char *branch_name = NULL;
1722 char *base_commit = NULL;
1723 struct base_tree_info bases;
1724 struct commit *base;
1725 int show_progress = 0;
1726 struct progress *progress = NULL;
1727 struct oid_array idiff_prev = OID_ARRAY_INIT;
1728 struct strbuf idiff_title = STRBUF_INIT;
1729 const char *rdiff_prev = NULL;
1730 struct strbuf rdiff1 = STRBUF_INIT;
1731 struct strbuf rdiff2 = STRBUF_INIT;
1732 struct strbuf rdiff_title = STRBUF_INIT;
1733 int creation_factor = -1;
1735 const struct option builtin_format_patch_options[] = {
1736 OPT_CALLBACK_F('n', "numbered", &numbered, NULL,
1737 N_("use [PATCH n/m] even with a single patch"),
1738 PARSE_OPT_NOARG, numbered_callback),
1739 OPT_CALLBACK_F('N', "no-numbered", &numbered, NULL,
1740 N_("use [PATCH] even with multiple patches"),
1741 PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback),
1742 OPT_BOOL('s', "signoff", &do_signoff, N_("add a Signed-off-by trailer")),
1743 OPT_BOOL(0, "stdout", &use_stdout,
1744 N_("print patches to standard out")),
1745 OPT_BOOL(0, "cover-letter", &cover_letter,
1746 N_("generate a cover letter")),
1747 OPT_BOOL(0, "numbered-files", &just_numbers,
1748 N_("use simple number sequence for output file names")),
1749 OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
1750 N_("use <sfx> instead of '.patch'")),
1751 OPT_INTEGER(0, "start-number", &start_number,
1752 N_("start numbering patches at <n> instead of 1")),
1753 OPT_INTEGER('v', "reroll-count", &reroll_count,
1754 N_("mark the series as Nth re-roll")),
1755 OPT_INTEGER(0, "filename-max-length", &fmt_patch_name_max,
1756 N_("max length of output filename")),
1757 OPT_CALLBACK_F(0, "rfc", &rev, NULL,
1758 N_("use [RFC PATCH] instead of [PATCH]"),
1759 PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback),
1760 OPT_STRING(0, "cover-from-description", &cover_from_description_arg,
1761 N_("cover-from-description-mode"),
1762 N_("generate parts of a cover letter based on a branch's description")),
1763 OPT_CALLBACK_F(0, "subject-prefix", &rev, N_("prefix"),
1764 N_("use [<prefix>] instead of [PATCH]"),
1765 PARSE_OPT_NONEG, subject_prefix_callback),
1766 OPT_CALLBACK_F('o', "output-directory", &output_directory,
1767 N_("dir"), N_("store resulting files in <dir>"),
1768 PARSE_OPT_NONEG, output_directory_callback),
1769 OPT_CALLBACK_F('k', "keep-subject", &rev, NULL,
1770 N_("don't strip/add [PATCH]"),
1771 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback),
1772 OPT_BOOL(0, "no-binary", &no_binary_diff,
1773 N_("don't output binary diffs")),
1774 OPT_BOOL(0, "zero-commit", &zero_commit,
1775 N_("output all-zero hash in From header")),
1776 OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1777 N_("don't include a patch matching a commit upstream")),
1778 OPT_SET_INT_F('p', "no-stat", &use_patch_format,
1779 N_("show patch format instead of default (patch + stat)"),
1780 1, PARSE_OPT_NONEG),
1781 OPT_GROUP(N_("Messaging")),
1782 OPT_CALLBACK(0, "add-header", NULL, N_("header"),
1783 N_("add email header"), header_callback),
1784 OPT_CALLBACK(0, "to", NULL, N_("email"), N_("add To: header"), to_callback),
1785 OPT_CALLBACK(0, "cc", NULL, N_("email"), N_("add Cc: header"), cc_callback),
1786 OPT_CALLBACK_F(0, "from", &from, N_("ident"),
1787 N_("set From address to <ident> (or committer ident if absent)"),
1788 PARSE_OPT_OPTARG, from_callback),
1789 OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
1790 N_("make first mail a reply to <message-id>")),
1791 OPT_CALLBACK_F(0, "attach", &rev, N_("boundary"),
1792 N_("attach the patch"), PARSE_OPT_OPTARG,
1793 attach_callback),
1794 OPT_CALLBACK_F(0, "inline", &rev, N_("boundary"),
1795 N_("inline the patch"),
1796 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1797 inline_callback),
1798 OPT_CALLBACK_F(0, "thread", &thread, N_("style"),
1799 N_("enable message threading, styles: shallow, deep"),
1800 PARSE_OPT_OPTARG, thread_callback),
1801 OPT_STRING(0, "signature", &signature, N_("signature"),
1802 N_("add a signature")),
1803 OPT_CALLBACK_F(0, "base", &base_commit, N_("base-commit"),
1804 N_("add prerequisite tree info to the patch series"),
1805 0, base_callback),
1806 OPT_FILENAME(0, "signature-file", &signature_file,
1807 N_("add a signature from a file")),
1808 OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1809 OPT_BOOL(0, "progress", &show_progress,
1810 N_("show progress while generating patches")),
1811 OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
1812 N_("show changes against <rev> in cover letter or single patch"),
1813 parse_opt_object_name),
1814 OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
1815 N_("show changes against <refspec> in cover letter or single patch")),
1816 OPT_INTEGER(0, "creation-factor", &creation_factor,
1817 N_("percentage by which creation is weighted")),
1818 OPT_END()
1821 extra_hdr.strdup_strings = 1;
1822 extra_to.strdup_strings = 1;
1823 extra_cc.strdup_strings = 1;
1824 init_log_defaults();
1825 init_display_notes(&notes_opt);
1826 git_config(git_format_config, NULL);
1827 repo_init_revisions(the_repository, &rev, prefix);
1828 rev.show_notes = show_notes;
1829 memcpy(&rev.notes_opt, &notes_opt, sizeof(notes_opt));
1830 rev.commit_format = CMIT_FMT_EMAIL;
1831 rev.encode_email_headers = default_encode_email_headers;
1832 rev.expand_tabs_in_log_default = 0;
1833 rev.verbose_header = 1;
1834 rev.diff = 1;
1835 rev.max_parents = 1;
1836 rev.diffopt.flags.recursive = 1;
1837 rev.subject_prefix = fmt_patch_subject_prefix;
1838 memset(&s_r_opt, 0, sizeof(s_r_opt));
1839 s_r_opt.def = "HEAD";
1840 s_r_opt.revarg_opt = REVARG_COMMITTISH;
1842 if (default_attach) {
1843 rev.mime_boundary = default_attach;
1844 rev.no_inline = 1;
1848 * Parse the arguments before setup_revisions(), or something
1849 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1850 * possibly a valid SHA1.
1852 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1853 builtin_format_patch_usage,
1854 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1855 PARSE_OPT_KEEP_DASHDASH);
1857 /* Make sure "0000-$sub.patch" gives non-negative length for $sub */
1858 if (fmt_patch_name_max <= strlen("0000-") + strlen(fmt_patch_suffix))
1859 fmt_patch_name_max = strlen("0000-") + strlen(fmt_patch_suffix);
1861 if (cover_from_description_arg)
1862 cover_from_description_mode = parse_cover_from_description(cover_from_description_arg);
1864 if (0 < reroll_count) {
1865 struct strbuf sprefix = STRBUF_INIT;
1866 strbuf_addf(&sprefix, "%s v%d",
1867 rev.subject_prefix, reroll_count);
1868 rev.reroll_count = reroll_count;
1869 rev.subject_prefix = strbuf_detach(&sprefix, NULL);
1872 for (i = 0; i < extra_hdr.nr; i++) {
1873 strbuf_addstr(&buf, extra_hdr.items[i].string);
1874 strbuf_addch(&buf, '\n');
1877 if (extra_to.nr)
1878 strbuf_addstr(&buf, "To: ");
1879 for (i = 0; i < extra_to.nr; i++) {
1880 if (i)
1881 strbuf_addstr(&buf, " ");
1882 strbuf_addstr(&buf, extra_to.items[i].string);
1883 if (i + 1 < extra_to.nr)
1884 strbuf_addch(&buf, ',');
1885 strbuf_addch(&buf, '\n');
1888 if (extra_cc.nr)
1889 strbuf_addstr(&buf, "Cc: ");
1890 for (i = 0; i < extra_cc.nr; i++) {
1891 if (i)
1892 strbuf_addstr(&buf, " ");
1893 strbuf_addstr(&buf, extra_cc.items[i].string);
1894 if (i + 1 < extra_cc.nr)
1895 strbuf_addch(&buf, ',');
1896 strbuf_addch(&buf, '\n');
1899 rev.extra_headers = strbuf_detach(&buf, NULL);
1901 if (from) {
1902 if (split_ident_line(&rev.from_ident, from, strlen(from)))
1903 die(_("invalid ident line: %s"), from);
1906 if (start_number < 0)
1907 start_number = 1;
1910 * If numbered is set solely due to format.numbered in config,
1911 * and it would conflict with --keep-subject (-k) from the
1912 * command line, reset "numbered".
1914 if (numbered && keep_subject && !numbered_cmdline_opt)
1915 numbered = 0;
1917 if (numbered && keep_subject)
1918 die(_("-n and -k are mutually exclusive"));
1919 if (keep_subject && subject_prefix)
1920 die(_("--subject-prefix/--rfc and -k are mutually exclusive"));
1921 rev.preserve_subject = keep_subject;
1923 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1924 if (argc > 1)
1925 die(_("unrecognized argument: %s"), argv[1]);
1927 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1928 die(_("--name-only does not make sense"));
1929 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1930 die(_("--name-status does not make sense"));
1931 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1932 die(_("--check does not make sense"));
1934 if (!use_patch_format &&
1935 (!rev.diffopt.output_format ||
1936 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1937 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1938 if (!rev.diffopt.stat_width)
1939 rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
1941 /* Always generate a patch */
1942 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1944 rev.zero_commit = zero_commit;
1945 rev.patch_name_max = fmt_patch_name_max;
1947 if (!rev.diffopt.flags.text && !no_binary_diff)
1948 rev.diffopt.flags.binary = 1;
1950 if (rev.show_notes)
1951 load_display_notes(&rev.notes_opt);
1953 if (use_stdout + rev.diffopt.close_file + !!output_directory > 1)
1954 die(_("--stdout, --output, and --output-directory are mutually exclusive"));
1956 if (use_stdout) {
1957 setup_pager();
1958 } else if (rev.diffopt.close_file) {
1960 * The diff code parsed --output; it has already opened the
1961 * file, but but we must instruct it not to close after each
1962 * diff.
1964 rev.diffopt.close_file = 0;
1965 } else {
1966 int saved;
1968 if (!output_directory)
1969 output_directory = config_output_directory;
1970 output_directory = set_outdir(prefix, output_directory);
1972 if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
1973 rev.diffopt.use_color = GIT_COLOR_NEVER;
1975 * We consider <outdir> as 'outside of gitdir', therefore avoid
1976 * applying adjust_shared_perm in s-c-l-d.
1978 saved = get_shared_repository();
1979 set_shared_repository(0);
1980 switch (safe_create_leading_directories_const(output_directory)) {
1981 case SCLD_OK:
1982 case SCLD_EXISTS:
1983 break;
1984 default:
1985 die(_("could not create leading directories "
1986 "of '%s'"), output_directory);
1988 set_shared_repository(saved);
1989 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1990 die_errno(_("could not create directory '%s'"),
1991 output_directory);
1994 if (rev.pending.nr == 1) {
1995 int check_head = 0;
1997 if (rev.max_count < 0 && !rev.show_root_diff) {
1999 * This is traditional behaviour of "git format-patch
2000 * origin" that prepares what the origin side still
2001 * does not have.
2003 rev.pending.objects[0].item->flags |= UNINTERESTING;
2004 add_head_to_pending(&rev);
2005 check_head = 1;
2008 * Otherwise, it is "format-patch -22 HEAD", and/or
2009 * "format-patch --root HEAD". The user wants
2010 * get_revision() to do the usual traversal.
2013 if (!strcmp(rev.pending.objects[0].name, "HEAD"))
2014 check_head = 1;
2016 if (check_head) {
2017 const char *ref, *v;
2018 ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2019 NULL, NULL);
2020 if (ref && skip_prefix(ref, "refs/heads/", &v))
2021 branch_name = xstrdup(v);
2022 else
2023 branch_name = xstrdup(""); /* no branch */
2028 * We cannot move this anywhere earlier because we do want to
2029 * know if --root was given explicitly from the command line.
2031 rev.show_root_diff = 1;
2033 if (ignore_if_in_upstream) {
2034 /* Don't say anything if head and upstream are the same. */
2035 if (rev.pending.nr == 2) {
2036 struct object_array_entry *o = rev.pending.objects;
2037 if (oideq(&o[0].item->oid, &o[1].item->oid))
2038 goto done;
2040 get_patch_ids(&rev, &ids);
2043 if (prepare_revision_walk(&rev))
2044 die(_("revision walk setup failed"));
2045 rev.boundary = 1;
2046 while ((commit = get_revision(&rev)) != NULL) {
2047 if (commit->object.flags & BOUNDARY) {
2048 boundary_count++;
2049 origin = (boundary_count == 1) ? commit : NULL;
2050 continue;
2053 if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
2054 continue;
2056 nr++;
2057 REALLOC_ARRAY(list, nr);
2058 list[nr - 1] = commit;
2060 if (nr == 0)
2061 /* nothing to do */
2062 goto done;
2063 total = nr;
2064 if (cover_letter == -1) {
2065 if (config_cover_letter == COVER_AUTO)
2066 cover_letter = (total > 1);
2067 else
2068 cover_letter = (config_cover_letter == COVER_ON);
2070 if (!keep_subject && auto_number && (total > 1 || cover_letter))
2071 numbered = 1;
2072 if (numbered)
2073 rev.total = total + start_number - 1;
2075 if (idiff_prev.nr) {
2076 if (!cover_letter && total != 1)
2077 die(_("--interdiff requires --cover-letter or single patch"));
2078 rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
2079 rev.idiff_oid2 = get_commit_tree_oid(list[0]);
2080 rev.idiff_title = diff_title(&idiff_title, reroll_count,
2081 _("Interdiff:"),
2082 _("Interdiff against v%d:"));
2085 if (creation_factor < 0)
2086 creation_factor = RANGE_DIFF_CREATION_FACTOR_DEFAULT;
2087 else if (!rdiff_prev)
2088 die(_("--creation-factor requires --range-diff"));
2090 if (rdiff_prev) {
2091 if (!cover_letter && total != 1)
2092 die(_("--range-diff requires --cover-letter or single patch"));
2094 infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
2095 origin, list[0]);
2096 rev.rdiff1 = rdiff1.buf;
2097 rev.rdiff2 = rdiff2.buf;
2098 rev.creation_factor = creation_factor;
2099 rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
2100 _("Range-diff:"),
2101 _("Range-diff against v%d:"));
2104 if (!signature) {
2105 ; /* --no-signature inhibits all signatures */
2106 } else if (signature && signature != git_version_string) {
2107 ; /* non-default signature already set */
2108 } else if (signature_file) {
2109 struct strbuf buf = STRBUF_INIT;
2111 if (strbuf_read_file(&buf, signature_file, 128) < 0)
2112 die_errno(_("unable to read signature file '%s'"), signature_file);
2113 signature = strbuf_detach(&buf, NULL);
2116 memset(&bases, 0, sizeof(bases));
2117 base = get_base_commit(base_commit, list, nr);
2118 if (base) {
2119 reset_revision_walk();
2120 clear_object_flags(UNINTERESTING);
2121 prepare_bases(&bases, base, list, nr);
2124 if (in_reply_to || thread || cover_letter)
2125 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
2126 if (in_reply_to) {
2127 const char *msgid = clean_message_id(in_reply_to);
2128 string_list_append(rev.ref_message_ids, msgid);
2130 rev.numbered_files = just_numbers;
2131 rev.patch_suffix = fmt_patch_suffix;
2132 if (cover_letter) {
2133 if (thread)
2134 gen_message_id(&rev, "cover");
2135 make_cover_letter(&rev, !!output_directory,
2136 origin, nr, list, branch_name, quiet);
2137 print_bases(&bases, rev.diffopt.file);
2138 print_signature(rev.diffopt.file);
2139 total++;
2140 start_number--;
2141 /* interdiff/range-diff in cover-letter; omit from patches */
2142 rev.idiff_oid1 = NULL;
2143 rev.rdiff1 = NULL;
2145 rev.add_signoff = do_signoff;
2147 if (show_progress)
2148 progress = start_delayed_progress(_("Generating patches"), total);
2149 while (0 <= --nr) {
2150 int shown;
2151 display_progress(progress, total - nr);
2152 commit = list[nr];
2153 rev.nr = total - nr + (start_number - 1);
2154 /* Make the second and subsequent mails replies to the first */
2155 if (thread) {
2156 /* Have we already had a message ID? */
2157 if (rev.message_id) {
2159 * For deep threading: make every mail
2160 * a reply to the previous one, no
2161 * matter what other options are set.
2163 * For shallow threading:
2165 * Without --cover-letter and
2166 * --in-reply-to, make every mail a
2167 * reply to the one before.
2169 * With --in-reply-to but no
2170 * --cover-letter, make every mail a
2171 * reply to the <reply-to>.
2173 * With --cover-letter, make every
2174 * mail but the cover letter a reply
2175 * to the cover letter. The cover
2176 * letter is a reply to the
2177 * --in-reply-to, if specified.
2179 if (thread == THREAD_SHALLOW
2180 && rev.ref_message_ids->nr > 0
2181 && (!cover_letter || rev.nr > 1))
2182 free(rev.message_id);
2183 else
2184 string_list_append(rev.ref_message_ids,
2185 rev.message_id);
2187 gen_message_id(&rev, oid_to_hex(&commit->object.oid));
2190 if (output_directory &&
2191 open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
2192 die(_("failed to create output files"));
2193 shown = log_tree_commit(&rev, commit);
2194 free_commit_buffer(the_repository->parsed_objects,
2195 commit);
2197 /* We put one extra blank line between formatted
2198 * patches and this flag is used by log-tree code
2199 * to see if it needs to emit a LF before showing
2200 * the log; when using one file per patch, we do
2201 * not want the extra blank line.
2203 if (output_directory)
2204 rev.shown_one = 0;
2205 if (shown) {
2206 print_bases(&bases, rev.diffopt.file);
2207 if (rev.mime_boundary)
2208 fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
2209 mime_boundary_leader,
2210 rev.mime_boundary);
2211 else
2212 print_signature(rev.diffopt.file);
2214 if (output_directory)
2215 fclose(rev.diffopt.file);
2217 stop_progress(&progress);
2218 free(list);
2219 free(branch_name);
2220 string_list_clear(&extra_to, 0);
2221 string_list_clear(&extra_cc, 0);
2222 string_list_clear(&extra_hdr, 0);
2223 if (ignore_if_in_upstream)
2224 free_patch_ids(&ids);
2226 done:
2227 oid_array_clear(&idiff_prev);
2228 strbuf_release(&idiff_title);
2229 strbuf_release(&rdiff1);
2230 strbuf_release(&rdiff2);
2231 strbuf_release(&rdiff_title);
2232 return 0;
2235 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
2237 struct object_id oid;
2238 if (get_oid(arg, &oid) == 0) {
2239 struct commit *commit = lookup_commit_reference(the_repository,
2240 &oid);
2241 if (commit) {
2242 commit->object.flags |= flags;
2243 add_pending_object(revs, &commit->object, arg);
2244 return 0;
2247 return -1;
2250 static const char * const cherry_usage[] = {
2251 N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
2252 NULL
2255 static void print_commit(char sign, struct commit *commit, int verbose,
2256 int abbrev, FILE *file)
2258 if (!verbose) {
2259 fprintf(file, "%c %s\n", sign,
2260 find_unique_abbrev(&commit->object.oid, abbrev));
2261 } else {
2262 struct strbuf buf = STRBUF_INIT;
2263 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2264 fprintf(file, "%c %s %s\n", sign,
2265 find_unique_abbrev(&commit->object.oid, abbrev),
2266 buf.buf);
2267 strbuf_release(&buf);
2271 int cmd_cherry(int argc, const char **argv, const char *prefix)
2273 struct rev_info revs;
2274 struct patch_ids ids;
2275 struct commit *commit;
2276 struct commit_list *list = NULL;
2277 struct branch *current_branch;
2278 const char *upstream;
2279 const char *head = "HEAD";
2280 const char *limit = NULL;
2281 int verbose = 0, abbrev = 0;
2283 struct option options[] = {
2284 OPT__ABBREV(&abbrev),
2285 OPT__VERBOSE(&verbose, N_("be verbose")),
2286 OPT_END()
2289 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
2291 switch (argc) {
2292 case 3:
2293 limit = argv[2];
2294 /* FALLTHROUGH */
2295 case 2:
2296 head = argv[1];
2297 /* FALLTHROUGH */
2298 case 1:
2299 upstream = argv[0];
2300 break;
2301 default:
2302 current_branch = branch_get(NULL);
2303 upstream = branch_get_upstream(current_branch, NULL);
2304 if (!upstream) {
2305 fprintf(stderr, _("Could not find a tracked"
2306 " remote branch, please"
2307 " specify <upstream> manually.\n"));
2308 usage_with_options(cherry_usage, options);
2312 repo_init_revisions(the_repository, &revs, prefix);
2313 revs.max_parents = 1;
2315 if (add_pending_commit(head, &revs, 0))
2316 die(_("unknown commit %s"), head);
2317 if (add_pending_commit(upstream, &revs, UNINTERESTING))
2318 die(_("unknown commit %s"), upstream);
2320 /* Don't say anything if head and upstream are the same. */
2321 if (revs.pending.nr == 2) {
2322 struct object_array_entry *o = revs.pending.objects;
2323 if (oideq(&o[0].item->oid, &o[1].item->oid))
2324 return 0;
2327 get_patch_ids(&revs, &ids);
2329 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2330 die(_("unknown commit %s"), limit);
2332 /* reverse the list of commits */
2333 if (prepare_revision_walk(&revs))
2334 die(_("revision walk setup failed"));
2335 while ((commit = get_revision(&revs)) != NULL) {
2336 commit_list_insert(commit, &list);
2339 while (list) {
2340 char sign = '+';
2342 commit = list->item;
2343 if (has_commit_patch_id(commit, &ids))
2344 sign = '-';
2345 print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2346 list = list->next;
2349 free_patch_ids(&ids);
2350 return 0;