t1092: fix buggy sparse "blame" test
[git.git] / builtin / log.c
blob9b937d59b83dc29691d9cb940223c981f38ff7bf
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"
38 #include "tmp-objdir.h"
40 #define MAIL_DEFAULT_WRAP 72
41 #define COVER_FROM_AUTO_MAX_SUBJECT_LEN 100
42 #define FORMAT_PATCH_NAME_MAX_DEFAULT 64
44 /* Set a default date-time format for git log ("log.date" config variable) */
45 static const char *default_date_mode = NULL;
47 static int default_abbrev_commit;
48 static int default_show_root = 1;
49 static int default_follow;
50 static int default_show_signature;
51 static int default_encode_email_headers = 1;
52 static int decoration_style;
53 static int decoration_given;
54 static int use_mailmap_config = 1;
55 static const char *fmt_patch_subject_prefix = "PATCH";
56 static int fmt_patch_name_max = FORMAT_PATCH_NAME_MAX_DEFAULT;
57 static const char *fmt_pretty;
59 static const char * const builtin_log_usage[] = {
60 N_("git log [<options>] [<revision-range>] [[--] <path>...]"),
61 N_("git show [<options>] <object>..."),
62 NULL
65 struct line_opt_callback_data {
66 struct rev_info *rev;
67 const char *prefix;
68 struct string_list args;
71 static int session_is_interactive(void)
73 return isatty(1) || pager_in_use();
76 static int auto_decoration_style(void)
78 return session_is_interactive() ? DECORATE_SHORT_REFS : 0;
81 static int parse_decoration_style(const char *value)
83 switch (git_parse_maybe_bool(value)) {
84 case 1:
85 return DECORATE_SHORT_REFS;
86 case 0:
87 return 0;
88 default:
89 break;
91 if (!strcmp(value, "full"))
92 return DECORATE_FULL_REFS;
93 else if (!strcmp(value, "short"))
94 return DECORATE_SHORT_REFS;
95 else if (!strcmp(value, "auto"))
96 return auto_decoration_style();
98 * Please update _git_log() in git-completion.bash when you
99 * add new decoration styles.
101 return -1;
104 static int decorate_callback(const struct option *opt, const char *arg, int unset)
106 if (unset)
107 decoration_style = 0;
108 else if (arg)
109 decoration_style = parse_decoration_style(arg);
110 else
111 decoration_style = DECORATE_SHORT_REFS;
113 if (decoration_style < 0)
114 die(_("invalid --decorate option: %s"), arg);
116 decoration_given = 1;
118 return 0;
121 static int log_line_range_callback(const struct option *option, const char *arg, int unset)
123 struct line_opt_callback_data *data = option->value;
125 BUG_ON_OPT_NEG(unset);
127 if (!arg)
128 return -1;
130 data->rev->line_level_traverse = 1;
131 string_list_append(&data->args, arg);
133 return 0;
136 static void init_log_defaults(void)
138 init_diff_ui_defaults();
140 decoration_style = auto_decoration_style();
143 static void cmd_log_init_defaults(struct rev_info *rev)
145 if (fmt_pretty)
146 get_commit_format(fmt_pretty, rev);
147 if (default_follow)
148 rev->diffopt.flags.default_follow_renames = 1;
149 rev->verbose_header = 1;
150 rev->diffopt.flags.recursive = 1;
151 rev->diffopt.stat_width = -1; /* use full terminal width */
152 rev->diffopt.stat_graph_width = -1; /* respect statGraphWidth config */
153 rev->abbrev_commit = default_abbrev_commit;
154 rev->show_root_diff = default_show_root;
155 rev->subject_prefix = fmt_patch_subject_prefix;
156 rev->patch_name_max = fmt_patch_name_max;
157 rev->show_signature = default_show_signature;
158 rev->encode_email_headers = default_encode_email_headers;
159 rev->diffopt.flags.allow_textconv = 1;
161 if (default_date_mode)
162 parse_date_format(default_date_mode, &rev->date_mode);
165 static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
166 struct rev_info *rev, struct setup_revision_opt *opt)
168 struct userformat_want w;
169 int quiet = 0, source = 0, mailmap;
170 static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
171 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
172 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
173 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
174 struct decoration_filter decoration_filter = {&decorate_refs_include,
175 &decorate_refs_exclude,
176 &decorate_refs_exclude_config};
177 static struct revision_sources revision_sources;
179 const struct option builtin_log_options[] = {
180 OPT__QUIET(&quiet, N_("suppress diff output")),
181 OPT_BOOL(0, "source", &source, N_("show source")),
182 OPT_BOOL(0, "use-mailmap", &mailmap, N_("use mail map file")),
183 OPT_ALIAS(0, "mailmap", "use-mailmap"),
184 OPT_STRING_LIST(0, "decorate-refs", &decorate_refs_include,
185 N_("pattern"), N_("only decorate refs that match <pattern>")),
186 OPT_STRING_LIST(0, "decorate-refs-exclude", &decorate_refs_exclude,
187 N_("pattern"), N_("do not decorate refs that match <pattern>")),
188 OPT_CALLBACK_F(0, "decorate", NULL, NULL, N_("decorate options"),
189 PARSE_OPT_OPTARG, decorate_callback),
190 OPT_CALLBACK('L', NULL, &line_cb, "range:file",
191 N_("trace the evolution of line range <start>,<end> or function :<funcname> in <file>"),
192 log_line_range_callback),
193 OPT_END()
196 line_cb.rev = rev;
197 line_cb.prefix = prefix;
199 mailmap = use_mailmap_config;
200 argc = parse_options(argc, argv, prefix,
201 builtin_log_options, builtin_log_usage,
202 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
203 PARSE_OPT_KEEP_DASHDASH);
205 if (quiet)
206 rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
207 argc = setup_revisions(argc, argv, rev, opt);
209 /* Any arguments at this point are not recognized */
210 if (argc > 1)
211 die(_("unrecognized argument: %s"), argv[1]);
213 if (rev->line_level_traverse && rev->prune_data.nr)
214 die(_("-L<range>:<file> cannot be used with pathspec"));
216 memset(&w, 0, sizeof(w));
217 userformat_find_requirements(NULL, &w);
219 if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
220 rev->show_notes = 1;
221 if (rev->show_notes)
222 load_display_notes(&rev->notes_opt);
224 if ((rev->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
225 rev->diffopt.filter || rev->diffopt.flags.follow_renames)
226 rev->always_show_header = 0;
228 if (source || w.source) {
229 init_revision_sources(&revision_sources);
230 rev->sources = &revision_sources;
233 if (mailmap) {
234 rev->mailmap = xmalloc(sizeof(struct string_list));
235 string_list_init_nodup(rev->mailmap);
236 read_mailmap(rev->mailmap);
239 if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
241 * "log --pretty=raw" is special; ignore UI oriented
242 * configuration variables such as decoration.
244 if (!decoration_given)
245 decoration_style = 0;
246 if (!rev->abbrev_commit_given)
247 rev->abbrev_commit = 0;
250 if (rev->commit_format == CMIT_FMT_USERFORMAT) {
251 if (!w.decorate) {
253 * Disable decoration loading if the format will not
254 * show them anyway.
256 decoration_style = 0;
257 } else if (!decoration_style) {
259 * If we are going to show them, make sure we do load
260 * them here, but taking care not to override a
261 * specific style set by config or --decorate.
263 decoration_style = DECORATE_SHORT_REFS;
267 if (decoration_style || rev->simplify_by_decoration) {
268 const struct string_list *config_exclude =
269 repo_config_get_value_multi(the_repository,
270 "log.excludeDecoration");
272 if (config_exclude) {
273 struct string_list_item *item;
274 for_each_string_list_item(item, config_exclude)
275 string_list_append(&decorate_refs_exclude_config,
276 item->string);
279 if (decoration_style)
280 rev->show_decorations = 1;
282 load_ref_decorations(&decoration_filter, decoration_style);
285 if (rev->line_level_traverse)
286 line_log_init(rev, line_cb.prefix, &line_cb.args);
288 setup_pager();
291 static void cmd_log_init(int argc, const char **argv, const char *prefix,
292 struct rev_info *rev, struct setup_revision_opt *opt)
294 cmd_log_init_defaults(rev);
295 cmd_log_init_finish(argc, argv, prefix, rev, opt);
298 static int cmd_log_deinit(int ret, struct rev_info *rev)
300 release_revisions(rev);
301 return ret;
305 * This gives a rough estimate for how many commits we
306 * will print out in the list.
308 static int estimate_commit_count(struct commit_list *list)
310 int n = 0;
312 while (list) {
313 struct commit *commit = list->item;
314 unsigned int flags = commit->object.flags;
315 list = list->next;
316 if (!(flags & (TREESAME | UNINTERESTING)))
317 n++;
319 return n;
322 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
324 if (rev->shown_one) {
325 rev->shown_one = 0;
326 if (rev->commit_format != CMIT_FMT_ONELINE)
327 putchar(rev->diffopt.line_termination);
329 fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
332 static struct itimerval early_output_timer;
334 static void log_show_early(struct rev_info *revs, struct commit_list *list)
336 int i = revs->early_output;
337 int show_header = 1;
338 int no_free = revs->diffopt.no_free;
340 revs->diffopt.no_free = 0;
341 sort_in_topological_order(&list, revs->sort_order);
342 while (list && i) {
343 struct commit *commit = list->item;
344 switch (simplify_commit(revs, commit)) {
345 case commit_show:
346 if (show_header) {
347 int n = estimate_commit_count(list);
348 show_early_header(revs, "incomplete", n);
349 show_header = 0;
351 log_tree_commit(revs, commit);
352 i--;
353 break;
354 case commit_ignore:
355 break;
356 case commit_error:
357 revs->diffopt.no_free = no_free;
358 diff_free(&revs->diffopt);
359 return;
361 list = list->next;
364 /* Did we already get enough commits for the early output? */
365 if (!i) {
366 revs->diffopt.no_free = 0;
367 diff_free(&revs->diffopt);
368 return;
372 * ..if no, then repeat it twice a second until we
373 * do.
375 * NOTE! We don't use "it_interval", because if the
376 * reader isn't listening, we want our output to be
377 * throttled by the writing, and not have the timer
378 * trigger every second even if we're blocked on a
379 * reader!
381 early_output_timer.it_value.tv_sec = 0;
382 early_output_timer.it_value.tv_usec = 500000;
383 setitimer(ITIMER_REAL, &early_output_timer, NULL);
386 static void early_output(int signal)
388 show_early_output = log_show_early;
391 static void setup_early_output(void)
393 struct sigaction sa;
396 * Set up the signal handler, minimally intrusively:
397 * we only set a single volatile integer word (not
398 * using sigatomic_t - trying to avoid unnecessary
399 * system dependencies and headers), and using
400 * SA_RESTART.
402 memset(&sa, 0, sizeof(sa));
403 sa.sa_handler = early_output;
404 sigemptyset(&sa.sa_mask);
405 sa.sa_flags = SA_RESTART;
406 sigaction(SIGALRM, &sa, NULL);
409 * If we can get the whole output in less than a
410 * tenth of a second, don't even bother doing the
411 * early-output thing..
413 * This is a one-time-only trigger.
415 early_output_timer.it_value.tv_sec = 0;
416 early_output_timer.it_value.tv_usec = 100000;
417 setitimer(ITIMER_REAL, &early_output_timer, NULL);
420 static void finish_early_output(struct rev_info *rev)
422 int n = estimate_commit_count(rev->commits);
423 signal(SIGALRM, SIG_IGN);
424 show_early_header(rev, "done", n);
427 static int cmd_log_walk_no_free(struct rev_info *rev)
429 struct commit *commit;
430 int saved_nrl = 0;
431 int saved_dcctc = 0;
433 if (rev->remerge_diff) {
434 rev->remerge_objdir = tmp_objdir_create("remerge-diff");
435 if (!rev->remerge_objdir)
436 die(_("unable to create temporary object directory"));
437 tmp_objdir_replace_primary_odb(rev->remerge_objdir, 1);
440 if (rev->early_output)
441 setup_early_output();
443 if (prepare_revision_walk(rev))
444 die(_("revision walk setup failed"));
446 if (rev->early_output)
447 finish_early_output(rev);
450 * For --check and --exit-code, the exit code is based on CHECK_FAILED
451 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
452 * retain that state information if replacing rev->diffopt in this loop
454 while ((commit = get_revision(rev)) != NULL) {
455 if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
457 * We decremented max_count in get_revision,
458 * but we didn't actually show the commit.
460 rev->max_count++;
461 if (!rev->reflog_info) {
463 * We may show a given commit multiple times when
464 * walking the reflogs.
466 free_commit_buffer(the_repository->parsed_objects,
467 commit);
468 free_commit_list(commit->parents);
469 commit->parents = NULL;
471 if (saved_nrl < rev->diffopt.needed_rename_limit)
472 saved_nrl = rev->diffopt.needed_rename_limit;
473 if (rev->diffopt.degraded_cc_to_c)
474 saved_dcctc = 1;
476 rev->diffopt.degraded_cc_to_c = saved_dcctc;
477 rev->diffopt.needed_rename_limit = saved_nrl;
479 if (rev->remerge_diff) {
480 tmp_objdir_destroy(rev->remerge_objdir);
481 rev->remerge_objdir = NULL;
484 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
485 rev->diffopt.flags.check_failed) {
486 return 02;
488 return diff_result_code(&rev->diffopt, 0);
491 static int cmd_log_walk(struct rev_info *rev)
493 int retval;
495 rev->diffopt.no_free = 1;
496 retval = cmd_log_walk_no_free(rev);
497 rev->diffopt.no_free = 0;
498 diff_free(&rev->diffopt);
499 return retval;
502 static int git_log_config(const char *var, const char *value, void *cb)
504 const char *slot_name;
506 if (!strcmp(var, "format.pretty"))
507 return git_config_string(&fmt_pretty, var, value);
508 if (!strcmp(var, "format.subjectprefix"))
509 return git_config_string(&fmt_patch_subject_prefix, var, value);
510 if (!strcmp(var, "format.filenamemaxlength")) {
511 fmt_patch_name_max = git_config_int(var, value);
512 return 0;
514 if (!strcmp(var, "format.encodeemailheaders")) {
515 default_encode_email_headers = git_config_bool(var, value);
516 return 0;
518 if (!strcmp(var, "log.abbrevcommit")) {
519 default_abbrev_commit = git_config_bool(var, value);
520 return 0;
522 if (!strcmp(var, "log.date"))
523 return git_config_string(&default_date_mode, var, value);
524 if (!strcmp(var, "log.decorate")) {
525 decoration_style = parse_decoration_style(value);
526 if (decoration_style < 0)
527 decoration_style = 0; /* maybe warn? */
528 return 0;
530 if (!strcmp(var, "log.diffmerges"))
531 return diff_merges_config(value);
532 if (!strcmp(var, "log.showroot")) {
533 default_show_root = git_config_bool(var, value);
534 return 0;
536 if (!strcmp(var, "log.follow")) {
537 default_follow = git_config_bool(var, value);
538 return 0;
540 if (skip_prefix(var, "color.decorate.", &slot_name))
541 return parse_decorate_color_config(var, slot_name, value);
542 if (!strcmp(var, "log.mailmap")) {
543 use_mailmap_config = git_config_bool(var, value);
544 return 0;
546 if (!strcmp(var, "log.showsignature")) {
547 default_show_signature = git_config_bool(var, value);
548 return 0;
551 if (git_gpg_config(var, value, cb) < 0)
552 return -1;
553 return git_diff_ui_config(var, value, cb);
556 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
558 struct rev_info rev;
559 struct setup_revision_opt opt;
561 init_log_defaults();
562 git_config(git_log_config, NULL);
564 repo_init_revisions(the_repository, &rev, prefix);
565 git_config(grep_config, &rev.grep_filter);
567 rev.diff = 1;
568 rev.simplify_history = 0;
569 memset(&opt, 0, sizeof(opt));
570 opt.def = "HEAD";
571 opt.revarg_opt = REVARG_COMMITTISH;
572 cmd_log_init(argc, argv, prefix, &rev, &opt);
573 if (!rev.diffopt.output_format)
574 rev.diffopt.output_format = DIFF_FORMAT_RAW;
575 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
578 static void show_tagger(const char *buf, struct rev_info *rev)
580 struct strbuf out = STRBUF_INIT;
581 struct pretty_print_context pp = {0};
583 pp.fmt = rev->commit_format;
584 pp.date_mode = rev->date_mode;
585 pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
586 fprintf(rev->diffopt.file, "%s", out.buf);
587 strbuf_release(&out);
590 static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
592 struct object_id oidc;
593 struct object_context obj_context;
594 char *buf;
595 unsigned long size;
597 fflush(rev->diffopt.file);
598 if (!rev->diffopt.flags.textconv_set_via_cmdline ||
599 !rev->diffopt.flags.allow_textconv)
600 return stream_blob_to_fd(1, oid, NULL, 0);
602 if (get_oid_with_context(the_repository, obj_name,
603 GET_OID_RECORD_PATH,
604 &oidc, &obj_context))
605 die(_("not a valid object name %s"), obj_name);
606 if (!obj_context.path ||
607 !textconv_object(the_repository, obj_context.path,
608 obj_context.mode, &oidc, 1, &buf, &size)) {
609 free(obj_context.path);
610 return stream_blob_to_fd(1, oid, NULL, 0);
613 if (!buf)
614 die(_("git show %s: bad file"), obj_name);
616 write_or_die(1, buf, size);
617 free(obj_context.path);
618 return 0;
621 static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
623 unsigned long size;
624 enum object_type type;
625 char *buf = read_object_file(oid, &type, &size);
626 int offset = 0;
628 if (!buf)
629 return error(_("could not read object %s"), oid_to_hex(oid));
631 assert(type == OBJ_TAG);
632 while (offset < size && buf[offset] != '\n') {
633 int new_offset = offset + 1;
634 const char *ident;
635 while (new_offset < size && buf[new_offset++] != '\n')
636 ; /* do nothing */
637 if (skip_prefix(buf + offset, "tagger ", &ident))
638 show_tagger(ident, rev);
639 offset = new_offset;
642 if (offset < size)
643 fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
644 free(buf);
645 return 0;
648 static int show_tree_object(const struct object_id *oid,
649 struct strbuf *base,
650 const char *pathname, unsigned mode, void *context)
652 FILE *file = context;
653 fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
654 return 0;
657 static void show_setup_revisions_tweak(struct rev_info *rev,
658 struct setup_revision_opt *opt)
660 if (rev->first_parent_only)
661 diff_merges_default_to_first_parent(rev);
662 else
663 diff_merges_default_to_dense_combined(rev);
664 if (!rev->diffopt.output_format)
665 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
668 int cmd_show(int argc, const char **argv, const char *prefix)
670 struct rev_info rev;
671 unsigned int i;
672 struct setup_revision_opt opt;
673 struct pathspec match_all;
674 int ret = 0;
676 init_log_defaults();
677 git_config(git_log_config, NULL);
679 if (the_repository->gitdir) {
680 prepare_repo_settings(the_repository);
681 the_repository->settings.command_requires_full_index = 0;
684 memset(&match_all, 0, sizeof(match_all));
685 repo_init_revisions(the_repository, &rev, prefix);
686 git_config(grep_config, &rev.grep_filter);
688 rev.diff = 1;
689 rev.always_show_header = 1;
690 rev.no_walk = 1;
691 rev.diffopt.stat_width = -1; /* Scale to real terminal size */
693 memset(&opt, 0, sizeof(opt));
694 opt.def = "HEAD";
695 opt.tweak = show_setup_revisions_tweak;
696 cmd_log_init(argc, argv, prefix, &rev, &opt);
698 if (!rev.no_walk)
699 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
701 rev.diffopt.no_free = 1;
702 for (i = 0; i < rev.pending.nr && !ret; i++) {
703 struct object *o = rev.pending.objects[i].item;
704 const char *name = rev.pending.objects[i].name;
705 switch (o->type) {
706 case OBJ_BLOB:
707 ret = show_blob_object(&o->oid, &rev, name);
708 break;
709 case OBJ_TAG: {
710 struct tag *t = (struct tag *)o;
711 struct object_id *oid = get_tagged_oid(t);
713 if (rev.shown_one)
714 putchar('\n');
715 fprintf(rev.diffopt.file, "%stag %s%s\n",
716 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
717 t->tag,
718 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
719 ret = show_tag_object(&o->oid, &rev);
720 rev.shown_one = 1;
721 if (ret)
722 break;
723 o = parse_object(the_repository, oid);
724 if (!o)
725 ret = error(_("could not read object %s"),
726 oid_to_hex(oid));
727 rev.pending.objects[i].item = o;
728 i--;
729 break;
731 case OBJ_TREE:
732 if (rev.shown_one)
733 putchar('\n');
734 fprintf(rev.diffopt.file, "%stree %s%s\n\n",
735 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
736 name,
737 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
738 read_tree(the_repository, (struct tree *)o,
739 &match_all, show_tree_object,
740 rev.diffopt.file);
741 rev.shown_one = 1;
742 break;
743 case OBJ_COMMIT:
745 struct object_array old;
746 struct object_array blank = OBJECT_ARRAY_INIT;
748 memcpy(&old, &rev.pending, sizeof(old));
749 memcpy(&rev.pending, &blank, sizeof(rev.pending));
751 add_object_array(o, name, &rev.pending);
752 ret = cmd_log_walk_no_free(&rev);
755 * No need for
756 * object_array_clear(&pending). It was
757 * cleared already in prepare_revision_walk()
759 memcpy(&rev.pending, &old, sizeof(rev.pending));
760 break;
762 default:
763 ret = error(_("unknown type: %d"), o->type);
767 rev.diffopt.no_free = 0;
768 diff_free(&rev.diffopt);
770 return cmd_log_deinit(ret, &rev);
774 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
776 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
778 struct rev_info rev;
779 struct setup_revision_opt opt;
781 init_log_defaults();
782 git_config(git_log_config, NULL);
784 repo_init_revisions(the_repository, &rev, prefix);
785 init_reflog_walk(&rev.reflog_info);
786 git_config(grep_config, &rev.grep_filter);
788 rev.verbose_header = 1;
789 memset(&opt, 0, sizeof(opt));
790 opt.def = "HEAD";
791 cmd_log_init_defaults(&rev);
792 rev.abbrev_commit = 1;
793 rev.commit_format = CMIT_FMT_ONELINE;
794 rev.use_terminator = 1;
795 rev.always_show_header = 1;
796 cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
798 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
801 static void log_setup_revisions_tweak(struct rev_info *rev,
802 struct setup_revision_opt *opt)
804 if (rev->diffopt.flags.default_follow_renames &&
805 rev->prune_data.nr == 1)
806 rev->diffopt.flags.follow_renames = 1;
808 if (rev->first_parent_only)
809 diff_merges_default_to_first_parent(rev);
812 int cmd_log(int argc, const char **argv, const char *prefix)
814 struct rev_info rev;
815 struct setup_revision_opt opt;
817 init_log_defaults();
818 git_config(git_log_config, NULL);
820 repo_init_revisions(the_repository, &rev, prefix);
821 git_config(grep_config, &rev.grep_filter);
823 rev.always_show_header = 1;
824 memset(&opt, 0, sizeof(opt));
825 opt.def = "HEAD";
826 opt.revarg_opt = REVARG_COMMITTISH;
827 opt.tweak = log_setup_revisions_tweak;
828 cmd_log_init(argc, argv, prefix, &rev, &opt);
829 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
832 /* format-patch */
834 static const char *fmt_patch_suffix = ".patch";
835 static int numbered = 0;
836 static int auto_number = 1;
838 static char *default_attach = NULL;
840 static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
841 static struct string_list extra_to = STRING_LIST_INIT_NODUP;
842 static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
844 static void add_header(const char *value)
846 struct string_list_item *item;
847 int len = strlen(value);
848 while (len && value[len - 1] == '\n')
849 len--;
851 if (!strncasecmp(value, "to: ", 4)) {
852 item = string_list_append(&extra_to, value + 4);
853 len -= 4;
854 } else if (!strncasecmp(value, "cc: ", 4)) {
855 item = string_list_append(&extra_cc, value + 4);
856 len -= 4;
857 } else {
858 item = string_list_append(&extra_hdr, value);
861 item->string[len] = '\0';
864 enum cover_setting {
865 COVER_UNSET,
866 COVER_OFF,
867 COVER_ON,
868 COVER_AUTO
871 enum thread_level {
872 THREAD_UNSET,
873 THREAD_SHALLOW,
874 THREAD_DEEP
877 enum cover_from_description {
878 COVER_FROM_NONE,
879 COVER_FROM_MESSAGE,
880 COVER_FROM_SUBJECT,
881 COVER_FROM_AUTO
884 enum auto_base_setting {
885 AUTO_BASE_NEVER,
886 AUTO_BASE_ALWAYS,
887 AUTO_BASE_WHEN_ABLE
890 static enum thread_level thread;
891 static int do_signoff;
892 static enum auto_base_setting auto_base;
893 static char *from;
894 static const char *signature = git_version_string;
895 static const char *signature_file;
896 static enum cover_setting config_cover_letter;
897 static const char *config_output_directory;
898 static enum cover_from_description cover_from_description_mode = COVER_FROM_MESSAGE;
899 static int show_notes;
900 static struct display_notes_opt notes_opt;
902 static enum cover_from_description parse_cover_from_description(const char *arg)
904 if (!arg || !strcmp(arg, "default"))
905 return COVER_FROM_MESSAGE;
906 else if (!strcmp(arg, "none"))
907 return COVER_FROM_NONE;
908 else if (!strcmp(arg, "message"))
909 return COVER_FROM_MESSAGE;
910 else if (!strcmp(arg, "subject"))
911 return COVER_FROM_SUBJECT;
912 else if (!strcmp(arg, "auto"))
913 return COVER_FROM_AUTO;
914 else
915 die(_("%s: invalid cover from description mode"), arg);
918 static int git_format_config(const char *var, const char *value, void *cb)
920 if (!strcmp(var, "format.headers")) {
921 if (!value)
922 die(_("format.headers without value"));
923 add_header(value);
924 return 0;
926 if (!strcmp(var, "format.suffix"))
927 return git_config_string(&fmt_patch_suffix, var, value);
928 if (!strcmp(var, "format.to")) {
929 if (!value)
930 return config_error_nonbool(var);
931 string_list_append(&extra_to, value);
932 return 0;
934 if (!strcmp(var, "format.cc")) {
935 if (!value)
936 return config_error_nonbool(var);
937 string_list_append(&extra_cc, value);
938 return 0;
940 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
941 !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
942 return 0;
944 if (!strcmp(var, "format.numbered")) {
945 if (value && !strcasecmp(value, "auto")) {
946 auto_number = 1;
947 return 0;
949 numbered = git_config_bool(var, value);
950 auto_number = auto_number && numbered;
951 return 0;
953 if (!strcmp(var, "format.attach")) {
954 if (value && *value)
955 default_attach = xstrdup(value);
956 else
957 default_attach = xstrdup(git_version_string);
958 return 0;
960 if (!strcmp(var, "format.thread")) {
961 if (value && !strcasecmp(value, "deep")) {
962 thread = THREAD_DEEP;
963 return 0;
965 if (value && !strcasecmp(value, "shallow")) {
966 thread = THREAD_SHALLOW;
967 return 0;
969 thread = git_config_bool(var, value) ? THREAD_SHALLOW : THREAD_UNSET;
970 return 0;
972 if (!strcmp(var, "format.signoff")) {
973 do_signoff = git_config_bool(var, value);
974 return 0;
976 if (!strcmp(var, "format.signature"))
977 return git_config_string(&signature, var, value);
978 if (!strcmp(var, "format.signaturefile"))
979 return git_config_pathname(&signature_file, var, value);
980 if (!strcmp(var, "format.coverletter")) {
981 if (value && !strcasecmp(value, "auto")) {
982 config_cover_letter = COVER_AUTO;
983 return 0;
985 config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
986 return 0;
988 if (!strcmp(var, "format.outputdirectory"))
989 return git_config_string(&config_output_directory, var, value);
990 if (!strcmp(var, "format.useautobase")) {
991 if (value && !strcasecmp(value, "whenAble")) {
992 auto_base = AUTO_BASE_WHEN_ABLE;
993 return 0;
995 auto_base = git_config_bool(var, value) ? AUTO_BASE_ALWAYS : AUTO_BASE_NEVER;
996 return 0;
998 if (!strcmp(var, "format.from")) {
999 int b = git_parse_maybe_bool(value);
1000 free(from);
1001 if (b < 0)
1002 from = xstrdup(value);
1003 else if (b)
1004 from = xstrdup(git_committer_info(IDENT_NO_DATE));
1005 else
1006 from = NULL;
1007 return 0;
1009 if (!strcmp(var, "format.notes")) {
1010 int b = git_parse_maybe_bool(value);
1011 if (b < 0)
1012 enable_ref_display_notes(&notes_opt, &show_notes, value);
1013 else if (b)
1014 enable_default_display_notes(&notes_opt, &show_notes);
1015 else
1016 disable_display_notes(&notes_opt, &show_notes);
1017 return 0;
1019 if (!strcmp(var, "format.coverfromdescription")) {
1020 cover_from_description_mode = parse_cover_from_description(value);
1021 return 0;
1024 return git_log_config(var, value, cb);
1027 static const char *output_directory = NULL;
1028 static int outdir_offset;
1030 static int open_next_file(struct commit *commit, const char *subject,
1031 struct rev_info *rev, int quiet)
1033 struct strbuf filename = STRBUF_INIT;
1035 if (output_directory) {
1036 strbuf_addstr(&filename, output_directory);
1037 strbuf_complete(&filename, '/');
1040 if (rev->numbered_files)
1041 strbuf_addf(&filename, "%d", rev->nr);
1042 else if (commit)
1043 fmt_output_commit(&filename, commit, rev);
1044 else
1045 fmt_output_subject(&filename, subject, rev);
1047 if (!quiet)
1048 printf("%s\n", filename.buf + outdir_offset);
1050 if (!(rev->diffopt.file = fopen(filename.buf, "w"))) {
1051 error_errno(_("cannot open patch file %s"), filename.buf);
1052 strbuf_release(&filename);
1053 return -1;
1056 strbuf_release(&filename);
1057 return 0;
1060 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
1062 struct rev_info check_rev;
1063 struct commit *commit, *c1, *c2;
1064 struct object *o1, *o2;
1065 unsigned flags1, flags2;
1067 if (rev->pending.nr != 2)
1068 die(_("need exactly one range"));
1070 o1 = rev->pending.objects[0].item;
1071 o2 = rev->pending.objects[1].item;
1072 flags1 = o1->flags;
1073 flags2 = o2->flags;
1074 c1 = lookup_commit_reference(the_repository, &o1->oid);
1075 c2 = lookup_commit_reference(the_repository, &o2->oid);
1077 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
1078 die(_("not a range"));
1080 init_patch_ids(the_repository, ids);
1082 /* given a range a..b get all patch ids for b..a */
1083 repo_init_revisions(the_repository, &check_rev, rev->prefix);
1084 check_rev.max_parents = 1;
1085 o1->flags ^= UNINTERESTING;
1086 o2->flags ^= UNINTERESTING;
1087 add_pending_object(&check_rev, o1, "o1");
1088 add_pending_object(&check_rev, o2, "o2");
1089 if (prepare_revision_walk(&check_rev))
1090 die(_("revision walk setup failed"));
1092 while ((commit = get_revision(&check_rev)) != NULL) {
1093 add_commit_patch_id(commit, ids);
1096 /* reset for next revision walk */
1097 clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
1098 clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
1099 o1->flags = flags1;
1100 o2->flags = flags2;
1103 static void gen_message_id(struct rev_info *info, char *base)
1105 struct strbuf buf = STRBUF_INIT;
1106 strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
1107 (timestamp_t) time(NULL),
1108 git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
1109 info->message_id = strbuf_detach(&buf, NULL);
1112 static void print_signature(FILE *file)
1114 if (!signature || !*signature)
1115 return;
1117 fprintf(file, "-- \n%s", signature);
1118 if (signature[strlen(signature)-1] != '\n')
1119 putc('\n', file);
1120 putc('\n', file);
1123 static char *find_branch_name(struct rev_info *rev)
1125 int i, positive = -1;
1126 struct object_id branch_oid;
1127 const struct object_id *tip_oid;
1128 const char *ref, *v;
1129 char *full_ref, *branch = NULL;
1131 for (i = 0; i < rev->cmdline.nr; i++) {
1132 if (rev->cmdline.rev[i].flags & UNINTERESTING)
1133 continue;
1134 if (positive < 0)
1135 positive = i;
1136 else
1137 return NULL;
1139 if (positive < 0)
1140 return NULL;
1141 ref = rev->cmdline.rev[positive].name;
1142 tip_oid = &rev->cmdline.rev[positive].item->oid;
1143 if (dwim_ref(ref, strlen(ref), &branch_oid, &full_ref, 0) &&
1144 skip_prefix(full_ref, "refs/heads/", &v) &&
1145 oideq(tip_oid, &branch_oid))
1146 branch = xstrdup(v);
1147 free(full_ref);
1148 return branch;
1151 static void show_diffstat(struct rev_info *rev,
1152 struct commit *origin, struct commit *head)
1154 struct diff_options opts;
1156 memcpy(&opts, &rev->diffopt, sizeof(opts));
1157 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1158 diff_setup_done(&opts);
1160 diff_tree_oid(get_commit_tree_oid(origin),
1161 get_commit_tree_oid(head),
1162 "", &opts);
1163 diffcore_std(&opts);
1164 diff_flush(&opts);
1166 fprintf(rev->diffopt.file, "\n");
1169 static void prepare_cover_text(struct pretty_print_context *pp,
1170 const char *branch_name,
1171 struct strbuf *sb,
1172 const char *encoding,
1173 int need_8bit_cte)
1175 const char *subject = "*** SUBJECT HERE ***";
1176 const char *body = "*** BLURB HERE ***";
1177 struct strbuf description_sb = STRBUF_INIT;
1178 struct strbuf subject_sb = STRBUF_INIT;
1180 if (cover_from_description_mode == COVER_FROM_NONE)
1181 goto do_pp;
1183 if (branch_name && *branch_name)
1184 read_branch_desc(&description_sb, branch_name);
1185 if (!description_sb.len)
1186 goto do_pp;
1188 if (cover_from_description_mode == COVER_FROM_SUBJECT ||
1189 cover_from_description_mode == COVER_FROM_AUTO)
1190 body = format_subject(&subject_sb, description_sb.buf, " ");
1192 if (cover_from_description_mode == COVER_FROM_MESSAGE ||
1193 (cover_from_description_mode == COVER_FROM_AUTO &&
1194 subject_sb.len > COVER_FROM_AUTO_MAX_SUBJECT_LEN))
1195 body = description_sb.buf;
1196 else
1197 subject = subject_sb.buf;
1199 do_pp:
1200 pp_title_line(pp, &subject, sb, encoding, need_8bit_cte);
1201 pp_remainder(pp, &body, sb, 0);
1203 strbuf_release(&description_sb);
1204 strbuf_release(&subject_sb);
1207 static int get_notes_refs(struct string_list_item *item, void *arg)
1209 strvec_pushf(arg, "--notes=%s", item->string);
1210 return 0;
1213 static void get_notes_args(struct strvec *arg, struct rev_info *rev)
1215 if (!rev->show_notes) {
1216 strvec_push(arg, "--no-notes");
1217 } else if (rev->notes_opt.use_default_notes > 0 ||
1218 (rev->notes_opt.use_default_notes == -1 &&
1219 !rev->notes_opt.extra_notes_refs.nr)) {
1220 strvec_push(arg, "--notes");
1221 } else {
1222 for_each_string_list(&rev->notes_opt.extra_notes_refs, get_notes_refs, arg);
1226 static void make_cover_letter(struct rev_info *rev, int use_separate_file,
1227 struct commit *origin,
1228 int nr, struct commit **list,
1229 const char *branch_name,
1230 int quiet)
1232 const char *committer;
1233 struct shortlog log;
1234 struct strbuf sb = STRBUF_INIT;
1235 int i;
1236 const char *encoding = "UTF-8";
1237 int need_8bit_cte = 0;
1238 struct pretty_print_context pp = {0};
1239 struct commit *head = list[0];
1241 if (!cmit_fmt_is_mail(rev->commit_format))
1242 die(_("cover letter needs email format"));
1244 committer = git_committer_info(0);
1246 if (use_separate_file &&
1247 open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1248 die(_("failed to create cover-letter file"));
1250 log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1252 for (i = 0; !need_8bit_cte && i < nr; i++) {
1253 const char *buf = get_commit_buffer(list[i], NULL);
1254 if (has_non_ascii(buf))
1255 need_8bit_cte = 1;
1256 unuse_commit_buffer(list[i], buf);
1259 if (!branch_name)
1260 branch_name = find_branch_name(rev);
1262 pp.fmt = CMIT_FMT_EMAIL;
1263 pp.date_mode.type = DATE_RFC2822;
1264 pp.rev = rev;
1265 pp.print_email_subject = 1;
1266 pp_user_info(&pp, NULL, &sb, committer, encoding);
1267 prepare_cover_text(&pp, branch_name, &sb, encoding, need_8bit_cte);
1268 fprintf(rev->diffopt.file, "%s\n", sb.buf);
1270 strbuf_release(&sb);
1272 shortlog_init(&log);
1273 log.wrap_lines = 1;
1274 log.wrap = MAIL_DEFAULT_WRAP;
1275 log.in1 = 2;
1276 log.in2 = 4;
1277 log.file = rev->diffopt.file;
1278 log.groups = SHORTLOG_GROUP_AUTHOR;
1279 for (i = 0; i < nr; i++)
1280 shortlog_add_commit(&log, list[i]);
1282 shortlog_output(&log);
1284 /* We can only do diffstat with a unique reference point */
1285 if (origin)
1286 show_diffstat(rev, origin, head);
1288 if (rev->idiff_oid1) {
1289 fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1290 show_interdiff(rev->idiff_oid1, rev->idiff_oid2, 0,
1291 &rev->diffopt);
1294 if (rev->rdiff1) {
1296 * Pass minimum required diff-options to range-diff; others
1297 * can be added later if deemed desirable.
1299 struct diff_options opts;
1300 struct strvec other_arg = STRVEC_INIT;
1301 struct range_diff_options range_diff_opts = {
1302 .creation_factor = rev->creation_factor,
1303 .dual_color = 1,
1304 .diffopt = &opts,
1305 .other_arg = &other_arg
1308 diff_setup(&opts);
1309 opts.file = rev->diffopt.file;
1310 opts.use_color = rev->diffopt.use_color;
1311 diff_setup_done(&opts);
1312 fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1313 get_notes_args(&other_arg, rev);
1314 show_range_diff(rev->rdiff1, rev->rdiff2, &range_diff_opts);
1315 strvec_clear(&other_arg);
1319 static const char *clean_message_id(const char *msg_id)
1321 char ch;
1322 const char *a, *z, *m;
1324 m = msg_id;
1325 while ((ch = *m) && (isspace(ch) || (ch == '<')))
1326 m++;
1327 a = m;
1328 z = NULL;
1329 while ((ch = *m)) {
1330 if (!isspace(ch) && (ch != '>'))
1331 z = m;
1332 m++;
1334 if (!z)
1335 die(_("insane in-reply-to: %s"), msg_id);
1336 if (++z == m)
1337 return a;
1338 return xmemdupz(a, z - a);
1341 static const char *set_outdir(const char *prefix, const char *output_directory)
1343 if (output_directory && is_absolute_path(output_directory))
1344 return output_directory;
1346 if (!prefix || !*prefix) {
1347 if (output_directory)
1348 return output_directory;
1349 /* The user did not explicitly ask for "./" */
1350 outdir_offset = 2;
1351 return "./";
1354 outdir_offset = strlen(prefix);
1355 if (!output_directory)
1356 return prefix;
1358 return prefix_filename(prefix, output_directory);
1361 static const char * const builtin_format_patch_usage[] = {
1362 N_("git format-patch [<options>] [<since> | <revision-range>]"),
1363 NULL
1366 static int keep_subject = 0;
1368 static int keep_callback(const struct option *opt, const char *arg, int unset)
1370 BUG_ON_OPT_NEG(unset);
1371 BUG_ON_OPT_ARG(arg);
1372 ((struct rev_info *)opt->value)->total = -1;
1373 keep_subject = 1;
1374 return 0;
1377 static int subject_prefix = 0;
1379 static int subject_prefix_callback(const struct option *opt, const char *arg,
1380 int unset)
1382 BUG_ON_OPT_NEG(unset);
1383 subject_prefix = 1;
1384 ((struct rev_info *)opt->value)->subject_prefix = arg;
1385 return 0;
1388 static int rfc_callback(const struct option *opt, const char *arg, int unset)
1390 BUG_ON_OPT_NEG(unset);
1391 BUG_ON_OPT_ARG(arg);
1392 return subject_prefix_callback(opt, "RFC PATCH", unset);
1395 static int numbered_cmdline_opt = 0;
1397 static int numbered_callback(const struct option *opt, const char *arg,
1398 int unset)
1400 BUG_ON_OPT_ARG(arg);
1401 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1402 if (unset)
1403 auto_number = 0;
1404 return 0;
1407 static int no_numbered_callback(const struct option *opt, const char *arg,
1408 int unset)
1410 BUG_ON_OPT_NEG(unset);
1411 return numbered_callback(opt, arg, 1);
1414 static int output_directory_callback(const struct option *opt, const char *arg,
1415 int unset)
1417 const char **dir = (const char **)opt->value;
1418 BUG_ON_OPT_NEG(unset);
1419 if (*dir)
1420 die(_("two output directories?"));
1421 *dir = arg;
1422 return 0;
1425 static int thread_callback(const struct option *opt, const char *arg, int unset)
1427 enum thread_level *thread = (enum thread_level *)opt->value;
1428 if (unset)
1429 *thread = THREAD_UNSET;
1430 else if (!arg || !strcmp(arg, "shallow"))
1431 *thread = THREAD_SHALLOW;
1432 else if (!strcmp(arg, "deep"))
1433 *thread = THREAD_DEEP;
1435 * Please update _git_formatpatch() in git-completion.bash
1436 * when you add new options.
1438 else
1439 return 1;
1440 return 0;
1443 static int attach_callback(const struct option *opt, const char *arg, int unset)
1445 struct rev_info *rev = (struct rev_info *)opt->value;
1446 if (unset)
1447 rev->mime_boundary = NULL;
1448 else if (arg)
1449 rev->mime_boundary = arg;
1450 else
1451 rev->mime_boundary = git_version_string;
1452 rev->no_inline = unset ? 0 : 1;
1453 return 0;
1456 static int inline_callback(const struct option *opt, const char *arg, int unset)
1458 struct rev_info *rev = (struct rev_info *)opt->value;
1459 if (unset)
1460 rev->mime_boundary = NULL;
1461 else if (arg)
1462 rev->mime_boundary = arg;
1463 else
1464 rev->mime_boundary = git_version_string;
1465 rev->no_inline = 0;
1466 return 0;
1469 static int header_callback(const struct option *opt, const char *arg, int unset)
1471 if (unset) {
1472 string_list_clear(&extra_hdr, 0);
1473 string_list_clear(&extra_to, 0);
1474 string_list_clear(&extra_cc, 0);
1475 } else {
1476 add_header(arg);
1478 return 0;
1481 static int to_callback(const struct option *opt, const char *arg, int unset)
1483 if (unset)
1484 string_list_clear(&extra_to, 0);
1485 else
1486 string_list_append(&extra_to, arg);
1487 return 0;
1490 static int cc_callback(const struct option *opt, const char *arg, int unset)
1492 if (unset)
1493 string_list_clear(&extra_cc, 0);
1494 else
1495 string_list_append(&extra_cc, arg);
1496 return 0;
1499 static int from_callback(const struct option *opt, const char *arg, int unset)
1501 char **from = opt->value;
1503 free(*from);
1505 if (unset)
1506 *from = NULL;
1507 else if (arg)
1508 *from = xstrdup(arg);
1509 else
1510 *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1511 return 0;
1514 static int base_callback(const struct option *opt, const char *arg, int unset)
1516 const char **base_commit = opt->value;
1518 if (unset) {
1519 auto_base = AUTO_BASE_NEVER;
1520 *base_commit = NULL;
1521 } else if (!strcmp(arg, "auto")) {
1522 auto_base = AUTO_BASE_ALWAYS;
1523 *base_commit = NULL;
1524 } else {
1525 auto_base = AUTO_BASE_NEVER;
1526 *base_commit = arg;
1528 return 0;
1531 struct base_tree_info {
1532 struct object_id base_commit;
1533 int nr_patch_id, alloc_patch_id;
1534 struct object_id *patch_id;
1537 static struct commit *get_base_commit(const char *base_commit,
1538 struct commit **list,
1539 int total)
1541 struct commit *base = NULL;
1542 struct commit **rev;
1543 int i = 0, rev_nr = 0, auto_select, die_on_failure;
1545 switch (auto_base) {
1546 case AUTO_BASE_NEVER:
1547 if (base_commit) {
1548 auto_select = 0;
1549 die_on_failure = 1;
1550 } else {
1551 /* no base information is requested */
1552 return NULL;
1554 break;
1555 case AUTO_BASE_ALWAYS:
1556 case AUTO_BASE_WHEN_ABLE:
1557 if (base_commit) {
1558 BUG("requested automatic base selection but a commit was provided");
1559 } else {
1560 auto_select = 1;
1561 die_on_failure = auto_base == AUTO_BASE_ALWAYS;
1563 break;
1564 default:
1565 BUG("unexpected automatic base selection method");
1568 if (!auto_select) {
1569 base = lookup_commit_reference_by_name(base_commit);
1570 if (!base)
1571 die(_("unknown commit %s"), base_commit);
1572 } else {
1573 struct branch *curr_branch = branch_get(NULL);
1574 const char *upstream = branch_get_upstream(curr_branch, NULL);
1575 if (upstream) {
1576 struct commit_list *base_list;
1577 struct commit *commit;
1578 struct object_id oid;
1580 if (get_oid(upstream, &oid)) {
1581 if (die_on_failure)
1582 die(_("failed to resolve '%s' as a valid ref"), upstream);
1583 else
1584 return NULL;
1586 commit = lookup_commit_or_die(&oid, "upstream base");
1587 base_list = get_merge_bases_many(commit, total, list);
1588 /* There should be one and only one merge base. */
1589 if (!base_list || base_list->next) {
1590 if (die_on_failure) {
1591 die(_("could not find exact merge base"));
1592 } else {
1593 free_commit_list(base_list);
1594 return NULL;
1597 base = base_list->item;
1598 free_commit_list(base_list);
1599 } else {
1600 if (die_on_failure)
1601 die(_("failed to get upstream, if you want to record base commit automatically,\n"
1602 "please use git branch --set-upstream-to to track a remote branch.\n"
1603 "Or you could specify base commit by --base=<base-commit-id> manually"));
1604 else
1605 return NULL;
1609 ALLOC_ARRAY(rev, total);
1610 for (i = 0; i < total; i++)
1611 rev[i] = list[i];
1613 rev_nr = total;
1615 * Get merge base through pair-wise computations
1616 * and store it in rev[0].
1618 while (rev_nr > 1) {
1619 for (i = 0; i < rev_nr / 2; i++) {
1620 struct commit_list *merge_base;
1621 merge_base = get_merge_bases(rev[2 * i], rev[2 * i + 1]);
1622 if (!merge_base || merge_base->next) {
1623 if (die_on_failure) {
1624 die(_("failed to find exact merge base"));
1625 } else {
1626 free(rev);
1627 return NULL;
1631 rev[i] = merge_base->item;
1634 if (rev_nr % 2)
1635 rev[i] = rev[2 * i];
1636 rev_nr = DIV_ROUND_UP(rev_nr, 2);
1639 if (!in_merge_bases(base, rev[0])) {
1640 if (die_on_failure) {
1641 die(_("base commit should be the ancestor of revision list"));
1642 } else {
1643 free(rev);
1644 return NULL;
1648 for (i = 0; i < total; i++) {
1649 if (base == list[i]) {
1650 if (die_on_failure) {
1651 die(_("base commit shouldn't be in revision list"));
1652 } else {
1653 free(rev);
1654 return NULL;
1659 free(rev);
1660 return base;
1663 define_commit_slab(commit_base, int);
1665 static void prepare_bases(struct base_tree_info *bases,
1666 struct commit *base,
1667 struct commit **list,
1668 int total)
1670 struct commit *commit;
1671 struct rev_info revs;
1672 struct diff_options diffopt;
1673 struct commit_base commit_base;
1674 int i;
1676 if (!base)
1677 return;
1679 init_commit_base(&commit_base);
1680 repo_diff_setup(the_repository, &diffopt);
1681 diffopt.flags.recursive = 1;
1682 diff_setup_done(&diffopt);
1684 oidcpy(&bases->base_commit, &base->object.oid);
1686 repo_init_revisions(the_repository, &revs, NULL);
1687 revs.max_parents = 1;
1688 revs.topo_order = 1;
1689 for (i = 0; i < total; i++) {
1690 list[i]->object.flags &= ~UNINTERESTING;
1691 add_pending_object(&revs, &list[i]->object, "rev_list");
1692 *commit_base_at(&commit_base, list[i]) = 1;
1694 base->object.flags |= UNINTERESTING;
1695 add_pending_object(&revs, &base->object, "base");
1697 if (prepare_revision_walk(&revs))
1698 die(_("revision walk setup failed"));
1700 * Traverse the commits list, get prerequisite patch ids
1701 * and stuff them in bases structure.
1703 while ((commit = get_revision(&revs)) != NULL) {
1704 struct object_id oid;
1705 struct object_id *patch_id;
1706 if (*commit_base_at(&commit_base, commit))
1707 continue;
1708 if (commit_patch_id(commit, &diffopt, &oid, 0, 1))
1709 die(_("cannot get patch id"));
1710 ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1711 patch_id = bases->patch_id + bases->nr_patch_id;
1712 oidcpy(patch_id, &oid);
1713 bases->nr_patch_id++;
1715 clear_commit_base(&commit_base);
1718 static void print_bases(struct base_tree_info *bases, FILE *file)
1720 int i;
1722 /* Only do this once, either for the cover or for the first one */
1723 if (is_null_oid(&bases->base_commit))
1724 return;
1726 /* Show the base commit */
1727 fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1729 /* Show the prerequisite patches */
1730 for (i = bases->nr_patch_id - 1; i >= 0; i--)
1731 fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1733 free(bases->patch_id);
1734 bases->nr_patch_id = 0;
1735 bases->alloc_patch_id = 0;
1736 oidclr(&bases->base_commit);
1739 static const char *diff_title(struct strbuf *sb,
1740 const char *reroll_count,
1741 const char *generic,
1742 const char *rerolled)
1744 int v;
1746 /* RFC may be v0, so allow -v1 to diff against v0 */
1747 if (reroll_count && !strtol_i(reroll_count, 10, &v) &&
1748 v >= 1)
1749 strbuf_addf(sb, rerolled, v - 1);
1750 else
1751 strbuf_addstr(sb, generic);
1752 return sb->buf;
1755 static void infer_range_diff_ranges(struct strbuf *r1,
1756 struct strbuf *r2,
1757 const char *prev,
1758 struct commit *origin,
1759 struct commit *head)
1761 const char *head_oid = oid_to_hex(&head->object.oid);
1762 int prev_is_range = is_range_diff_range(prev);
1764 if (prev_is_range)
1765 strbuf_addstr(r1, prev);
1766 else
1767 strbuf_addf(r1, "%s..%s", head_oid, prev);
1769 if (origin)
1770 strbuf_addf(r2, "%s..%s", oid_to_hex(&origin->object.oid), head_oid);
1771 else if (prev_is_range)
1772 die(_("failed to infer range-diff origin of current series"));
1773 else {
1774 warning(_("using '%s' as range-diff origin of current series"), prev);
1775 strbuf_addf(r2, "%s..%s", prev, head_oid);
1779 int cmd_format_patch(int argc, const char **argv, const char *prefix)
1781 struct commit *commit;
1782 struct commit **list = NULL;
1783 struct rev_info rev;
1784 char *to_free = NULL;
1785 struct setup_revision_opt s_r_opt;
1786 int nr = 0, total, i;
1787 int use_stdout = 0;
1788 int start_number = -1;
1789 int just_numbers = 0;
1790 int ignore_if_in_upstream = 0;
1791 int cover_letter = -1;
1792 int boundary_count = 0;
1793 int no_binary_diff = 0;
1794 int zero_commit = 0;
1795 struct commit *origin = NULL;
1796 const char *in_reply_to = NULL;
1797 struct patch_ids ids;
1798 struct strbuf buf = STRBUF_INIT;
1799 int use_patch_format = 0;
1800 int quiet = 0;
1801 const char *reroll_count = NULL;
1802 char *cover_from_description_arg = NULL;
1803 char *branch_name = NULL;
1804 char *base_commit = NULL;
1805 struct base_tree_info bases;
1806 struct commit *base;
1807 int show_progress = 0;
1808 struct progress *progress = NULL;
1809 struct oid_array idiff_prev = OID_ARRAY_INIT;
1810 struct strbuf idiff_title = STRBUF_INIT;
1811 const char *rdiff_prev = NULL;
1812 struct strbuf rdiff1 = STRBUF_INIT;
1813 struct strbuf rdiff2 = STRBUF_INIT;
1814 struct strbuf rdiff_title = STRBUF_INIT;
1815 int creation_factor = -1;
1817 const struct option builtin_format_patch_options[] = {
1818 OPT_CALLBACK_F('n', "numbered", &numbered, NULL,
1819 N_("use [PATCH n/m] even with a single patch"),
1820 PARSE_OPT_NOARG, numbered_callback),
1821 OPT_CALLBACK_F('N', "no-numbered", &numbered, NULL,
1822 N_("use [PATCH] even with multiple patches"),
1823 PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback),
1824 OPT_BOOL('s', "signoff", &do_signoff, N_("add a Signed-off-by trailer")),
1825 OPT_BOOL(0, "stdout", &use_stdout,
1826 N_("print patches to standard out")),
1827 OPT_BOOL(0, "cover-letter", &cover_letter,
1828 N_("generate a cover letter")),
1829 OPT_BOOL(0, "numbered-files", &just_numbers,
1830 N_("use simple number sequence for output file names")),
1831 OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
1832 N_("use <sfx> instead of '.patch'")),
1833 OPT_INTEGER(0, "start-number", &start_number,
1834 N_("start numbering patches at <n> instead of 1")),
1835 OPT_STRING('v', "reroll-count", &reroll_count, N_("reroll-count"),
1836 N_("mark the series as Nth re-roll")),
1837 OPT_INTEGER(0, "filename-max-length", &fmt_patch_name_max,
1838 N_("max length of output filename")),
1839 OPT_CALLBACK_F(0, "rfc", &rev, NULL,
1840 N_("use [RFC PATCH] instead of [PATCH]"),
1841 PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback),
1842 OPT_STRING(0, "cover-from-description", &cover_from_description_arg,
1843 N_("cover-from-description-mode"),
1844 N_("generate parts of a cover letter based on a branch's description")),
1845 OPT_CALLBACK_F(0, "subject-prefix", &rev, N_("prefix"),
1846 N_("use [<prefix>] instead of [PATCH]"),
1847 PARSE_OPT_NONEG, subject_prefix_callback),
1848 OPT_CALLBACK_F('o', "output-directory", &output_directory,
1849 N_("dir"), N_("store resulting files in <dir>"),
1850 PARSE_OPT_NONEG, output_directory_callback),
1851 OPT_CALLBACK_F('k', "keep-subject", &rev, NULL,
1852 N_("don't strip/add [PATCH]"),
1853 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback),
1854 OPT_BOOL(0, "no-binary", &no_binary_diff,
1855 N_("don't output binary diffs")),
1856 OPT_BOOL(0, "zero-commit", &zero_commit,
1857 N_("output all-zero hash in From header")),
1858 OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1859 N_("don't include a patch matching a commit upstream")),
1860 OPT_SET_INT_F('p', "no-stat", &use_patch_format,
1861 N_("show patch format instead of default (patch + stat)"),
1862 1, PARSE_OPT_NONEG),
1863 OPT_GROUP(N_("Messaging")),
1864 OPT_CALLBACK(0, "add-header", NULL, N_("header"),
1865 N_("add email header"), header_callback),
1866 OPT_CALLBACK(0, "to", NULL, N_("email"), N_("add To: header"), to_callback),
1867 OPT_CALLBACK(0, "cc", NULL, N_("email"), N_("add Cc: header"), cc_callback),
1868 OPT_CALLBACK_F(0, "from", &from, N_("ident"),
1869 N_("set From address to <ident> (or committer ident if absent)"),
1870 PARSE_OPT_OPTARG, from_callback),
1871 OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
1872 N_("make first mail a reply to <message-id>")),
1873 OPT_CALLBACK_F(0, "attach", &rev, N_("boundary"),
1874 N_("attach the patch"), PARSE_OPT_OPTARG,
1875 attach_callback),
1876 OPT_CALLBACK_F(0, "inline", &rev, N_("boundary"),
1877 N_("inline the patch"),
1878 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1879 inline_callback),
1880 OPT_CALLBACK_F(0, "thread", &thread, N_("style"),
1881 N_("enable message threading, styles: shallow, deep"),
1882 PARSE_OPT_OPTARG, thread_callback),
1883 OPT_STRING(0, "signature", &signature, N_("signature"),
1884 N_("add a signature")),
1885 OPT_CALLBACK_F(0, "base", &base_commit, N_("base-commit"),
1886 N_("add prerequisite tree info to the patch series"),
1887 0, base_callback),
1888 OPT_FILENAME(0, "signature-file", &signature_file,
1889 N_("add a signature from a file")),
1890 OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1891 OPT_BOOL(0, "progress", &show_progress,
1892 N_("show progress while generating patches")),
1893 OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
1894 N_("show changes against <rev> in cover letter or single patch"),
1895 parse_opt_object_name),
1896 OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
1897 N_("show changes against <refspec> in cover letter or single patch")),
1898 OPT_INTEGER(0, "creation-factor", &creation_factor,
1899 N_("percentage by which creation is weighted")),
1900 OPT_END()
1903 extra_hdr.strdup_strings = 1;
1904 extra_to.strdup_strings = 1;
1905 extra_cc.strdup_strings = 1;
1907 init_log_defaults();
1908 init_display_notes(&notes_opt);
1909 git_config(git_format_config, NULL);
1910 repo_init_revisions(the_repository, &rev, prefix);
1911 git_config(grep_config, &rev.grep_filter);
1913 rev.show_notes = show_notes;
1914 memcpy(&rev.notes_opt, &notes_opt, sizeof(notes_opt));
1915 rev.commit_format = CMIT_FMT_EMAIL;
1916 rev.encode_email_headers = default_encode_email_headers;
1917 rev.expand_tabs_in_log_default = 0;
1918 rev.verbose_header = 1;
1919 rev.diff = 1;
1920 rev.max_parents = 1;
1921 rev.diffopt.flags.recursive = 1;
1922 rev.diffopt.no_free = 1;
1923 rev.subject_prefix = fmt_patch_subject_prefix;
1924 memset(&s_r_opt, 0, sizeof(s_r_opt));
1925 s_r_opt.def = "HEAD";
1926 s_r_opt.revarg_opt = REVARG_COMMITTISH;
1928 if (default_attach) {
1929 rev.mime_boundary = default_attach;
1930 rev.no_inline = 1;
1934 * Parse the arguments before setup_revisions(), or something
1935 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1936 * possibly a valid SHA1.
1938 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1939 builtin_format_patch_usage,
1940 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1941 PARSE_OPT_KEEP_DASHDASH);
1943 /* Make sure "0000-$sub.patch" gives non-negative length for $sub */
1944 if (fmt_patch_name_max <= strlen("0000-") + strlen(fmt_patch_suffix))
1945 fmt_patch_name_max = strlen("0000-") + strlen(fmt_patch_suffix);
1947 if (cover_from_description_arg)
1948 cover_from_description_mode = parse_cover_from_description(cover_from_description_arg);
1950 if (reroll_count) {
1951 struct strbuf sprefix = STRBUF_INIT;
1953 strbuf_addf(&sprefix, "%s v%s",
1954 rev.subject_prefix, reroll_count);
1955 rev.reroll_count = reroll_count;
1956 rev.subject_prefix = strbuf_detach(&sprefix, NULL);
1959 for (i = 0; i < extra_hdr.nr; i++) {
1960 strbuf_addstr(&buf, extra_hdr.items[i].string);
1961 strbuf_addch(&buf, '\n');
1964 if (extra_to.nr)
1965 strbuf_addstr(&buf, "To: ");
1966 for (i = 0; i < extra_to.nr; i++) {
1967 if (i)
1968 strbuf_addstr(&buf, " ");
1969 strbuf_addstr(&buf, extra_to.items[i].string);
1970 if (i + 1 < extra_to.nr)
1971 strbuf_addch(&buf, ',');
1972 strbuf_addch(&buf, '\n');
1975 if (extra_cc.nr)
1976 strbuf_addstr(&buf, "Cc: ");
1977 for (i = 0; i < extra_cc.nr; i++) {
1978 if (i)
1979 strbuf_addstr(&buf, " ");
1980 strbuf_addstr(&buf, extra_cc.items[i].string);
1981 if (i + 1 < extra_cc.nr)
1982 strbuf_addch(&buf, ',');
1983 strbuf_addch(&buf, '\n');
1986 rev.extra_headers = to_free = strbuf_detach(&buf, NULL);
1988 if (from) {
1989 if (split_ident_line(&rev.from_ident, from, strlen(from)))
1990 die(_("invalid ident line: %s"), from);
1993 if (start_number < 0)
1994 start_number = 1;
1997 * If numbered is set solely due to format.numbered in config,
1998 * and it would conflict with --keep-subject (-k) from the
1999 * command line, reset "numbered".
2001 if (numbered && keep_subject && !numbered_cmdline_opt)
2002 numbered = 0;
2004 if (numbered && keep_subject)
2005 die(_("options '%s' and '%s' cannot be used together"), "-n", "-k");
2006 if (keep_subject && subject_prefix)
2007 die(_("options '%s' and '%s' cannot be used together"), "--subject-prefix/--rfc", "-k");
2008 rev.preserve_subject = keep_subject;
2010 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
2011 if (argc > 1)
2012 die(_("unrecognized argument: %s"), argv[1]);
2014 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
2015 die(_("--name-only does not make sense"));
2016 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
2017 die(_("--name-status does not make sense"));
2018 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
2019 die(_("--check does not make sense"));
2020 if (rev.remerge_diff)
2021 die(_("--remerge-diff does not make sense"));
2023 if (!use_patch_format &&
2024 (!rev.diffopt.output_format ||
2025 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
2026 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
2027 if (!rev.diffopt.stat_width)
2028 rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
2030 /* Always generate a patch */
2031 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
2033 rev.zero_commit = zero_commit;
2034 rev.patch_name_max = fmt_patch_name_max;
2036 if (!rev.diffopt.flags.text && !no_binary_diff)
2037 rev.diffopt.flags.binary = 1;
2039 if (rev.show_notes)
2040 load_display_notes(&rev.notes_opt);
2042 die_for_incompatible_opt3(use_stdout, "--stdout",
2043 rev.diffopt.close_file, "--output",
2044 !!output_directory, "--output-directory");
2046 if (use_stdout) {
2047 setup_pager();
2048 } else if (!rev.diffopt.close_file) {
2049 int saved;
2051 if (!output_directory)
2052 output_directory = config_output_directory;
2053 output_directory = set_outdir(prefix, output_directory);
2055 if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
2056 rev.diffopt.use_color = GIT_COLOR_NEVER;
2058 * We consider <outdir> as 'outside of gitdir', therefore avoid
2059 * applying adjust_shared_perm in s-c-l-d.
2061 saved = get_shared_repository();
2062 set_shared_repository(0);
2063 switch (safe_create_leading_directories_const(output_directory)) {
2064 case SCLD_OK:
2065 case SCLD_EXISTS:
2066 break;
2067 default:
2068 die(_("could not create leading directories "
2069 "of '%s'"), output_directory);
2071 set_shared_repository(saved);
2072 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
2073 die_errno(_("could not create directory '%s'"),
2074 output_directory);
2077 if (rev.pending.nr == 1) {
2078 int check_head = 0;
2080 if (rev.max_count < 0 && !rev.show_root_diff) {
2082 * This is traditional behaviour of "git format-patch
2083 * origin" that prepares what the origin side still
2084 * does not have.
2086 rev.pending.objects[0].item->flags |= UNINTERESTING;
2087 add_head_to_pending(&rev);
2088 check_head = 1;
2091 * Otherwise, it is "format-patch -22 HEAD", and/or
2092 * "format-patch --root HEAD". The user wants
2093 * get_revision() to do the usual traversal.
2096 if (!strcmp(rev.pending.objects[0].name, "HEAD"))
2097 check_head = 1;
2099 if (check_head) {
2100 const char *ref, *v;
2101 ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2102 NULL, NULL);
2103 if (ref && skip_prefix(ref, "refs/heads/", &v))
2104 branch_name = xstrdup(v);
2105 else
2106 branch_name = xstrdup(""); /* no branch */
2111 * We cannot move this anywhere earlier because we do want to
2112 * know if --root was given explicitly from the command line.
2114 rev.show_root_diff = 1;
2116 if (ignore_if_in_upstream) {
2117 /* Don't say anything if head and upstream are the same. */
2118 if (rev.pending.nr == 2) {
2119 struct object_array_entry *o = rev.pending.objects;
2120 if (oideq(&o[0].item->oid, &o[1].item->oid))
2121 goto done;
2123 get_patch_ids(&rev, &ids);
2126 if (prepare_revision_walk(&rev))
2127 die(_("revision walk setup failed"));
2128 rev.boundary = 1;
2129 while ((commit = get_revision(&rev)) != NULL) {
2130 if (commit->object.flags & BOUNDARY) {
2131 boundary_count++;
2132 origin = (boundary_count == 1) ? commit : NULL;
2133 continue;
2136 if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
2137 continue;
2139 nr++;
2140 REALLOC_ARRAY(list, nr);
2141 list[nr - 1] = commit;
2143 if (nr == 0)
2144 /* nothing to do */
2145 goto done;
2146 total = nr;
2147 if (cover_letter == -1) {
2148 if (config_cover_letter == COVER_AUTO)
2149 cover_letter = (total > 1);
2150 else
2151 cover_letter = (config_cover_letter == COVER_ON);
2153 if (!keep_subject && auto_number && (total > 1 || cover_letter))
2154 numbered = 1;
2155 if (numbered)
2156 rev.total = total + start_number - 1;
2158 if (idiff_prev.nr) {
2159 if (!cover_letter && total != 1)
2160 die(_("--interdiff requires --cover-letter or single patch"));
2161 rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
2162 rev.idiff_oid2 = get_commit_tree_oid(list[0]);
2163 rev.idiff_title = diff_title(&idiff_title, reroll_count,
2164 _("Interdiff:"),
2165 _("Interdiff against v%d:"));
2168 if (creation_factor < 0)
2169 creation_factor = RANGE_DIFF_CREATION_FACTOR_DEFAULT;
2170 else if (!rdiff_prev)
2171 die(_("the option '%s' requires '%s'"), "--creation-factor", "--range-diff");
2173 if (rdiff_prev) {
2174 if (!cover_letter && total != 1)
2175 die(_("--range-diff requires --cover-letter or single patch"));
2177 infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
2178 origin, list[0]);
2179 rev.rdiff1 = rdiff1.buf;
2180 rev.rdiff2 = rdiff2.buf;
2181 rev.creation_factor = creation_factor;
2182 rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
2183 _("Range-diff:"),
2184 _("Range-diff against v%d:"));
2187 if (!signature) {
2188 ; /* --no-signature inhibits all signatures */
2189 } else if (signature && signature != git_version_string) {
2190 ; /* non-default signature already set */
2191 } else if (signature_file) {
2192 struct strbuf buf = STRBUF_INIT;
2194 if (strbuf_read_file(&buf, signature_file, 128) < 0)
2195 die_errno(_("unable to read signature file '%s'"), signature_file);
2196 signature = strbuf_detach(&buf, NULL);
2199 memset(&bases, 0, sizeof(bases));
2200 base = get_base_commit(base_commit, list, nr);
2201 if (base) {
2202 reset_revision_walk();
2203 clear_object_flags(UNINTERESTING);
2204 prepare_bases(&bases, base, list, nr);
2207 if (in_reply_to || thread || cover_letter) {
2208 rev.ref_message_ids = xmalloc(sizeof(*rev.ref_message_ids));
2209 string_list_init_nodup(rev.ref_message_ids);
2211 if (in_reply_to) {
2212 const char *msgid = clean_message_id(in_reply_to);
2213 string_list_append(rev.ref_message_ids, msgid);
2215 rev.numbered_files = just_numbers;
2216 rev.patch_suffix = fmt_patch_suffix;
2217 if (cover_letter) {
2218 if (thread)
2219 gen_message_id(&rev, "cover");
2220 make_cover_letter(&rev, !!output_directory,
2221 origin, nr, list, branch_name, quiet);
2222 print_bases(&bases, rev.diffopt.file);
2223 print_signature(rev.diffopt.file);
2224 total++;
2225 start_number--;
2226 /* interdiff/range-diff in cover-letter; omit from patches */
2227 rev.idiff_oid1 = NULL;
2228 rev.rdiff1 = NULL;
2230 rev.add_signoff = do_signoff;
2232 if (show_progress)
2233 progress = start_delayed_progress(_("Generating patches"), total);
2234 while (0 <= --nr) {
2235 int shown;
2236 display_progress(progress, total - nr);
2237 commit = list[nr];
2238 rev.nr = total - nr + (start_number - 1);
2239 /* Make the second and subsequent mails replies to the first */
2240 if (thread) {
2241 /* Have we already had a message ID? */
2242 if (rev.message_id) {
2244 * For deep threading: make every mail
2245 * a reply to the previous one, no
2246 * matter what other options are set.
2248 * For shallow threading:
2250 * Without --cover-letter and
2251 * --in-reply-to, make every mail a
2252 * reply to the one before.
2254 * With --in-reply-to but no
2255 * --cover-letter, make every mail a
2256 * reply to the <reply-to>.
2258 * With --cover-letter, make every
2259 * mail but the cover letter a reply
2260 * to the cover letter. The cover
2261 * letter is a reply to the
2262 * --in-reply-to, if specified.
2264 if (thread == THREAD_SHALLOW
2265 && rev.ref_message_ids->nr > 0
2266 && (!cover_letter || rev.nr > 1))
2267 free(rev.message_id);
2268 else
2269 string_list_append(rev.ref_message_ids,
2270 rev.message_id);
2272 gen_message_id(&rev, oid_to_hex(&commit->object.oid));
2275 if (output_directory &&
2276 open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
2277 die(_("failed to create output files"));
2278 shown = log_tree_commit(&rev, commit);
2279 free_commit_buffer(the_repository->parsed_objects,
2280 commit);
2282 /* We put one extra blank line between formatted
2283 * patches and this flag is used by log-tree code
2284 * to see if it needs to emit a LF before showing
2285 * the log; when using one file per patch, we do
2286 * not want the extra blank line.
2288 if (output_directory)
2289 rev.shown_one = 0;
2290 if (shown) {
2291 print_bases(&bases, rev.diffopt.file);
2292 if (rev.mime_boundary)
2293 fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
2294 mime_boundary_leader,
2295 rev.mime_boundary);
2296 else
2297 print_signature(rev.diffopt.file);
2299 if (output_directory)
2300 fclose(rev.diffopt.file);
2302 stop_progress(&progress);
2303 free(list);
2304 free(branch_name);
2305 string_list_clear(&extra_to, 0);
2306 string_list_clear(&extra_cc, 0);
2307 string_list_clear(&extra_hdr, 0);
2308 if (ignore_if_in_upstream)
2309 free_patch_ids(&ids);
2311 done:
2312 oid_array_clear(&idiff_prev);
2313 strbuf_release(&idiff_title);
2314 strbuf_release(&rdiff1);
2315 strbuf_release(&rdiff2);
2316 strbuf_release(&rdiff_title);
2317 free(to_free);
2318 if (rev.ref_message_ids)
2319 string_list_clear(rev.ref_message_ids, 0);
2320 free(rev.ref_message_ids);
2321 return cmd_log_deinit(0, &rev);
2324 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
2326 struct object_id oid;
2327 if (get_oid(arg, &oid) == 0) {
2328 struct commit *commit = lookup_commit_reference(the_repository,
2329 &oid);
2330 if (commit) {
2331 commit->object.flags |= flags;
2332 add_pending_object(revs, &commit->object, arg);
2333 return 0;
2336 return -1;
2339 static const char * const cherry_usage[] = {
2340 N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
2341 NULL
2344 static void print_commit(char sign, struct commit *commit, int verbose,
2345 int abbrev, FILE *file)
2347 if (!verbose) {
2348 fprintf(file, "%c %s\n", sign,
2349 find_unique_abbrev(&commit->object.oid, abbrev));
2350 } else {
2351 struct strbuf buf = STRBUF_INIT;
2352 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2353 fprintf(file, "%c %s %s\n", sign,
2354 find_unique_abbrev(&commit->object.oid, abbrev),
2355 buf.buf);
2356 strbuf_release(&buf);
2360 int cmd_cherry(int argc, const char **argv, const char *prefix)
2362 struct rev_info revs;
2363 struct patch_ids ids;
2364 struct commit *commit;
2365 struct commit_list *list = NULL;
2366 struct branch *current_branch;
2367 const char *upstream;
2368 const char *head = "HEAD";
2369 const char *limit = NULL;
2370 int verbose = 0, abbrev = 0;
2372 struct option options[] = {
2373 OPT__ABBREV(&abbrev),
2374 OPT__VERBOSE(&verbose, N_("be verbose")),
2375 OPT_END()
2378 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
2380 switch (argc) {
2381 case 3:
2382 limit = argv[2];
2383 /* FALLTHROUGH */
2384 case 2:
2385 head = argv[1];
2386 /* FALLTHROUGH */
2387 case 1:
2388 upstream = argv[0];
2389 break;
2390 default:
2391 current_branch = branch_get(NULL);
2392 upstream = branch_get_upstream(current_branch, NULL);
2393 if (!upstream) {
2394 fprintf(stderr, _("Could not find a tracked"
2395 " remote branch, please"
2396 " specify <upstream> manually.\n"));
2397 usage_with_options(cherry_usage, options);
2401 repo_init_revisions(the_repository, &revs, prefix);
2402 revs.max_parents = 1;
2404 if (add_pending_commit(head, &revs, 0))
2405 die(_("unknown commit %s"), head);
2406 if (add_pending_commit(upstream, &revs, UNINTERESTING))
2407 die(_("unknown commit %s"), upstream);
2409 /* Don't say anything if head and upstream are the same. */
2410 if (revs.pending.nr == 2) {
2411 struct object_array_entry *o = revs.pending.objects;
2412 if (oideq(&o[0].item->oid, &o[1].item->oid))
2413 return 0;
2416 get_patch_ids(&revs, &ids);
2418 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2419 die(_("unknown commit %s"), limit);
2421 /* reverse the list of commits */
2422 if (prepare_revision_walk(&revs))
2423 die(_("revision walk setup failed"));
2424 while ((commit = get_revision(&revs)) != NULL) {
2425 commit_list_insert(commit, &list);
2428 while (list) {
2429 char sign = '+';
2431 commit = list->item;
2432 if (has_commit_patch_id(commit, &ids))
2433 sign = '-';
2434 print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2435 list = list->next;
2438 free_patch_ids(&ids);
2439 return 0;