Sync with Git 2.47.1
[git/gitster.git] / builtin / log.c
blob368f6580a6eb8843592d3fc10d87bf85df03fb9e
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_REPOSITORY_VARIABLE
8 #include "builtin.h"
9 #include "abspath.h"
10 #include "config.h"
11 #include "environment.h"
12 #include "gettext.h"
13 #include "hex.h"
14 #include "refs.h"
15 #include "object-file.h"
16 #include "object-name.h"
17 #include "object-store-ll.h"
18 #include "pager.h"
19 #include "color.h"
20 #include "commit.h"
21 #include "diff.h"
22 #include "diff-merges.h"
23 #include "revision.h"
24 #include "log-tree.h"
25 #include "builtin.h"
26 #include "oid-array.h"
27 #include "tag.h"
28 #include "reflog-walk.h"
29 #include "patch-ids.h"
30 #include "shortlog.h"
31 #include "remote.h"
32 #include "string-list.h"
33 #include "parse-options.h"
34 #include "line-log.h"
35 #include "branch.h"
36 #include "streaming.h"
37 #include "version.h"
38 #include "mailmap.h"
39 #include "progress.h"
40 #include "commit-slab.h"
42 #include "commit-reach.h"
43 #include "range-diff.h"
44 #include "tmp-objdir.h"
45 #include "tree.h"
46 #include "write-or-die.h"
48 #define MAIL_DEFAULT_WRAP 72
49 #define COVER_FROM_AUTO_MAX_SUBJECT_LEN 100
50 #define FORMAT_PATCH_NAME_MAX_DEFAULT 64
52 static unsigned int force_in_body_from;
53 static int stdout_mboxrd;
54 static int format_no_prefix;
56 static const char * const builtin_log_usage[] = {
57 N_("git log [<options>] [<revision-range>] [[--] <path>...]"),
58 N_("git show [<options>] <object>..."),
59 NULL
62 struct line_opt_callback_data {
63 struct rev_info *rev;
64 const char *prefix;
65 struct string_list args;
68 static int session_is_interactive(void)
70 return isatty(1) || pager_in_use();
73 static int auto_decoration_style(void)
75 return session_is_interactive() ? DECORATE_SHORT_REFS : 0;
78 static int parse_decoration_style(const char *value)
80 switch (git_parse_maybe_bool(value)) {
81 case 1:
82 return DECORATE_SHORT_REFS;
83 case 0:
84 return 0;
85 default:
86 break;
88 if (!strcmp(value, "full"))
89 return DECORATE_FULL_REFS;
90 else if (!strcmp(value, "short"))
91 return DECORATE_SHORT_REFS;
92 else if (!strcmp(value, "auto"))
93 return auto_decoration_style();
95 * Please update _git_log() in git-completion.bash when you
96 * add new decoration styles.
98 return -1;
101 struct log_config {
102 int default_abbrev_commit;
103 int default_show_root;
104 int default_follow;
105 int default_show_signature;
106 int default_encode_email_headers;
107 int decoration_style;
108 int decoration_given;
109 int use_mailmap_config;
110 char *fmt_patch_subject_prefix;
111 int fmt_patch_name_max;
112 char *fmt_pretty;
113 char *default_date_mode;
116 static void log_config_init(struct log_config *cfg)
118 memset(cfg, 0, sizeof(*cfg));
119 cfg->default_show_root = 1;
120 cfg->default_encode_email_headers = 1;
121 cfg->use_mailmap_config = 1;
122 cfg->fmt_patch_subject_prefix = xstrdup("PATCH");
123 cfg->fmt_patch_name_max = FORMAT_PATCH_NAME_MAX_DEFAULT;
124 cfg->decoration_style = auto_decoration_style();
127 static void log_config_release(struct log_config *cfg)
129 free(cfg->default_date_mode);
130 free(cfg->fmt_pretty);
131 free(cfg->fmt_patch_subject_prefix);
134 static int use_default_decoration_filter = 1;
135 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
136 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
137 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
139 static int clear_decorations_callback(const struct option *opt UNUSED,
140 const char *arg, int unset)
142 BUG_ON_OPT_NEG(unset);
143 BUG_ON_OPT_ARG(arg);
144 string_list_clear(&decorate_refs_include, 0);
145 string_list_clear(&decorate_refs_exclude, 0);
146 use_default_decoration_filter = 0;
147 return 0;
150 static int decorate_callback(const struct option *opt, const char *arg,
151 int unset)
153 struct log_config *cfg = opt->value;
155 if (unset)
156 cfg->decoration_style = 0;
157 else if (arg)
158 cfg->decoration_style = parse_decoration_style(arg);
159 else
160 cfg->decoration_style = DECORATE_SHORT_REFS;
162 if (cfg->decoration_style < 0)
163 die(_("invalid --decorate option: %s"), arg);
165 cfg->decoration_given = 1;
167 return 0;
170 static int log_line_range_callback(const struct option *option, const char *arg, int unset)
172 struct line_opt_callback_data *data = option->value;
174 BUG_ON_OPT_NEG(unset);
176 if (!arg)
177 return -1;
179 data->rev->line_level_traverse = 1;
180 string_list_append(&data->args, arg);
182 return 0;
185 static void cmd_log_init_defaults(struct rev_info *rev,
186 struct log_config *cfg)
188 if (cfg->fmt_pretty)
189 get_commit_format(cfg->fmt_pretty, rev);
190 if (cfg->default_follow)
191 rev->diffopt.flags.default_follow_renames = 1;
192 rev->verbose_header = 1;
193 init_diffstat_widths(&rev->diffopt);
194 rev->diffopt.flags.recursive = 1;
195 rev->diffopt.flags.allow_textconv = 1;
196 rev->abbrev_commit = cfg->default_abbrev_commit;
197 rev->show_root_diff = cfg->default_show_root;
198 rev->subject_prefix = cfg->fmt_patch_subject_prefix;
199 rev->patch_name_max = cfg->fmt_patch_name_max;
200 rev->show_signature = cfg->default_show_signature;
201 rev->encode_email_headers = cfg->default_encode_email_headers;
203 if (cfg->default_date_mode)
204 parse_date_format(cfg->default_date_mode, &rev->date_mode);
207 static void set_default_decoration_filter(struct decoration_filter *decoration_filter)
209 int i;
210 char *value = NULL;
211 struct string_list *include = decoration_filter->include_ref_pattern;
212 const struct string_list *config_exclude;
214 if (!git_config_get_string_multi("log.excludeDecoration",
215 &config_exclude)) {
216 struct string_list_item *item;
217 for_each_string_list_item(item, config_exclude)
218 string_list_append(decoration_filter->exclude_ref_config_pattern,
219 item->string);
223 * By default, decorate_all is disabled. Enable it if
224 * log.initialDecorationSet=all. Don't ever disable it by config,
225 * since the command-line takes precedent.
227 if (use_default_decoration_filter &&
228 !git_config_get_string("log.initialdecorationset", &value) &&
229 !strcmp("all", value))
230 use_default_decoration_filter = 0;
231 free(value);
233 if (!use_default_decoration_filter ||
234 decoration_filter->exclude_ref_pattern->nr ||
235 decoration_filter->include_ref_pattern->nr ||
236 decoration_filter->exclude_ref_config_pattern->nr)
237 return;
240 * No command-line or config options were given, so
241 * populate with sensible defaults.
243 for (i = 0; i < ARRAY_SIZE(ref_namespace); i++) {
244 if (!ref_namespace[i].decoration)
245 continue;
247 string_list_append(include, ref_namespace[i].ref);
251 static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
252 struct rev_info *rev, struct setup_revision_opt *opt,
253 struct log_config *cfg)
255 struct userformat_want w;
256 int quiet = 0, source = 0, mailmap;
257 static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
258 struct decoration_filter decoration_filter = {
259 .exclude_ref_pattern = &decorate_refs_exclude,
260 .include_ref_pattern = &decorate_refs_include,
261 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
263 static struct revision_sources revision_sources;
265 const struct option builtin_log_options[] = {
266 OPT__QUIET(&quiet, N_("suppress diff output")),
267 OPT_BOOL(0, "source", &source, N_("show source")),
268 OPT_BOOL(0, "use-mailmap", &mailmap, N_("use mail map file")),
269 OPT_ALIAS(0, "mailmap", "use-mailmap"),
270 OPT_CALLBACK_F(0, "clear-decorations", NULL, NULL,
271 N_("clear all previously-defined decoration filters"),
272 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
273 clear_decorations_callback),
274 OPT_STRING_LIST(0, "decorate-refs", &decorate_refs_include,
275 N_("pattern"), N_("only decorate refs that match <pattern>")),
276 OPT_STRING_LIST(0, "decorate-refs-exclude", &decorate_refs_exclude,
277 N_("pattern"), N_("do not decorate refs that match <pattern>")),
278 OPT_CALLBACK_F(0, "decorate", cfg, NULL, N_("decorate options"),
279 PARSE_OPT_OPTARG, decorate_callback),
280 OPT_CALLBACK('L', NULL, &line_cb, "range:file",
281 N_("trace the evolution of line range <start>,<end> or function :<funcname> in <file>"),
282 log_line_range_callback),
283 OPT_END()
286 line_cb.rev = rev;
287 line_cb.prefix = prefix;
289 mailmap = cfg->use_mailmap_config;
290 argc = parse_options(argc, argv, prefix,
291 builtin_log_options, builtin_log_usage,
292 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
293 PARSE_OPT_KEEP_DASHDASH);
295 if (quiet)
296 rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
297 argc = setup_revisions(argc, argv, rev, opt);
299 /* Any arguments at this point are not recognized */
300 if (argc > 1)
301 die(_("unrecognized argument: %s"), argv[1]);
303 if (rev->line_level_traverse && rev->prune_data.nr)
304 die(_("-L<range>:<file> cannot be used with pathspec"));
306 memset(&w, 0, sizeof(w));
307 userformat_find_requirements(NULL, &w);
309 if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
310 rev->show_notes = 1;
311 if (rev->show_notes)
312 load_display_notes(&rev->notes_opt);
314 if ((rev->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
315 rev->diffopt.filter || rev->diffopt.flags.follow_renames)
316 rev->always_show_header = 0;
318 if (source || w.source) {
319 init_revision_sources(&revision_sources);
320 rev->sources = &revision_sources;
323 if (mailmap) {
324 rev->mailmap = xmalloc(sizeof(struct string_list));
325 string_list_init_nodup(rev->mailmap);
326 read_mailmap(rev->mailmap);
329 if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
331 * "log --pretty=raw" is special; ignore UI oriented
332 * configuration variables such as decoration.
334 if (!cfg->decoration_given)
335 cfg->decoration_style = 0;
336 if (!rev->abbrev_commit_given)
337 rev->abbrev_commit = 0;
340 if (rev->commit_format == CMIT_FMT_USERFORMAT) {
341 if (!w.decorate) {
343 * Disable decoration loading if the format will not
344 * show them anyway.
346 cfg->decoration_style = 0;
347 } else if (!cfg->decoration_style) {
349 * If we are going to show them, make sure we do load
350 * them here, but taking care not to override a
351 * specific style set by config or --decorate.
353 cfg->decoration_style = DECORATE_SHORT_REFS;
357 if (cfg->decoration_style || rev->simplify_by_decoration) {
358 set_default_decoration_filter(&decoration_filter);
360 if (cfg->decoration_style)
361 rev->show_decorations = 1;
363 load_ref_decorations(&decoration_filter, cfg->decoration_style);
366 if (rev->line_level_traverse)
367 line_log_init(rev, line_cb.prefix, &line_cb.args);
369 setup_pager();
372 static void cmd_log_init(int argc, const char **argv, const char *prefix,
373 struct rev_info *rev, struct setup_revision_opt *opt,
374 struct log_config *cfg)
376 cmd_log_init_defaults(rev, cfg);
377 cmd_log_init_finish(argc, argv, prefix, rev, opt, cfg);
381 * This gives a rough estimate for how many commits we
382 * will print out in the list.
384 static int estimate_commit_count(struct commit_list *list)
386 int n = 0;
388 while (list) {
389 struct commit *commit = list->item;
390 unsigned int flags = commit->object.flags;
391 list = list->next;
392 if (!(flags & (TREESAME | UNINTERESTING)))
393 n++;
395 return n;
398 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
400 if (rev->shown_one) {
401 rev->shown_one = 0;
402 if (rev->commit_format != CMIT_FMT_ONELINE)
403 putchar(rev->diffopt.line_termination);
405 fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
408 static struct itimerval early_output_timer;
410 static void log_show_early(struct rev_info *revs, struct commit_list *list)
412 int i = revs->early_output;
413 int show_header = 1;
414 int no_free = revs->diffopt.no_free;
416 revs->diffopt.no_free = 0;
417 sort_in_topological_order(&list, revs->sort_order);
418 while (list && i) {
419 struct commit *commit = list->item;
420 switch (simplify_commit(revs, commit)) {
421 case commit_show:
422 if (show_header) {
423 int n = estimate_commit_count(list);
424 show_early_header(revs, "incomplete", n);
425 show_header = 0;
427 log_tree_commit(revs, commit);
428 i--;
429 break;
430 case commit_ignore:
431 break;
432 case commit_error:
433 revs->diffopt.no_free = no_free;
434 diff_free(&revs->diffopt);
435 return;
437 list = list->next;
440 /* Did we already get enough commits for the early output? */
441 if (!i) {
442 revs->diffopt.no_free = 0;
443 diff_free(&revs->diffopt);
444 return;
448 * ..if no, then repeat it twice a second until we
449 * do.
451 * NOTE! We don't use "it_interval", because if the
452 * reader isn't listening, we want our output to be
453 * throttled by the writing, and not have the timer
454 * trigger every second even if we're blocked on a
455 * reader!
457 early_output_timer.it_value.tv_sec = 0;
458 early_output_timer.it_value.tv_usec = 500000;
459 setitimer(ITIMER_REAL, &early_output_timer, NULL);
462 static void early_output(int signal UNUSED)
464 show_early_output = log_show_early;
467 static void setup_early_output(void)
469 struct sigaction sa;
472 * Set up the signal handler, minimally intrusively:
473 * we only set a single volatile integer word (not
474 * using sigatomic_t - trying to avoid unnecessary
475 * system dependencies and headers), and using
476 * SA_RESTART.
478 memset(&sa, 0, sizeof(sa));
479 sa.sa_handler = early_output;
480 sigemptyset(&sa.sa_mask);
481 sa.sa_flags = SA_RESTART;
482 sigaction(SIGALRM, &sa, NULL);
485 * If we can get the whole output in less than a
486 * tenth of a second, don't even bother doing the
487 * early-output thing..
489 * This is a one-time-only trigger.
491 early_output_timer.it_value.tv_sec = 0;
492 early_output_timer.it_value.tv_usec = 100000;
493 setitimer(ITIMER_REAL, &early_output_timer, NULL);
496 static void finish_early_output(struct rev_info *rev)
498 int n = estimate_commit_count(rev->commits);
499 signal(SIGALRM, SIG_IGN);
500 show_early_header(rev, "done", n);
503 static int cmd_log_walk_no_free(struct rev_info *rev)
505 struct commit *commit;
506 int saved_nrl = 0;
507 int saved_dcctc = 0;
508 int result;
510 if (rev->early_output)
511 setup_early_output();
513 if (prepare_revision_walk(rev))
514 die(_("revision walk setup failed"));
516 if (rev->early_output)
517 finish_early_output(rev);
520 * For --check and --exit-code, the exit code is based on CHECK_FAILED
521 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
522 * retain that state information if replacing rev->diffopt in this loop
524 while ((commit = get_revision(rev)) != NULL) {
525 if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
527 * We decremented max_count in get_revision,
528 * but we didn't actually show the commit.
530 rev->max_count++;
531 if (!rev->reflog_info) {
533 * We may show a given commit multiple times when
534 * walking the reflogs.
536 free_commit_buffer(the_repository->parsed_objects,
537 commit);
538 free_commit_list(commit->parents);
539 commit->parents = NULL;
541 if (saved_nrl < rev->diffopt.needed_rename_limit)
542 saved_nrl = rev->diffopt.needed_rename_limit;
543 if (rev->diffopt.degraded_cc_to_c)
544 saved_dcctc = 1;
546 rev->diffopt.degraded_cc_to_c = saved_dcctc;
547 rev->diffopt.needed_rename_limit = saved_nrl;
549 result = diff_result_code(rev);
550 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
551 rev->diffopt.flags.check_failed) {
552 result = 02;
554 return result;
557 static int cmd_log_walk(struct rev_info *rev)
559 int retval;
561 rev->diffopt.no_free = 1;
562 retval = cmd_log_walk_no_free(rev);
563 rev->diffopt.no_free = 0;
564 diff_free(&rev->diffopt);
565 return retval;
568 static int git_log_config(const char *var, const char *value,
569 const struct config_context *ctx, void *cb)
571 struct log_config *cfg = cb;
572 const char *slot_name;
574 if (!strcmp(var, "format.pretty")) {
575 FREE_AND_NULL(cfg->fmt_pretty);
576 return git_config_string(&cfg->fmt_pretty, var, value);
578 if (!strcmp(var, "format.subjectprefix")) {
579 FREE_AND_NULL(cfg->fmt_patch_subject_prefix);
580 return git_config_string(&cfg->fmt_patch_subject_prefix, var, value);
582 if (!strcmp(var, "format.filenamemaxlength")) {
583 cfg->fmt_patch_name_max = git_config_int(var, value, ctx->kvi);
584 return 0;
586 if (!strcmp(var, "format.encodeemailheaders")) {
587 cfg->default_encode_email_headers = git_config_bool(var, value);
588 return 0;
590 if (!strcmp(var, "log.abbrevcommit")) {
591 cfg->default_abbrev_commit = git_config_bool(var, value);
592 return 0;
594 if (!strcmp(var, "log.date")) {
595 FREE_AND_NULL(cfg->default_date_mode);
596 return git_config_string(&cfg->default_date_mode, var, value);
598 if (!strcmp(var, "log.decorate")) {
599 cfg->decoration_style = parse_decoration_style(value);
600 if (cfg->decoration_style < 0)
601 cfg->decoration_style = 0; /* maybe warn? */
602 return 0;
604 if (!strcmp(var, "log.diffmerges")) {
605 if (!value)
606 return config_error_nonbool(var);
607 return diff_merges_config(value);
609 if (!strcmp(var, "log.showroot")) {
610 cfg->default_show_root = git_config_bool(var, value);
611 return 0;
613 if (!strcmp(var, "log.follow")) {
614 cfg->default_follow = git_config_bool(var, value);
615 return 0;
617 if (skip_prefix(var, "color.decorate.", &slot_name))
618 return parse_decorate_color_config(var, slot_name, value);
619 if (!strcmp(var, "log.mailmap")) {
620 cfg->use_mailmap_config = git_config_bool(var, value);
621 return 0;
623 if (!strcmp(var, "log.showsignature")) {
624 cfg->default_show_signature = git_config_bool(var, value);
625 return 0;
628 return git_diff_ui_config(var, value, ctx, cb);
631 int cmd_whatchanged(int argc,
632 const char **argv,
633 const char *prefix,
634 struct repository *repo UNUSED)
636 struct log_config cfg;
637 struct rev_info rev;
638 struct setup_revision_opt opt;
639 int ret;
641 log_config_init(&cfg);
642 init_diff_ui_defaults();
643 git_config(git_log_config, &cfg);
645 repo_init_revisions(the_repository, &rev, prefix);
646 git_config(grep_config, &rev.grep_filter);
648 rev.diff = 1;
649 rev.simplify_history = 0;
650 memset(&opt, 0, sizeof(opt));
651 opt.def = "HEAD";
652 opt.revarg_opt = REVARG_COMMITTISH;
653 cmd_log_init(argc, argv, prefix, &rev, &opt, &cfg);
654 if (!rev.diffopt.output_format)
655 rev.diffopt.output_format = DIFF_FORMAT_RAW;
657 ret = cmd_log_walk(&rev);
659 release_revisions(&rev);
660 log_config_release(&cfg);
661 return ret;
664 static void show_tagger(const char *buf, struct rev_info *rev)
666 struct strbuf out = STRBUF_INIT;
667 struct pretty_print_context pp = {0};
669 pp.fmt = rev->commit_format;
670 pp.date_mode = rev->date_mode;
671 pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
672 fprintf(rev->diffopt.file, "%s", out.buf);
673 strbuf_release(&out);
676 static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
678 struct object_id oidc;
679 struct object_context obj_context = {0};
680 char *buf;
681 unsigned long size;
683 fflush(rev->diffopt.file);
684 if (!rev->diffopt.flags.textconv_set_via_cmdline ||
685 !rev->diffopt.flags.allow_textconv)
686 return stream_blob_to_fd(1, oid, NULL, 0);
688 if (get_oid_with_context(the_repository, obj_name,
689 GET_OID_RECORD_PATH,
690 &oidc, &obj_context))
691 die(_("not a valid object name %s"), obj_name);
692 if (!obj_context.path ||
693 !textconv_object(the_repository, obj_context.path,
694 obj_context.mode, &oidc, 1, &buf, &size)) {
695 object_context_release(&obj_context);
696 return stream_blob_to_fd(1, oid, NULL, 0);
699 if (!buf)
700 die(_("git show %s: bad file"), obj_name);
702 write_or_die(1, buf, size);
703 object_context_release(&obj_context);
704 free(buf);
705 return 0;
708 static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
710 unsigned long size;
711 enum object_type type;
712 char *buf = repo_read_object_file(the_repository, oid, &type, &size);
713 int offset = 0;
715 if (!buf)
716 return error(_("could not read object %s"), oid_to_hex(oid));
718 assert(type == OBJ_TAG);
719 while (offset < size && buf[offset] != '\n') {
720 int new_offset = offset + 1;
721 const char *ident;
722 while (new_offset < size && buf[new_offset++] != '\n')
723 ; /* do nothing */
724 if (skip_prefix(buf + offset, "tagger ", &ident))
725 show_tagger(ident, rev);
726 offset = new_offset;
729 if (offset < size)
730 fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
731 free(buf);
732 return 0;
735 static int show_tree_object(const struct object_id *oid UNUSED,
736 struct strbuf *base UNUSED,
737 const char *pathname, unsigned mode,
738 void *context)
740 FILE *file = context;
741 fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
742 return 0;
745 static void show_setup_revisions_tweak(struct rev_info *rev)
747 if (rev->first_parent_only)
748 diff_merges_default_to_first_parent(rev);
749 else
750 diff_merges_default_to_dense_combined(rev);
751 if (!rev->diffopt.output_format)
752 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
755 int cmd_show(int argc,
756 const char **argv,
757 const char *prefix,
758 struct repository *repo UNUSED)
760 struct log_config cfg;
761 struct rev_info rev;
762 unsigned int i;
763 struct setup_revision_opt opt;
764 struct pathspec match_all;
765 int ret = 0;
767 log_config_init(&cfg);
768 init_diff_ui_defaults();
769 git_config(git_log_config, &cfg);
771 if (the_repository->gitdir) {
772 prepare_repo_settings(the_repository);
773 the_repository->settings.command_requires_full_index = 0;
776 memset(&match_all, 0, sizeof(match_all));
777 repo_init_revisions(the_repository, &rev, prefix);
778 git_config(grep_config, &rev.grep_filter);
780 rev.diff = 1;
781 rev.always_show_header = 1;
782 rev.no_walk = 1;
783 rev.diffopt.stat_width = -1; /* Scale to real terminal size */
785 memset(&opt, 0, sizeof(opt));
786 opt.def = "HEAD";
787 opt.tweak = show_setup_revisions_tweak;
788 cmd_log_init(argc, argv, prefix, &rev, &opt, &cfg);
790 if (!rev.no_walk) {
791 ret = cmd_log_walk(&rev);
792 release_revisions(&rev);
793 log_config_release(&cfg);
794 return ret;
797 rev.diffopt.no_free = 1;
798 for (i = 0; i < rev.pending.nr && !ret; i++) {
799 struct object *o = rev.pending.objects[i].item;
800 const char *name = rev.pending.objects[i].name;
801 switch (o->type) {
802 case OBJ_BLOB:
803 ret = show_blob_object(&o->oid, &rev, name);
804 break;
805 case OBJ_TAG: {
806 struct tag *t = (struct tag *)o;
807 struct object_id *oid = get_tagged_oid(t);
809 if (rev.shown_one)
810 putchar('\n');
811 fprintf(rev.diffopt.file, "%stag %s%s\n",
812 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
813 t->tag,
814 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
815 ret = show_tag_object(&o->oid, &rev);
816 rev.shown_one = 1;
817 if (ret)
818 break;
819 o = parse_object(the_repository, oid);
820 if (!o)
821 ret = error(_("could not read object %s"),
822 oid_to_hex(oid));
823 rev.pending.objects[i].item = o;
824 i--;
825 break;
827 case OBJ_TREE:
828 if (rev.shown_one)
829 putchar('\n');
830 fprintf(rev.diffopt.file, "%stree %s%s\n\n",
831 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
832 name,
833 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
834 read_tree(the_repository, (struct tree *)o,
835 &match_all, show_tree_object,
836 rev.diffopt.file);
837 rev.shown_one = 1;
838 break;
839 case OBJ_COMMIT:
841 struct object_array old;
842 struct object_array blank = OBJECT_ARRAY_INIT;
844 memcpy(&old, &rev.pending, sizeof(old));
845 memcpy(&rev.pending, &blank, sizeof(rev.pending));
847 add_object_array(o, name, &rev.pending);
848 ret = cmd_log_walk_no_free(&rev);
851 * No need for
852 * object_array_clear(&pending). It was
853 * cleared already in prepare_revision_walk()
855 memcpy(&rev.pending, &old, sizeof(rev.pending));
856 break;
858 default:
859 ret = error(_("unknown type: %d"), o->type);
863 rev.diffopt.no_free = 0;
864 diff_free(&rev.diffopt);
865 release_revisions(&rev);
866 log_config_release(&cfg);
868 return ret;
872 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
874 int cmd_log_reflog(int argc,
875 const char **argv,
876 const char *prefix,
877 struct repository *repo UNUSED)
879 struct log_config cfg;
880 struct rev_info rev;
881 struct setup_revision_opt opt;
882 int ret;
884 log_config_init(&cfg);
885 init_diff_ui_defaults();
886 git_config(git_log_config, &cfg);
888 repo_init_revisions(the_repository, &rev, prefix);
889 init_reflog_walk(&rev.reflog_info);
890 git_config(grep_config, &rev.grep_filter);
892 rev.verbose_header = 1;
893 memset(&opt, 0, sizeof(opt));
894 opt.def = "HEAD";
895 cmd_log_init_defaults(&rev, &cfg);
896 rev.abbrev_commit = 1;
897 rev.commit_format = CMIT_FMT_ONELINE;
898 rev.use_terminator = 1;
899 rev.always_show_header = 1;
900 cmd_log_init_finish(argc, argv, prefix, &rev, &opt, &cfg);
902 ret = cmd_log_walk(&rev);
904 release_revisions(&rev);
905 log_config_release(&cfg);
906 return ret;
909 static void log_setup_revisions_tweak(struct rev_info *rev)
911 if (rev->diffopt.flags.default_follow_renames &&
912 diff_check_follow_pathspec(&rev->prune_data, 0))
913 rev->diffopt.flags.follow_renames = 1;
915 if (rev->first_parent_only)
916 diff_merges_default_to_first_parent(rev);
919 int cmd_log(int argc,
920 const char **argv,
921 const char *prefix,
922 struct repository *repo UNUSED)
924 struct log_config cfg;
925 struct rev_info rev;
926 struct setup_revision_opt opt;
927 int ret;
929 log_config_init(&cfg);
930 init_diff_ui_defaults();
931 git_config(git_log_config, &cfg);
933 repo_init_revisions(the_repository, &rev, prefix);
934 git_config(grep_config, &rev.grep_filter);
936 rev.always_show_header = 1;
937 memset(&opt, 0, sizeof(opt));
938 opt.def = "HEAD";
939 opt.revarg_opt = REVARG_COMMITTISH;
940 opt.tweak = log_setup_revisions_tweak;
941 cmd_log_init(argc, argv, prefix, &rev, &opt, &cfg);
943 ret = cmd_log_walk(&rev);
945 release_revisions(&rev);
946 log_config_release(&cfg);
947 return ret;
950 /* format-patch */
952 enum cover_setting {
953 COVER_UNSET,
954 COVER_OFF,
955 COVER_ON,
956 COVER_AUTO
959 enum thread_level {
960 THREAD_UNSET,
961 THREAD_SHALLOW,
962 THREAD_DEEP
965 enum cover_from_description {
966 COVER_FROM_NONE,
967 COVER_FROM_MESSAGE,
968 COVER_FROM_SUBJECT,
969 COVER_FROM_AUTO
972 enum auto_base_setting {
973 AUTO_BASE_NEVER,
974 AUTO_BASE_ALWAYS,
975 AUTO_BASE_WHEN_ABLE
978 struct format_config {
979 struct log_config log;
980 enum thread_level thread;
981 int do_signoff;
982 enum auto_base_setting auto_base;
983 char *base_commit;
984 char *from;
985 char *signature;
986 char *signature_file;
987 enum cover_setting config_cover_letter;
988 char *config_output_directory;
989 enum cover_from_description cover_from_description_mode;
990 int show_notes;
991 struct display_notes_opt notes_opt;
992 int numbered_cmdline_opt;
993 int numbered;
994 int auto_number;
995 char *default_attach;
996 struct string_list extra_hdr;
997 struct string_list extra_to;
998 struct string_list extra_cc;
999 int keep_subject;
1000 int subject_prefix;
1001 struct strbuf sprefix;
1002 char *fmt_patch_suffix;
1005 static void format_config_init(struct format_config *cfg)
1007 memset(cfg, 0, sizeof(*cfg));
1008 log_config_init(&cfg->log);
1009 cfg->cover_from_description_mode = COVER_FROM_MESSAGE;
1010 cfg->auto_number = 1;
1011 string_list_init_dup(&cfg->extra_hdr);
1012 string_list_init_dup(&cfg->extra_to);
1013 string_list_init_dup(&cfg->extra_cc);
1014 strbuf_init(&cfg->sprefix, 0);
1015 cfg->fmt_patch_suffix = xstrdup(".patch");
1018 static void format_config_release(struct format_config *cfg)
1020 log_config_release(&cfg->log);
1021 free(cfg->base_commit);
1022 free(cfg->from);
1023 free(cfg->signature);
1024 free(cfg->signature_file);
1025 free(cfg->config_output_directory);
1026 free(cfg->default_attach);
1027 string_list_clear(&cfg->extra_hdr, 0);
1028 string_list_clear(&cfg->extra_to, 0);
1029 string_list_clear(&cfg->extra_cc, 0);
1030 strbuf_release(&cfg->sprefix);
1031 free(cfg->fmt_patch_suffix);
1034 static enum cover_from_description parse_cover_from_description(const char *arg)
1036 if (!arg || !strcmp(arg, "default"))
1037 return COVER_FROM_MESSAGE;
1038 else if (!strcmp(arg, "none"))
1039 return COVER_FROM_NONE;
1040 else if (!strcmp(arg, "message"))
1041 return COVER_FROM_MESSAGE;
1042 else if (!strcmp(arg, "subject"))
1043 return COVER_FROM_SUBJECT;
1044 else if (!strcmp(arg, "auto"))
1045 return COVER_FROM_AUTO;
1046 else
1047 die(_("%s: invalid cover from description mode"), arg);
1050 static void add_header(struct format_config *cfg, const char *value)
1052 struct string_list_item *item;
1053 int len = strlen(value);
1054 while (len && value[len - 1] == '\n')
1055 len--;
1057 if (!strncasecmp(value, "to: ", 4)) {
1058 item = string_list_append(&cfg->extra_to, value + 4);
1059 len -= 4;
1060 } else if (!strncasecmp(value, "cc: ", 4)) {
1061 item = string_list_append(&cfg->extra_cc, value + 4);
1062 len -= 4;
1063 } else {
1064 item = string_list_append(&cfg->extra_hdr, value);
1067 item->string[len] = '\0';
1070 static int git_format_config(const char *var, const char *value,
1071 const struct config_context *ctx, void *cb)
1073 struct format_config *cfg = cb;
1075 if (!strcmp(var, "format.headers")) {
1076 if (!value)
1077 die(_("format.headers without value"));
1078 add_header(cfg, value);
1079 return 0;
1081 if (!strcmp(var, "format.suffix")) {
1082 FREE_AND_NULL(cfg->fmt_patch_suffix);
1083 return git_config_string(&cfg->fmt_patch_suffix, var, value);
1085 if (!strcmp(var, "format.to")) {
1086 if (!value)
1087 return config_error_nonbool(var);
1088 string_list_append(&cfg->extra_to, value);
1089 return 0;
1091 if (!strcmp(var, "format.cc")) {
1092 if (!value)
1093 return config_error_nonbool(var);
1094 string_list_append(&cfg->extra_cc, value);
1095 return 0;
1097 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
1098 !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
1099 return 0;
1101 if (!strcmp(var, "format.numbered")) {
1102 if (value && !strcasecmp(value, "auto")) {
1103 cfg->auto_number = 1;
1104 return 0;
1106 cfg->numbered = git_config_bool(var, value);
1107 cfg->auto_number = cfg->auto_number && cfg->numbered;
1108 return 0;
1110 if (!strcmp(var, "format.attach")) {
1111 if (value && *value) {
1112 FREE_AND_NULL(cfg->default_attach);
1113 cfg->default_attach = xstrdup(value);
1114 } else if (value && !*value) {
1115 FREE_AND_NULL(cfg->default_attach);
1116 } else {
1117 FREE_AND_NULL(cfg->default_attach);
1118 cfg->default_attach = xstrdup(git_version_string);
1120 return 0;
1122 if (!strcmp(var, "format.thread")) {
1123 if (value && !strcasecmp(value, "deep")) {
1124 cfg->thread = THREAD_DEEP;
1125 return 0;
1127 if (value && !strcasecmp(value, "shallow")) {
1128 cfg->thread = THREAD_SHALLOW;
1129 return 0;
1131 cfg->thread = git_config_bool(var, value) ? THREAD_SHALLOW : THREAD_UNSET;
1132 return 0;
1134 if (!strcmp(var, "format.signoff")) {
1135 cfg->do_signoff = git_config_bool(var, value);
1136 return 0;
1138 if (!strcmp(var, "format.signature")) {
1139 FREE_AND_NULL(cfg->signature);
1140 return git_config_string(&cfg->signature, var, value);
1142 if (!strcmp(var, "format.signaturefile")) {
1143 FREE_AND_NULL(cfg->signature_file);
1144 return git_config_pathname(&cfg->signature_file, var, value);
1146 if (!strcmp(var, "format.coverletter")) {
1147 if (value && !strcasecmp(value, "auto")) {
1148 cfg->config_cover_letter = COVER_AUTO;
1149 return 0;
1151 cfg->config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
1152 return 0;
1154 if (!strcmp(var, "format.outputdirectory")) {
1155 FREE_AND_NULL(cfg->config_output_directory);
1156 return git_config_string(&cfg->config_output_directory, var, value);
1158 if (!strcmp(var, "format.useautobase")) {
1159 if (value && !strcasecmp(value, "whenAble")) {
1160 cfg->auto_base = AUTO_BASE_WHEN_ABLE;
1161 return 0;
1163 cfg->auto_base = git_config_bool(var, value) ? AUTO_BASE_ALWAYS : AUTO_BASE_NEVER;
1164 return 0;
1166 if (!strcmp(var, "format.from")) {
1167 int b = git_parse_maybe_bool(value);
1168 FREE_AND_NULL(cfg->from);
1169 if (b < 0)
1170 cfg->from = xstrdup(value);
1171 else if (b)
1172 cfg->from = xstrdup(git_committer_info(IDENT_NO_DATE));
1173 return 0;
1175 if (!strcmp(var, "format.forceinbodyfrom")) {
1176 force_in_body_from = git_config_bool(var, value);
1177 return 0;
1179 if (!strcmp(var, "format.notes")) {
1180 int b = git_parse_maybe_bool(value);
1181 if (b < 0)
1182 enable_ref_display_notes(&cfg->notes_opt, &cfg->show_notes, value);
1183 else if (b)
1184 enable_default_display_notes(&cfg->notes_opt, &cfg->show_notes);
1185 else
1186 disable_display_notes(&cfg->notes_opt, &cfg->show_notes);
1187 return 0;
1189 if (!strcmp(var, "format.coverfromdescription")) {
1190 cfg->cover_from_description_mode = parse_cover_from_description(value);
1191 return 0;
1193 if (!strcmp(var, "format.mboxrd")) {
1194 stdout_mboxrd = git_config_bool(var, value);
1195 return 0;
1197 if (!strcmp(var, "format.noprefix")) {
1198 format_no_prefix = 1;
1199 return 0;
1203 * ignore some porcelain config which would otherwise be parsed by
1204 * git_diff_ui_config(), via git_log_config(); we can't just avoid
1205 * diff_ui_config completely, because we do care about some ui options
1206 * like color.
1208 if (!strcmp(var, "diff.noprefix"))
1209 return 0;
1211 return git_log_config(var, value, ctx, &cfg->log);
1214 static const char *output_directory = NULL;
1215 static int outdir_offset;
1217 static int open_next_file(struct commit *commit, const char *subject,
1218 struct rev_info *rev, int quiet)
1220 struct strbuf filename = STRBUF_INIT;
1222 if (output_directory) {
1223 strbuf_addstr(&filename, output_directory);
1224 strbuf_complete(&filename, '/');
1227 if (rev->numbered_files)
1228 strbuf_addf(&filename, "%d", rev->nr);
1229 else if (commit)
1230 fmt_output_commit(&filename, commit, rev);
1231 else
1232 fmt_output_subject(&filename, subject, rev);
1234 if (!quiet)
1235 printf("%s\n", filename.buf + outdir_offset);
1237 if (!(rev->diffopt.file = fopen(filename.buf, "w"))) {
1238 error_errno(_("cannot open patch file %s"), filename.buf);
1239 strbuf_release(&filename);
1240 return -1;
1243 strbuf_release(&filename);
1244 return 0;
1247 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
1249 struct rev_info check_rev;
1250 struct commit *commit, *c1, *c2;
1251 struct object *o1, *o2;
1252 unsigned flags1, flags2;
1254 if (rev->pending.nr != 2)
1255 die(_("need exactly one range"));
1257 o1 = rev->pending.objects[0].item;
1258 o2 = rev->pending.objects[1].item;
1259 flags1 = o1->flags;
1260 flags2 = o2->flags;
1261 c1 = lookup_commit_reference(the_repository, &o1->oid);
1262 c2 = lookup_commit_reference(the_repository, &o2->oid);
1264 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
1265 die(_("not a range"));
1267 init_patch_ids(the_repository, ids);
1269 /* given a range a..b get all patch ids for b..a */
1270 repo_init_revisions(the_repository, &check_rev, rev->prefix);
1271 check_rev.max_parents = 1;
1272 o1->flags ^= UNINTERESTING;
1273 o2->flags ^= UNINTERESTING;
1274 add_pending_object(&check_rev, o1, "o1");
1275 add_pending_object(&check_rev, o2, "o2");
1276 if (prepare_revision_walk(&check_rev))
1277 die(_("revision walk setup failed"));
1279 while ((commit = get_revision(&check_rev)) != NULL) {
1280 add_commit_patch_id(commit, ids);
1283 /* reset for next revision walk */
1284 clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
1285 clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
1286 o1->flags = flags1;
1287 o2->flags = flags2;
1290 static void gen_message_id(struct rev_info *info, const char *base)
1292 struct strbuf buf = STRBUF_INIT;
1293 strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
1294 (timestamp_t) time(NULL),
1295 git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
1296 info->message_id = strbuf_detach(&buf, NULL);
1299 static void print_signature(const char *signature, FILE *file)
1301 if (!signature || !*signature)
1302 return;
1304 fprintf(file, "-- \n%s", signature);
1305 if (signature[strlen(signature)-1] != '\n')
1306 putc('\n', file);
1307 putc('\n', file);
1310 static char *find_branch_name(struct rev_info *rev)
1312 int i, positive = -1;
1313 struct object_id branch_oid;
1314 const struct object_id *tip_oid;
1315 const char *ref, *v;
1316 char *full_ref, *branch = NULL;
1318 for (i = 0; i < rev->cmdline.nr; i++) {
1319 if (rev->cmdline.rev[i].flags & UNINTERESTING)
1320 continue;
1321 if (positive < 0)
1322 positive = i;
1323 else
1324 return NULL;
1326 if (positive < 0)
1327 return NULL;
1328 ref = rev->cmdline.rev[positive].name;
1329 tip_oid = &rev->cmdline.rev[positive].item->oid;
1330 if (repo_dwim_ref(the_repository, ref, strlen(ref), &branch_oid,
1331 &full_ref, 0) &&
1332 skip_prefix(full_ref, "refs/heads/", &v) &&
1333 oideq(tip_oid, &branch_oid))
1334 branch = xstrdup(v);
1335 free(full_ref);
1336 return branch;
1339 static void show_diffstat(struct rev_info *rev,
1340 struct commit *origin, struct commit *head)
1342 struct diff_options opts;
1344 memcpy(&opts, &rev->diffopt, sizeof(opts));
1345 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1346 diff_setup_done(&opts);
1348 diff_tree_oid(get_commit_tree_oid(origin),
1349 get_commit_tree_oid(head),
1350 "", &opts);
1351 diffcore_std(&opts);
1352 diff_flush(&opts);
1354 fprintf(rev->diffopt.file, "\n");
1357 static void read_desc_file(struct strbuf *buf, const char *desc_file)
1359 if (strbuf_read_file(buf, desc_file, 0) < 0)
1360 die_errno(_("unable to read branch description file '%s'"),
1361 desc_file);
1364 static void prepare_cover_text(struct pretty_print_context *pp,
1365 const char *description_file,
1366 const char *branch_name,
1367 struct strbuf *sb,
1368 const char *encoding,
1369 int need_8bit_cte,
1370 const struct format_config *cfg)
1372 const char *subject = "*** SUBJECT HERE ***";
1373 const char *body = "*** BLURB HERE ***";
1374 struct strbuf description_sb = STRBUF_INIT;
1375 struct strbuf subject_sb = STRBUF_INIT;
1377 if (cfg->cover_from_description_mode == COVER_FROM_NONE)
1378 goto do_pp;
1380 if (description_file && *description_file)
1381 read_desc_file(&description_sb, description_file);
1382 else if (branch_name && *branch_name)
1383 read_branch_desc(&description_sb, branch_name);
1384 if (!description_sb.len)
1385 goto do_pp;
1387 if (cfg->cover_from_description_mode == COVER_FROM_SUBJECT ||
1388 cfg->cover_from_description_mode == COVER_FROM_AUTO)
1389 body = format_subject(&subject_sb, description_sb.buf, " ");
1391 if (cfg->cover_from_description_mode == COVER_FROM_MESSAGE ||
1392 (cfg->cover_from_description_mode == COVER_FROM_AUTO &&
1393 subject_sb.len > COVER_FROM_AUTO_MAX_SUBJECT_LEN))
1394 body = description_sb.buf;
1395 else
1396 subject = subject_sb.buf;
1398 do_pp:
1399 pp_email_subject(pp, &subject, sb, encoding, need_8bit_cte);
1400 pp_remainder(pp, &body, sb, 0);
1402 strbuf_release(&description_sb);
1403 strbuf_release(&subject_sb);
1406 static int get_notes_refs(struct string_list_item *item, void *arg)
1408 strvec_pushf(arg, "--notes=%s", item->string);
1409 return 0;
1412 static void get_notes_args(struct strvec *arg, struct rev_info *rev)
1414 if (!rev->show_notes) {
1415 strvec_push(arg, "--no-notes");
1416 } else if (rev->notes_opt.use_default_notes > 0 ||
1417 (rev->notes_opt.use_default_notes == -1 &&
1418 !rev->notes_opt.extra_notes_refs.nr)) {
1419 strvec_push(arg, "--notes");
1420 } else {
1421 for_each_string_list(&rev->notes_opt.extra_notes_refs, get_notes_refs, arg);
1425 static void make_cover_letter(struct rev_info *rev, int use_separate_file,
1426 struct commit *origin,
1427 int nr, struct commit **list,
1428 const char *description_file,
1429 const char *branch_name,
1430 int quiet,
1431 const struct format_config *cfg)
1433 const char *committer;
1434 struct shortlog log;
1435 struct strbuf sb = STRBUF_INIT;
1436 int i;
1437 const char *encoding = "UTF-8";
1438 int need_8bit_cte = 0;
1439 struct pretty_print_context pp = {0};
1440 struct commit *head = list[0];
1441 char *to_free = NULL;
1443 if (!cmit_fmt_is_mail(rev->commit_format))
1444 die(_("cover letter needs email format"));
1446 committer = git_committer_info(0);
1448 if (use_separate_file &&
1449 open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1450 die(_("failed to create cover-letter file"));
1452 log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1454 for (i = 0; !need_8bit_cte && i < nr; i++) {
1455 const char *buf = repo_get_commit_buffer(the_repository,
1456 list[i], NULL);
1457 if (has_non_ascii(buf))
1458 need_8bit_cte = 1;
1459 repo_unuse_commit_buffer(the_repository, list[i], buf);
1462 if (!branch_name)
1463 branch_name = to_free = find_branch_name(rev);
1465 pp.fmt = CMIT_FMT_EMAIL;
1466 pp.date_mode.type = DATE_RFC2822;
1467 pp.rev = rev;
1468 pp.encode_email_headers = rev->encode_email_headers;
1469 pp_user_info(&pp, NULL, &sb, committer, encoding);
1470 prepare_cover_text(&pp, description_file, branch_name, &sb,
1471 encoding, need_8bit_cte, cfg);
1472 fprintf(rev->diffopt.file, "%s\n", sb.buf);
1474 free(to_free);
1475 free(pp.after_subject);
1476 strbuf_release(&sb);
1478 shortlog_init(&log);
1479 log.wrap_lines = 1;
1480 log.wrap = MAIL_DEFAULT_WRAP;
1481 log.in1 = 2;
1482 log.in2 = 4;
1483 log.file = rev->diffopt.file;
1484 log.groups = SHORTLOG_GROUP_AUTHOR;
1485 shortlog_finish_setup(&log);
1486 for (i = 0; i < nr; i++)
1487 shortlog_add_commit(&log, list[i]);
1489 shortlog_output(&log);
1491 /* We can only do diffstat with a unique reference point */
1492 if (origin)
1493 show_diffstat(rev, origin, head);
1495 if (rev->idiff_oid1) {
1496 fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1497 show_interdiff(rev->idiff_oid1, rev->idiff_oid2, 0,
1498 &rev->diffopt);
1501 if (rev->rdiff1) {
1503 * Pass minimum required diff-options to range-diff; others
1504 * can be added later if deemed desirable.
1506 struct diff_options opts;
1507 struct strvec other_arg = STRVEC_INIT;
1508 struct range_diff_options range_diff_opts = {
1509 .creation_factor = rev->creation_factor,
1510 .dual_color = 1,
1511 .diffopt = &opts,
1512 .other_arg = &other_arg
1515 repo_diff_setup(the_repository, &opts);
1516 opts.file = rev->diffopt.file;
1517 opts.use_color = rev->diffopt.use_color;
1518 diff_setup_done(&opts);
1519 fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1520 get_notes_args(&other_arg, rev);
1521 show_range_diff(rev->rdiff1, rev->rdiff2, &range_diff_opts);
1522 strvec_clear(&other_arg);
1526 static char *clean_message_id(const char *msg_id)
1528 char ch;
1529 const char *a, *z, *m;
1531 m = msg_id;
1532 while ((ch = *m) && (isspace(ch) || (ch == '<')))
1533 m++;
1534 a = m;
1535 z = NULL;
1536 while ((ch = *m)) {
1537 if (!isspace(ch) && (ch != '>'))
1538 z = m;
1539 m++;
1541 if (!z)
1542 die(_("insane in-reply-to: %s"), msg_id);
1543 if (++z == m)
1544 return xstrdup(a);
1545 return xmemdupz(a, z - a);
1548 static const char *set_outdir(const char *prefix, const char *output_directory)
1550 if (output_directory && is_absolute_path(output_directory))
1551 return output_directory;
1553 if (!prefix || !*prefix) {
1554 if (output_directory)
1555 return output_directory;
1556 /* The user did not explicitly ask for "./" */
1557 outdir_offset = 2;
1558 return "./";
1561 outdir_offset = strlen(prefix);
1562 if (!output_directory)
1563 return prefix;
1565 return prefix_filename(prefix, output_directory);
1568 static const char * const builtin_format_patch_usage[] = {
1569 N_("git format-patch [<options>] [<since> | <revision-range>]"),
1570 NULL
1573 struct keep_callback_data {
1574 struct format_config *cfg;
1575 struct rev_info *revs;
1578 static int keep_callback(const struct option *opt, const char *arg, int unset)
1580 struct keep_callback_data *data = opt->value;
1581 BUG_ON_OPT_NEG(unset);
1582 BUG_ON_OPT_ARG(arg);
1583 data->revs->total = -1;
1584 data->cfg->keep_subject = 1;
1585 return 0;
1588 static int subject_prefix_callback(const struct option *opt, const char *arg,
1589 int unset)
1591 struct format_config *cfg = opt->value;
1593 BUG_ON_OPT_NEG(unset);
1594 cfg->subject_prefix = 1;
1595 strbuf_reset(&cfg->sprefix);
1596 strbuf_addstr(&cfg->sprefix, arg);
1597 return 0;
1600 static int rfc_callback(const struct option *opt, const char *arg,
1601 int unset)
1603 const char **rfc = opt->value;
1605 *rfc = opt->value;
1606 if (unset)
1607 *rfc = NULL;
1608 else
1609 *rfc = arg ? arg : "RFC";
1610 return 0;
1613 static int numbered_callback(const struct option *opt, const char *arg,
1614 int unset)
1616 struct format_config *cfg = opt->value;
1617 BUG_ON_OPT_ARG(arg);
1618 cfg->numbered = cfg->numbered_cmdline_opt = unset ? 0 : 1;
1619 if (unset)
1620 cfg->auto_number = 0;
1621 return 0;
1624 static int no_numbered_callback(const struct option *opt, const char *arg,
1625 int unset)
1627 BUG_ON_OPT_NEG(unset);
1628 return numbered_callback(opt, arg, 1);
1631 static int output_directory_callback(const struct option *opt, const char *arg,
1632 int unset)
1634 const char **dir = (const char **)opt->value;
1635 BUG_ON_OPT_NEG(unset);
1636 if (*dir)
1637 die(_("two output directories?"));
1638 *dir = arg;
1639 return 0;
1642 static int thread_callback(const struct option *opt, const char *arg, int unset)
1644 struct format_config *cfg = opt->value;
1646 if (unset)
1647 cfg->thread = THREAD_UNSET;
1648 else if (!arg || !strcmp(arg, "shallow"))
1649 cfg->thread = THREAD_SHALLOW;
1650 else if (!strcmp(arg, "deep"))
1651 cfg->thread = THREAD_DEEP;
1653 * Please update _git_formatpatch() in git-completion.bash
1654 * when you add new options.
1656 else
1657 return 1;
1658 return 0;
1661 static int attach_callback(const struct option *opt, const char *arg, int unset)
1663 struct rev_info *rev = (struct rev_info *)opt->value;
1664 if (unset)
1665 rev->mime_boundary = NULL;
1666 else if (arg)
1667 rev->mime_boundary = arg;
1668 else
1669 rev->mime_boundary = git_version_string;
1670 rev->no_inline = unset ? 0 : 1;
1671 return 0;
1674 static int inline_callback(const struct option *opt, const char *arg, int unset)
1676 struct rev_info *rev = (struct rev_info *)opt->value;
1677 if (unset)
1678 rev->mime_boundary = NULL;
1679 else if (arg)
1680 rev->mime_boundary = arg;
1681 else
1682 rev->mime_boundary = git_version_string;
1683 rev->no_inline = 0;
1684 return 0;
1687 static int header_callback(const struct option *opt, const char *arg,
1688 int unset)
1690 struct format_config *cfg = opt->value;
1692 if (unset) {
1693 string_list_clear(&cfg->extra_hdr, 0);
1694 string_list_clear(&cfg->extra_to, 0);
1695 string_list_clear(&cfg->extra_cc, 0);
1696 } else {
1697 add_header(cfg, arg);
1699 return 0;
1702 static int from_callback(const struct option *opt, const char *arg, int unset)
1704 char **from = opt->value;
1706 free(*from);
1708 if (unset)
1709 *from = NULL;
1710 else if (arg)
1711 *from = xstrdup(arg);
1712 else
1713 *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1714 return 0;
1717 static int base_callback(const struct option *opt, const char *arg, int unset)
1719 struct format_config *cfg = opt->value;
1721 if (unset) {
1722 cfg->auto_base = AUTO_BASE_NEVER;
1723 FREE_AND_NULL(cfg->base_commit);
1724 } else if (!strcmp(arg, "auto")) {
1725 cfg->auto_base = AUTO_BASE_ALWAYS;
1726 FREE_AND_NULL(cfg->base_commit);
1727 } else {
1728 cfg->auto_base = AUTO_BASE_NEVER;
1729 cfg->base_commit = xstrdup(arg);
1731 return 0;
1734 struct base_tree_info {
1735 struct object_id base_commit;
1736 int nr_patch_id, alloc_patch_id;
1737 struct object_id *patch_id;
1740 static struct commit *get_base_commit(const struct format_config *cfg,
1741 struct commit **list,
1742 int total)
1744 struct commit *base = NULL;
1745 struct commit **rev;
1746 int i = 0, rev_nr = 0, auto_select, die_on_failure, ret;
1748 switch (cfg->auto_base) {
1749 case AUTO_BASE_NEVER:
1750 if (cfg->base_commit) {
1751 auto_select = 0;
1752 die_on_failure = 1;
1753 } else {
1754 /* no base information is requested */
1755 return NULL;
1757 break;
1758 case AUTO_BASE_ALWAYS:
1759 case AUTO_BASE_WHEN_ABLE:
1760 if (cfg->base_commit) {
1761 BUG("requested automatic base selection but a commit was provided");
1762 } else {
1763 auto_select = 1;
1764 die_on_failure = cfg->auto_base == AUTO_BASE_ALWAYS;
1766 break;
1767 default:
1768 BUG("unexpected automatic base selection method");
1771 if (!auto_select) {
1772 base = lookup_commit_reference_by_name(cfg->base_commit);
1773 if (!base)
1774 die(_("unknown commit %s"), cfg->base_commit);
1775 } else {
1776 struct branch *curr_branch = branch_get(NULL);
1777 const char *upstream = branch_get_upstream(curr_branch, NULL);
1778 if (upstream) {
1779 struct commit_list *base_list = NULL;
1780 struct commit *commit;
1781 struct object_id oid;
1783 if (repo_get_oid(the_repository, upstream, &oid)) {
1784 if (die_on_failure)
1785 die(_("failed to resolve '%s' as a valid ref"), upstream);
1786 else
1787 return NULL;
1789 commit = lookup_commit_or_die(&oid, "upstream base");
1790 if (repo_get_merge_bases_many(the_repository,
1791 commit, total,
1792 list,
1793 &base_list) < 0 ||
1794 /* There should be one and only one merge base. */
1795 !base_list || base_list->next) {
1796 if (die_on_failure) {
1797 die(_("could not find exact merge base"));
1798 } else {
1799 free_commit_list(base_list);
1800 return NULL;
1803 base = base_list->item;
1804 free_commit_list(base_list);
1805 } else {
1806 if (die_on_failure)
1807 die(_("failed to get upstream, if you want to record base commit automatically,\n"
1808 "please use git branch --set-upstream-to to track a remote branch.\n"
1809 "Or you could specify base commit by --base=<base-commit-id> manually"));
1810 else
1811 return NULL;
1815 ALLOC_ARRAY(rev, total);
1816 for (i = 0; i < total; i++)
1817 rev[i] = list[i];
1819 rev_nr = total;
1821 * Get merge base through pair-wise computations
1822 * and store it in rev[0].
1824 while (rev_nr > 1) {
1825 for (i = 0; i < rev_nr / 2; i++) {
1826 struct commit_list *merge_base = NULL;
1827 if (repo_get_merge_bases(the_repository,
1828 rev[2 * i],
1829 rev[2 * i + 1], &merge_base) < 0 ||
1830 !merge_base || merge_base->next) {
1831 if (die_on_failure) {
1832 die(_("failed to find exact merge base"));
1833 } else {
1834 free_commit_list(merge_base);
1835 free(rev);
1836 return NULL;
1840 rev[i] = merge_base->item;
1841 free_commit_list(merge_base);
1844 if (rev_nr % 2)
1845 rev[i] = rev[2 * i];
1846 rev_nr = DIV_ROUND_UP(rev_nr, 2);
1849 ret = repo_in_merge_bases(the_repository, base, rev[0]);
1850 if (ret < 0)
1851 exit(128);
1852 if (!ret) {
1853 if (die_on_failure) {
1854 die(_("base commit should be the ancestor of revision list"));
1855 } else {
1856 free(rev);
1857 return NULL;
1861 for (i = 0; i < total; i++) {
1862 if (base == list[i]) {
1863 if (die_on_failure) {
1864 die(_("base commit shouldn't be in revision list"));
1865 } else {
1866 free(rev);
1867 return NULL;
1872 free(rev);
1873 return base;
1876 define_commit_slab(commit_base, int);
1878 static void prepare_bases(struct base_tree_info *bases,
1879 struct commit *base,
1880 struct commit **list,
1881 int total)
1883 struct commit *commit;
1884 struct rev_info revs;
1885 struct diff_options diffopt;
1886 struct commit_base commit_base;
1887 int i;
1889 if (!base)
1890 return;
1892 init_commit_base(&commit_base);
1893 repo_diff_setup(the_repository, &diffopt);
1894 diffopt.flags.recursive = 1;
1895 diff_setup_done(&diffopt);
1897 oidcpy(&bases->base_commit, &base->object.oid);
1899 repo_init_revisions(the_repository, &revs, NULL);
1900 revs.max_parents = 1;
1901 revs.topo_order = 1;
1902 for (i = 0; i < total; i++) {
1903 list[i]->object.flags &= ~UNINTERESTING;
1904 add_pending_object(&revs, &list[i]->object, "rev_list");
1905 *commit_base_at(&commit_base, list[i]) = 1;
1907 base->object.flags |= UNINTERESTING;
1908 add_pending_object(&revs, &base->object, "base");
1910 if (prepare_revision_walk(&revs))
1911 die(_("revision walk setup failed"));
1913 * Traverse the commits list, get prerequisite patch ids
1914 * and stuff them in bases structure.
1916 while ((commit = get_revision(&revs)) != NULL) {
1917 struct object_id oid;
1918 struct object_id *patch_id;
1919 if (*commit_base_at(&commit_base, commit))
1920 continue;
1921 if (commit_patch_id(commit, &diffopt, &oid, 0))
1922 die(_("cannot get patch id"));
1923 ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1924 patch_id = bases->patch_id + bases->nr_patch_id;
1925 oidcpy(patch_id, &oid);
1926 bases->nr_patch_id++;
1928 clear_commit_base(&commit_base);
1931 static void print_bases(struct base_tree_info *bases, FILE *file)
1933 int i;
1935 /* Only do this once, either for the cover or for the first one */
1936 if (is_null_oid(&bases->base_commit))
1937 return;
1939 /* Show the base commit */
1940 fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1942 /* Show the prerequisite patches */
1943 for (i = bases->nr_patch_id - 1; i >= 0; i--)
1944 fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1946 free(bases->patch_id);
1947 bases->nr_patch_id = 0;
1948 bases->alloc_patch_id = 0;
1949 oidclr(&bases->base_commit, the_repository->hash_algo);
1952 static const char *diff_title(struct strbuf *sb,
1953 const char *reroll_count,
1954 const char *generic,
1955 const char *rerolled)
1957 int v;
1959 /* RFC may be v0, so allow -v1 to diff against v0 */
1960 if (reroll_count && !strtol_i(reroll_count, 10, &v) &&
1961 v >= 1)
1962 strbuf_addf(sb, rerolled, v - 1);
1963 else
1964 strbuf_addstr(sb, generic);
1965 return sb->buf;
1968 static void infer_range_diff_ranges(struct strbuf *r1,
1969 struct strbuf *r2,
1970 const char *prev,
1971 struct commit *origin,
1972 struct commit *head)
1974 const char *head_oid = oid_to_hex(&head->object.oid);
1975 int prev_is_range = is_range_diff_range(prev);
1977 if (prev_is_range)
1978 strbuf_addstr(r1, prev);
1979 else
1980 strbuf_addf(r1, "%s..%s", head_oid, prev);
1982 if (origin)
1983 strbuf_addf(r2, "%s..%s", oid_to_hex(&origin->object.oid), head_oid);
1984 else if (prev_is_range)
1985 die(_("failed to infer range-diff origin of current series"));
1986 else {
1987 warning(_("using '%s' as range-diff origin of current series"), prev);
1988 strbuf_addf(r2, "%s..%s", prev, head_oid);
1992 int cmd_format_patch(int argc,
1993 const char **argv,
1994 const char *prefix,
1995 struct repository *repo UNUSED)
1997 struct format_config cfg;
1998 struct commit *commit;
1999 struct commit **list = NULL;
2000 struct rev_info rev;
2001 char *to_free = NULL;
2002 struct setup_revision_opt s_r_opt;
2003 int nr = 0, total, i;
2004 int use_stdout = 0;
2005 int start_number = -1;
2006 int just_numbers = 0;
2007 int ignore_if_in_upstream = 0;
2008 int cover_letter = -1;
2009 int boundary_count = 0;
2010 int no_binary_diff = 0;
2011 int zero_commit = 0;
2012 struct commit *origin = NULL;
2013 const char *in_reply_to = NULL;
2014 struct patch_ids ids;
2015 struct strbuf buf = STRBUF_INIT;
2016 int use_patch_format = 0;
2017 int quiet = 0;
2018 const char *reroll_count = NULL;
2019 char *cover_from_description_arg = NULL;
2020 char *description_file = NULL;
2021 char *branch_name = NULL;
2022 struct base_tree_info bases;
2023 struct commit *base;
2024 int show_progress = 0;
2025 struct progress *progress = NULL;
2026 struct oid_array idiff_prev = OID_ARRAY_INIT;
2027 struct strbuf idiff_title = STRBUF_INIT;
2028 const char *rdiff_prev = NULL;
2029 struct strbuf rdiff1 = STRBUF_INIT;
2030 struct strbuf rdiff2 = STRBUF_INIT;
2031 struct strbuf rdiff_title = STRBUF_INIT;
2032 const char *rfc = NULL;
2033 int creation_factor = -1;
2034 const char *signature = git_version_string;
2035 char *signature_to_free = NULL;
2036 char *signature_file_arg = NULL;
2037 struct keep_callback_data keep_callback_data = {
2038 .cfg = &cfg,
2039 .revs = &rev,
2041 const char *fmt_patch_suffix = NULL;
2043 const struct option builtin_format_patch_options[] = {
2044 OPT_CALLBACK_F('n', "numbered", &cfg, NULL,
2045 N_("use [PATCH n/m] even with a single patch"),
2046 PARSE_OPT_NOARG, numbered_callback),
2047 OPT_CALLBACK_F('N', "no-numbered", &cfg, NULL,
2048 N_("use [PATCH] even with multiple patches"),
2049 PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback),
2050 OPT_BOOL('s', "signoff", &cfg.do_signoff, N_("add a Signed-off-by trailer")),
2051 OPT_BOOL(0, "stdout", &use_stdout,
2052 N_("print patches to standard out")),
2053 OPT_BOOL(0, "cover-letter", &cover_letter,
2054 N_("generate a cover letter")),
2055 OPT_BOOL(0, "numbered-files", &just_numbers,
2056 N_("use simple number sequence for output file names")),
2057 OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
2058 N_("use <sfx> instead of '.patch'")),
2059 OPT_INTEGER(0, "start-number", &start_number,
2060 N_("start numbering patches at <n> instead of 1")),
2061 OPT_STRING('v', "reroll-count", &reroll_count, N_("reroll-count"),
2062 N_("mark the series as Nth re-roll")),
2063 OPT_INTEGER(0, "filename-max-length", &cfg.log.fmt_patch_name_max,
2064 N_("max length of output filename")),
2065 OPT_CALLBACK_F(0, "rfc", &rfc, N_("rfc"),
2066 N_("add <rfc> (default 'RFC') before 'PATCH'"),
2067 PARSE_OPT_OPTARG, rfc_callback),
2068 OPT_STRING(0, "cover-from-description", &cover_from_description_arg,
2069 N_("cover-from-description-mode"),
2070 N_("generate parts of a cover letter based on a branch's description")),
2071 OPT_FILENAME(0, "description-file", &description_file,
2072 N_("use branch description from file")),
2073 OPT_CALLBACK_F(0, "subject-prefix", &cfg, N_("prefix"),
2074 N_("use [<prefix>] instead of [PATCH]"),
2075 PARSE_OPT_NONEG, subject_prefix_callback),
2076 OPT_CALLBACK_F('o', "output-directory", &output_directory,
2077 N_("dir"), N_("store resulting files in <dir>"),
2078 PARSE_OPT_NONEG, output_directory_callback),
2079 OPT_CALLBACK_F('k', "keep-subject", &keep_callback_data, NULL,
2080 N_("don't strip/add [PATCH]"),
2081 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback),
2082 OPT_BOOL(0, "no-binary", &no_binary_diff,
2083 N_("don't output binary diffs")),
2084 OPT_BOOL(0, "zero-commit", &zero_commit,
2085 N_("output all-zero hash in From header")),
2086 OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
2087 N_("don't include a patch matching a commit upstream")),
2088 OPT_SET_INT_F('p', "no-stat", &use_patch_format,
2089 N_("show patch format instead of default (patch + stat)"),
2090 1, PARSE_OPT_NONEG),
2091 OPT_GROUP(N_("Messaging")),
2092 OPT_CALLBACK(0, "add-header", &cfg, N_("header"),
2093 N_("add email header"), header_callback),
2094 OPT_STRING_LIST(0, "to", &cfg.extra_to, N_("email"), N_("add To: header")),
2095 OPT_STRING_LIST(0, "cc", &cfg.extra_cc, N_("email"), N_("add Cc: header")),
2096 OPT_CALLBACK_F(0, "from", &cfg.from, N_("ident"),
2097 N_("set From address to <ident> (or committer ident if absent)"),
2098 PARSE_OPT_OPTARG, from_callback),
2099 OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
2100 N_("make first mail a reply to <message-id>")),
2101 OPT_CALLBACK_F(0, "attach", &rev, N_("boundary"),
2102 N_("attach the patch"), PARSE_OPT_OPTARG,
2103 attach_callback),
2104 OPT_CALLBACK_F(0, "inline", &rev, N_("boundary"),
2105 N_("inline the patch"),
2106 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
2107 inline_callback),
2108 OPT_CALLBACK_F(0, "thread", &cfg, N_("style"),
2109 N_("enable message threading, styles: shallow, deep"),
2110 PARSE_OPT_OPTARG, thread_callback),
2111 OPT_STRING(0, "signature", &signature, N_("signature"),
2112 N_("add a signature")),
2113 OPT_CALLBACK_F(0, "base", &cfg, N_("base-commit"),
2114 N_("add prerequisite tree info to the patch series"),
2115 0, base_callback),
2116 OPT_FILENAME(0, "signature-file", &signature_file_arg,
2117 N_("add a signature from a file")),
2118 OPT__QUIET(&quiet, N_("don't print the patch filenames")),
2119 OPT_BOOL(0, "progress", &show_progress,
2120 N_("show progress while generating patches")),
2121 OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
2122 N_("show changes against <rev> in cover letter or single patch"),
2123 parse_opt_object_name),
2124 OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
2125 N_("show changes against <refspec> in cover letter or single patch")),
2126 OPT_INTEGER(0, "creation-factor", &creation_factor,
2127 N_("percentage by which creation is weighted")),
2128 OPT_BOOL(0, "force-in-body-from", &force_in_body_from,
2129 N_("show in-body From: even if identical to the e-mail header")),
2130 OPT_END()
2133 format_config_init(&cfg);
2134 init_diff_ui_defaults();
2135 init_display_notes(&cfg.notes_opt);
2136 git_config(git_format_config, &cfg);
2137 repo_init_revisions(the_repository, &rev, prefix);
2138 git_config(grep_config, &rev.grep_filter);
2140 rev.show_notes = cfg.show_notes;
2141 memcpy(&rev.notes_opt, &cfg.notes_opt, sizeof(cfg.notes_opt));
2142 rev.commit_format = CMIT_FMT_EMAIL;
2143 rev.encode_email_headers = cfg.log.default_encode_email_headers;
2144 rev.expand_tabs_in_log_default = 0;
2145 rev.verbose_header = 1;
2146 rev.diff = 1;
2147 rev.max_parents = 1;
2148 rev.diffopt.flags.recursive = 1;
2149 rev.diffopt.no_free = 1;
2150 memset(&s_r_opt, 0, sizeof(s_r_opt));
2151 s_r_opt.def = "HEAD";
2152 s_r_opt.revarg_opt = REVARG_COMMITTISH;
2154 strbuf_addstr(&cfg.sprefix, cfg.log.fmt_patch_subject_prefix);
2155 if (format_no_prefix)
2156 diff_set_noprefix(&rev.diffopt);
2158 if (cfg.default_attach) {
2159 rev.mime_boundary = cfg.default_attach;
2160 rev.no_inline = 1;
2164 * Parse the arguments before setup_revisions(), or something
2165 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
2166 * possibly a valid SHA1.
2168 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
2169 builtin_format_patch_usage,
2170 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
2171 PARSE_OPT_KEEP_DASHDASH);
2173 rev.force_in_body_from = force_in_body_from;
2175 if (!fmt_patch_suffix)
2176 fmt_patch_suffix = cfg.fmt_patch_suffix;
2178 /* Make sure "0000-$sub.patch" gives non-negative length for $sub */
2179 if (cfg.log.fmt_patch_name_max <= strlen("0000-") + strlen(fmt_patch_suffix))
2180 cfg.log.fmt_patch_name_max = strlen("0000-") + strlen(fmt_patch_suffix);
2182 if (cover_from_description_arg)
2183 cfg.cover_from_description_mode = parse_cover_from_description(cover_from_description_arg);
2185 if (rfc && rfc[0]) {
2186 cfg.subject_prefix = 1;
2187 if (rfc[0] == '-')
2188 strbuf_addf(&cfg.sprefix, " %s", rfc + 1);
2189 else
2190 strbuf_insertf(&cfg.sprefix, 0, "%s ", rfc);
2193 if (reroll_count) {
2194 strbuf_addf(&cfg.sprefix, " v%s", reroll_count);
2195 rev.reroll_count = reroll_count;
2198 rev.subject_prefix = cfg.sprefix.buf;
2200 for (i = 0; i < cfg.extra_hdr.nr; i++) {
2201 strbuf_addstr(&buf, cfg.extra_hdr.items[i].string);
2202 strbuf_addch(&buf, '\n');
2205 if (cfg.extra_to.nr)
2206 strbuf_addstr(&buf, "To: ");
2207 for (i = 0; i < cfg.extra_to.nr; i++) {
2208 if (i)
2209 strbuf_addstr(&buf, " ");
2210 strbuf_addstr(&buf, cfg.extra_to.items[i].string);
2211 if (i + 1 < cfg.extra_to.nr)
2212 strbuf_addch(&buf, ',');
2213 strbuf_addch(&buf, '\n');
2216 if (cfg.extra_cc.nr)
2217 strbuf_addstr(&buf, "Cc: ");
2218 for (i = 0; i < cfg.extra_cc.nr; i++) {
2219 if (i)
2220 strbuf_addstr(&buf, " ");
2221 strbuf_addstr(&buf, cfg.extra_cc.items[i].string);
2222 if (i + 1 < cfg.extra_cc.nr)
2223 strbuf_addch(&buf, ',');
2224 strbuf_addch(&buf, '\n');
2227 rev.extra_headers = to_free = strbuf_detach(&buf, NULL);
2229 if (cfg.from) {
2230 if (split_ident_line(&rev.from_ident, cfg.from, strlen(cfg.from)))
2231 die(_("invalid ident line: %s"), cfg.from);
2234 if (start_number < 0)
2235 start_number = 1;
2238 * If numbered is set solely due to format.numbered in config,
2239 * and it would conflict with --keep-subject (-k) from the
2240 * command line, reset "numbered".
2242 if (cfg.numbered && cfg.keep_subject && !cfg.numbered_cmdline_opt)
2243 cfg.numbered = 0;
2245 if (cfg.numbered && cfg.keep_subject)
2246 die(_("options '%s' and '%s' cannot be used together"), "-n", "-k");
2247 if (cfg.keep_subject && cfg.subject_prefix)
2248 die(_("options '%s' and '%s' cannot be used together"), "--subject-prefix/--rfc", "-k");
2249 rev.preserve_subject = cfg.keep_subject;
2251 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
2252 if (argc > 1)
2253 die(_("unrecognized argument: %s"), argv[1]);
2255 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
2256 die(_("--name-only does not make sense"));
2257 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
2258 die(_("--name-status does not make sense"));
2259 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
2260 die(_("--check does not make sense"));
2261 if (rev.remerge_diff)
2262 die(_("--remerge-diff does not make sense"));
2264 if (!use_patch_format &&
2265 (!rev.diffopt.output_format ||
2266 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
2267 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
2268 if (!rev.diffopt.stat_width)
2269 rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
2271 /* Always generate a patch */
2272 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
2273 rev.always_show_header = 1;
2275 rev.zero_commit = zero_commit;
2276 rev.patch_name_max = cfg.log.fmt_patch_name_max;
2278 if (!rev.diffopt.flags.text && !no_binary_diff)
2279 rev.diffopt.flags.binary = 1;
2281 if (rev.show_notes)
2282 load_display_notes(&rev.notes_opt);
2284 die_for_incompatible_opt3(use_stdout, "--stdout",
2285 rev.diffopt.close_file, "--output",
2286 !!output_directory, "--output-directory");
2288 if (use_stdout && stdout_mboxrd)
2289 rev.commit_format = CMIT_FMT_MBOXRD;
2291 if (use_stdout) {
2292 setup_pager();
2293 } else if (!rev.diffopt.close_file) {
2294 int saved;
2296 if (!output_directory)
2297 output_directory = cfg.config_output_directory;
2298 output_directory = set_outdir(prefix, output_directory);
2300 if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
2301 rev.diffopt.use_color = GIT_COLOR_NEVER;
2303 * We consider <outdir> as 'outside of gitdir', therefore avoid
2304 * applying adjust_shared_perm in s-c-l-d.
2306 saved = get_shared_repository();
2307 set_shared_repository(0);
2308 switch (safe_create_leading_directories_const(output_directory)) {
2309 case SCLD_OK:
2310 case SCLD_EXISTS:
2311 break;
2312 default:
2313 die(_("could not create leading directories "
2314 "of '%s'"), output_directory);
2316 set_shared_repository(saved);
2317 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
2318 die_errno(_("could not create directory '%s'"),
2319 output_directory);
2322 if (rev.pending.nr == 1) {
2323 int check_head = 0;
2325 if (rev.max_count < 0 && !rev.show_root_diff) {
2327 * This is traditional behaviour of "git format-patch
2328 * origin" that prepares what the origin side still
2329 * does not have.
2331 rev.pending.objects[0].item->flags |= UNINTERESTING;
2332 add_head_to_pending(&rev);
2333 check_head = 1;
2336 * Otherwise, it is "format-patch -22 HEAD", and/or
2337 * "format-patch --root HEAD". The user wants
2338 * get_revision() to do the usual traversal.
2341 if (!strcmp(rev.pending.objects[0].name, "HEAD"))
2342 check_head = 1;
2344 if (check_head) {
2345 const char *ref, *v;
2346 ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
2347 "HEAD",
2348 RESOLVE_REF_READING,
2349 NULL, NULL);
2350 if (ref && skip_prefix(ref, "refs/heads/", &v))
2351 branch_name = xstrdup(v);
2352 else
2353 branch_name = xstrdup(""); /* no branch */
2358 * We cannot move this anywhere earlier because we do want to
2359 * know if --root was given explicitly from the command line.
2361 rev.show_root_diff = 1;
2363 if (ignore_if_in_upstream) {
2364 /* Don't say anything if head and upstream are the same. */
2365 if (rev.pending.nr == 2) {
2366 struct object_array_entry *o = rev.pending.objects;
2367 if (oideq(&o[0].item->oid, &o[1].item->oid))
2368 goto done;
2370 get_patch_ids(&rev, &ids);
2373 if (prepare_revision_walk(&rev))
2374 die(_("revision walk setup failed"));
2375 rev.boundary = 1;
2376 while ((commit = get_revision(&rev)) != NULL) {
2377 if (commit->object.flags & BOUNDARY) {
2378 boundary_count++;
2379 origin = (boundary_count == 1) ? commit : NULL;
2380 continue;
2383 if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
2384 continue;
2386 nr++;
2387 REALLOC_ARRAY(list, nr);
2388 list[nr - 1] = commit;
2390 if (nr == 0)
2391 /* nothing to do */
2392 goto done;
2393 total = nr;
2394 if (cover_letter == -1) {
2395 if (cfg.config_cover_letter == COVER_AUTO)
2396 cover_letter = (total > 1);
2397 else if ((idiff_prev.nr || rdiff_prev) && (total > 1))
2398 cover_letter = (cfg.config_cover_letter != COVER_OFF);
2399 else
2400 cover_letter = (cfg.config_cover_letter == COVER_ON);
2402 if (!cfg.keep_subject && cfg.auto_number && (total > 1 || cover_letter))
2403 cfg.numbered = 1;
2404 if (cfg.numbered)
2405 rev.total = total + start_number - 1;
2407 if (idiff_prev.nr) {
2408 if (!cover_letter && total != 1)
2409 die(_("--interdiff requires --cover-letter or single patch"));
2410 rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
2411 rev.idiff_oid2 = get_commit_tree_oid(list[0]);
2412 rev.idiff_title = diff_title(&idiff_title, reroll_count,
2413 _("Interdiff:"),
2414 _("Interdiff against v%d:"));
2417 if (creation_factor < 0)
2418 creation_factor = CREATION_FACTOR_FOR_THE_SAME_SERIES;
2419 else if (!rdiff_prev)
2420 die(_("the option '%s' requires '%s'"), "--creation-factor", "--range-diff");
2422 if (rdiff_prev) {
2423 if (!cover_letter && total != 1)
2424 die(_("--range-diff requires --cover-letter or single patch"));
2426 infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
2427 origin, list[0]);
2428 rev.rdiff1 = rdiff1.buf;
2429 rev.rdiff2 = rdiff2.buf;
2430 rev.creation_factor = creation_factor;
2431 rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
2432 _("Range-diff:"),
2433 _("Range-diff against v%d:"));
2437 * The order of precedence is:
2439 * 1. The `--signature` and `--no-signature` options.
2440 * 2. The `--signature-file` option.
2441 * 3. The `format.signature` config.
2442 * 4. The `format.signatureFile` config.
2443 * 5. Default `git_version_string`.
2445 if (!signature) {
2446 ; /* --no-signature inhibits all signatures */
2447 } else if (signature && signature != git_version_string) {
2448 ; /* non-default signature already set */
2449 } else if (signature_file_arg || (cfg.signature_file && !cfg.signature)) {
2450 struct strbuf buf = STRBUF_INIT;
2451 const char *signature_file = signature_file_arg ?
2452 signature_file_arg : cfg.signature_file;
2454 if (strbuf_read_file(&buf, signature_file, 128) < 0)
2455 die_errno(_("unable to read signature file '%s'"), signature_file);
2456 signature = signature_to_free = strbuf_detach(&buf, NULL);
2457 } else if (cfg.signature) {
2458 signature = cfg.signature;
2461 memset(&bases, 0, sizeof(bases));
2462 base = get_base_commit(&cfg, list, nr);
2463 if (base) {
2464 reset_revision_walk();
2465 clear_object_flags(UNINTERESTING);
2466 prepare_bases(&bases, base, list, nr);
2469 if (in_reply_to || cfg.thread || cover_letter) {
2470 rev.ref_message_ids = xmalloc(sizeof(*rev.ref_message_ids));
2471 string_list_init_dup(rev.ref_message_ids);
2473 if (in_reply_to) {
2474 char *msgid = clean_message_id(in_reply_to);
2475 string_list_append_nodup(rev.ref_message_ids, msgid);
2477 rev.numbered_files = just_numbers;
2478 rev.patch_suffix = fmt_patch_suffix;
2479 if (cover_letter) {
2480 if (cfg.thread)
2481 gen_message_id(&rev, "cover");
2482 make_cover_letter(&rev, !!output_directory,
2483 origin, nr, list, description_file, branch_name, quiet, &cfg);
2484 print_bases(&bases, rev.diffopt.file);
2485 print_signature(signature, rev.diffopt.file);
2486 total++;
2487 start_number--;
2488 /* interdiff/range-diff in cover-letter; omit from patches */
2489 rev.idiff_oid1 = NULL;
2490 rev.rdiff1 = NULL;
2492 rev.add_signoff = cfg.do_signoff;
2494 if (show_progress)
2495 progress = start_delayed_progress(_("Generating patches"), total);
2496 while (0 <= --nr) {
2497 int shown;
2498 display_progress(progress, total - nr);
2499 commit = list[nr];
2500 rev.nr = total - nr + (start_number - 1);
2501 /* Make the second and subsequent mails replies to the first */
2502 if (cfg.thread) {
2503 /* Have we already had a message ID? */
2504 if (rev.message_id) {
2506 * For deep threading: make every mail
2507 * a reply to the previous one, no
2508 * matter what other options are set.
2510 * For shallow threading:
2512 * Without --cover-letter and
2513 * --in-reply-to, make every mail a
2514 * reply to the one before.
2516 * With --in-reply-to but no
2517 * --cover-letter, make every mail a
2518 * reply to the <reply-to>.
2520 * With --cover-letter, make every
2521 * mail but the cover letter a reply
2522 * to the cover letter. The cover
2523 * letter is a reply to the
2524 * --in-reply-to, if specified.
2526 if (cfg.thread == THREAD_SHALLOW
2527 && rev.ref_message_ids->nr > 0
2528 && (!cover_letter || rev.nr > 1))
2529 free(rev.message_id);
2530 else
2531 string_list_append_nodup(rev.ref_message_ids,
2532 rev.message_id);
2534 gen_message_id(&rev, oid_to_hex(&commit->object.oid));
2537 if (output_directory &&
2538 open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
2539 die(_("failed to create output files"));
2540 shown = log_tree_commit(&rev, commit);
2541 free_commit_buffer(the_repository->parsed_objects,
2542 commit);
2544 /* We put one extra blank line between formatted
2545 * patches and this flag is used by log-tree code
2546 * to see if it needs to emit a LF before showing
2547 * the log; when using one file per patch, we do
2548 * not want the extra blank line.
2550 if (output_directory)
2551 rev.shown_one = 0;
2552 if (shown) {
2553 print_bases(&bases, rev.diffopt.file);
2554 if (rev.mime_boundary)
2555 fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
2556 mime_boundary_leader,
2557 rev.mime_boundary);
2558 else
2559 print_signature(signature, rev.diffopt.file);
2561 if (output_directory) {
2562 fclose(rev.diffopt.file);
2563 rev.diffopt.file = NULL;
2566 stop_progress(&progress);
2567 free(list);
2568 if (ignore_if_in_upstream)
2569 free_patch_ids(&ids);
2571 done:
2572 oid_array_clear(&idiff_prev);
2573 strbuf_release(&idiff_title);
2574 strbuf_release(&rdiff1);
2575 strbuf_release(&rdiff2);
2576 strbuf_release(&rdiff_title);
2577 free(description_file);
2578 free(signature_file_arg);
2579 free(signature_to_free);
2580 free(branch_name);
2581 free(to_free);
2582 free(rev.message_id);
2583 if (rev.ref_message_ids)
2584 string_list_clear(rev.ref_message_ids, 0);
2585 free(rev.ref_message_ids);
2586 rev.diffopt.no_free = 0;
2587 release_revisions(&rev);
2588 format_config_release(&cfg);
2589 return 0;
2592 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
2594 struct object_id oid;
2595 if (repo_get_oid(the_repository, arg, &oid) == 0) {
2596 struct commit *commit = lookup_commit_reference(the_repository,
2597 &oid);
2598 if (commit) {
2599 commit->object.flags |= flags;
2600 add_pending_object(revs, &commit->object, arg);
2601 return 0;
2604 return -1;
2607 static const char * const cherry_usage[] = {
2608 N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
2609 NULL
2612 static void print_commit(char sign, struct commit *commit, int verbose,
2613 int abbrev, FILE *file)
2615 if (!verbose) {
2616 fprintf(file, "%c %s\n", sign,
2617 repo_find_unique_abbrev(the_repository, &commit->object.oid, abbrev));
2618 } else {
2619 struct strbuf buf = STRBUF_INIT;
2620 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2621 fprintf(file, "%c %s %s\n", sign,
2622 repo_find_unique_abbrev(the_repository, &commit->object.oid, abbrev),
2623 buf.buf);
2624 strbuf_release(&buf);
2628 int cmd_cherry(int argc,
2629 const char **argv,
2630 const char *prefix,
2631 struct repository *repo UNUSED)
2633 struct rev_info revs;
2634 struct patch_ids ids;
2635 struct commit *commit;
2636 struct commit_list *list = NULL;
2637 struct branch *current_branch;
2638 const char *upstream;
2639 const char *head = "HEAD";
2640 const char *limit = NULL;
2641 int verbose = 0, abbrev = 0;
2643 struct option options[] = {
2644 OPT__ABBREV(&abbrev),
2645 OPT__VERBOSE(&verbose, N_("be verbose")),
2646 OPT_END()
2649 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
2651 switch (argc) {
2652 case 3:
2653 limit = argv[2];
2654 /* FALLTHROUGH */
2655 case 2:
2656 head = argv[1];
2657 /* FALLTHROUGH */
2658 case 1:
2659 upstream = argv[0];
2660 break;
2661 default:
2662 current_branch = branch_get(NULL);
2663 upstream = branch_get_upstream(current_branch, NULL);
2664 if (!upstream) {
2665 fprintf(stderr, _("Could not find a tracked"
2666 " remote branch, please"
2667 " specify <upstream> manually.\n"));
2668 usage_with_options(cherry_usage, options);
2672 repo_init_revisions(the_repository, &revs, prefix);
2673 revs.max_parents = 1;
2675 if (add_pending_commit(head, &revs, 0))
2676 die(_("unknown commit %s"), head);
2677 if (add_pending_commit(upstream, &revs, UNINTERESTING))
2678 die(_("unknown commit %s"), upstream);
2680 /* Don't say anything if head and upstream are the same. */
2681 if (revs.pending.nr == 2) {
2682 struct object_array_entry *o = revs.pending.objects;
2683 if (oideq(&o[0].item->oid, &o[1].item->oid))
2684 return 0;
2687 get_patch_ids(&revs, &ids);
2689 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2690 die(_("unknown commit %s"), limit);
2692 /* reverse the list of commits */
2693 if (prepare_revision_walk(&revs))
2694 die(_("revision walk setup failed"));
2695 while ((commit = get_revision(&revs)) != NULL) {
2696 commit_list_insert(commit, &list);
2699 for (struct commit_list *l = list; l; l = l->next) {
2700 char sign = '+';
2702 commit = l->item;
2703 if (has_commit_patch_id(commit, &ids))
2704 sign = '-';
2705 print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2708 free_commit_list(list);
2709 free_patch_ids(&ids);
2710 return 0;