rebase -i: remove patch file after conflict resolution
[git.git] / builtin / log.c
blob7d195789633978c03c18e2c331d75f1b56f924e8
1 /*
2 * Builtin "git log" and related commands (show, whatchanged)
4 * (C) Copyright 2006 Linus Torvalds
5 * 2006 Junio Hamano
6 */
7 #include "git-compat-util.h"
8 #include "abspath.h"
9 #include "alloc.h"
10 #include "config.h"
11 #include "environment.h"
12 #include "gettext.h"
13 #include "hex.h"
14 #include "refs.h"
15 #include "object-store.h"
16 #include "color.h"
17 #include "commit.h"
18 #include "diff.h"
19 #include "diff-merges.h"
20 #include "revision.h"
21 #include "log-tree.h"
22 #include "builtin.h"
23 #include "tag.h"
24 #include "reflog-walk.h"
25 #include "patch-ids.h"
26 #include "run-command.h"
27 #include "shortlog.h"
28 #include "remote.h"
29 #include "string-list.h"
30 #include "parse-options.h"
31 #include "line-log.h"
32 #include "branch.h"
33 #include "streaming.h"
34 #include "version.h"
35 #include "mailmap.h"
36 #include "gpg-interface.h"
37 #include "progress.h"
38 #include "commit-slab.h"
39 #include "repository.h"
40 #include "commit-reach.h"
41 #include "range-diff.h"
42 #include "tmp-objdir.h"
43 #include "write-or-die.h"
45 #define MAIL_DEFAULT_WRAP 72
46 #define COVER_FROM_AUTO_MAX_SUBJECT_LEN 100
47 #define FORMAT_PATCH_NAME_MAX_DEFAULT 64
49 /* Set a default date-time format for git log ("log.date" config variable) */
50 static const char *default_date_mode = NULL;
52 static int default_abbrev_commit;
53 static int default_show_root = 1;
54 static int default_follow;
55 static int default_show_signature;
56 static int default_encode_email_headers = 1;
57 static int decoration_style;
58 static int decoration_given;
59 static int use_mailmap_config = 1;
60 static unsigned int force_in_body_from;
61 static int stdout_mboxrd;
62 static const char *fmt_patch_subject_prefix = "PATCH";
63 static int fmt_patch_name_max = FORMAT_PATCH_NAME_MAX_DEFAULT;
64 static const char *fmt_pretty;
65 static int format_no_prefix;
67 static const char * const builtin_log_usage[] = {
68 N_("git log [<options>] [<revision-range>] [[--] <path>...]"),
69 N_("git show [<options>] <object>..."),
70 NULL
73 struct line_opt_callback_data {
74 struct rev_info *rev;
75 const char *prefix;
76 struct string_list args;
79 static int session_is_interactive(void)
81 return isatty(1) || pager_in_use();
84 static int auto_decoration_style(void)
86 return session_is_interactive() ? DECORATE_SHORT_REFS : 0;
89 static int parse_decoration_style(const char *value)
91 switch (git_parse_maybe_bool(value)) {
92 case 1:
93 return DECORATE_SHORT_REFS;
94 case 0:
95 return 0;
96 default:
97 break;
99 if (!strcmp(value, "full"))
100 return DECORATE_FULL_REFS;
101 else if (!strcmp(value, "short"))
102 return DECORATE_SHORT_REFS;
103 else if (!strcmp(value, "auto"))
104 return auto_decoration_style();
106 * Please update _git_log() in git-completion.bash when you
107 * add new decoration styles.
109 return -1;
112 static int use_default_decoration_filter = 1;
113 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
114 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
115 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
117 static int clear_decorations_callback(const struct option *opt,
118 const char *arg, int unset)
120 string_list_clear(&decorate_refs_include, 0);
121 string_list_clear(&decorate_refs_exclude, 0);
122 use_default_decoration_filter = 0;
123 return 0;
126 static int decorate_callback(const struct option *opt, const char *arg, int unset)
128 if (unset)
129 decoration_style = 0;
130 else if (arg)
131 decoration_style = parse_decoration_style(arg);
132 else
133 decoration_style = DECORATE_SHORT_REFS;
135 if (decoration_style < 0)
136 die(_("invalid --decorate option: %s"), arg);
138 decoration_given = 1;
140 return 0;
143 static int log_line_range_callback(const struct option *option, const char *arg, int unset)
145 struct line_opt_callback_data *data = option->value;
147 BUG_ON_OPT_NEG(unset);
149 if (!arg)
150 return -1;
152 data->rev->line_level_traverse = 1;
153 string_list_append(&data->args, arg);
155 return 0;
158 static void init_log_defaults(void)
160 init_diff_ui_defaults();
162 decoration_style = auto_decoration_style();
165 static void cmd_log_init_defaults(struct rev_info *rev)
167 if (fmt_pretty)
168 get_commit_format(fmt_pretty, rev);
169 if (default_follow)
170 rev->diffopt.flags.default_follow_renames = 1;
171 rev->verbose_header = 1;
172 rev->diffopt.flags.recursive = 1;
173 rev->diffopt.stat_width = -1; /* use full terminal width */
174 rev->diffopt.stat_graph_width = -1; /* respect statGraphWidth config */
175 rev->abbrev_commit = default_abbrev_commit;
176 rev->show_root_diff = default_show_root;
177 rev->subject_prefix = fmt_patch_subject_prefix;
178 rev->patch_name_max = fmt_patch_name_max;
179 rev->show_signature = default_show_signature;
180 rev->encode_email_headers = default_encode_email_headers;
181 rev->diffopt.flags.allow_textconv = 1;
183 if (default_date_mode)
184 parse_date_format(default_date_mode, &rev->date_mode);
187 static void set_default_decoration_filter(struct decoration_filter *decoration_filter)
189 int i;
190 char *value = NULL;
191 struct string_list *include = decoration_filter->include_ref_pattern;
192 const struct string_list *config_exclude;
194 if (!git_config_get_string_multi("log.excludeDecoration",
195 &config_exclude)) {
196 struct string_list_item *item;
197 for_each_string_list_item(item, config_exclude)
198 string_list_append(decoration_filter->exclude_ref_config_pattern,
199 item->string);
203 * By default, decorate_all is disabled. Enable it if
204 * log.initialDecorationSet=all. Don't ever disable it by config,
205 * since the command-line takes precedent.
207 if (use_default_decoration_filter &&
208 !git_config_get_string("log.initialdecorationset", &value) &&
209 !strcmp("all", value))
210 use_default_decoration_filter = 0;
211 free(value);
213 if (!use_default_decoration_filter ||
214 decoration_filter->exclude_ref_pattern->nr ||
215 decoration_filter->include_ref_pattern->nr ||
216 decoration_filter->exclude_ref_config_pattern->nr)
217 return;
220 * No command-line or config options were given, so
221 * populate with sensible defaults.
223 for (i = 0; i < ARRAY_SIZE(ref_namespace); i++) {
224 if (!ref_namespace[i].decoration)
225 continue;
227 string_list_append(include, ref_namespace[i].ref);
231 static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
232 struct rev_info *rev, struct setup_revision_opt *opt)
234 struct userformat_want w;
235 int quiet = 0, source = 0, mailmap;
236 static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
237 struct decoration_filter decoration_filter = {
238 .exclude_ref_pattern = &decorate_refs_exclude,
239 .include_ref_pattern = &decorate_refs_include,
240 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
242 static struct revision_sources revision_sources;
244 const struct option builtin_log_options[] = {
245 OPT__QUIET(&quiet, N_("suppress diff output")),
246 OPT_BOOL(0, "source", &source, N_("show source")),
247 OPT_BOOL(0, "use-mailmap", &mailmap, N_("use mail map file")),
248 OPT_ALIAS(0, "mailmap", "use-mailmap"),
249 OPT_CALLBACK_F(0, "clear-decorations", NULL, NULL,
250 N_("clear all previously-defined decoration filters"),
251 PARSE_OPT_NOARG | PARSE_OPT_NONEG,
252 clear_decorations_callback),
253 OPT_STRING_LIST(0, "decorate-refs", &decorate_refs_include,
254 N_("pattern"), N_("only decorate refs that match <pattern>")),
255 OPT_STRING_LIST(0, "decorate-refs-exclude", &decorate_refs_exclude,
256 N_("pattern"), N_("do not decorate refs that match <pattern>")),
257 OPT_CALLBACK_F(0, "decorate", NULL, NULL, N_("decorate options"),
258 PARSE_OPT_OPTARG, decorate_callback),
259 OPT_CALLBACK('L', NULL, &line_cb, "range:file",
260 N_("trace the evolution of line range <start>,<end> or function :<funcname> in <file>"),
261 log_line_range_callback),
262 OPT_END()
265 line_cb.rev = rev;
266 line_cb.prefix = prefix;
268 mailmap = use_mailmap_config;
269 argc = parse_options(argc, argv, prefix,
270 builtin_log_options, builtin_log_usage,
271 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
272 PARSE_OPT_KEEP_DASHDASH);
274 if (quiet)
275 rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
276 argc = setup_revisions(argc, argv, rev, opt);
278 /* Any arguments at this point are not recognized */
279 if (argc > 1)
280 die(_("unrecognized argument: %s"), argv[1]);
282 if (rev->line_level_traverse && rev->prune_data.nr)
283 die(_("-L<range>:<file> cannot be used with pathspec"));
285 memset(&w, 0, sizeof(w));
286 userformat_find_requirements(NULL, &w);
288 if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
289 rev->show_notes = 1;
290 if (rev->show_notes)
291 load_display_notes(&rev->notes_opt);
293 if ((rev->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
294 rev->diffopt.filter || rev->diffopt.flags.follow_renames)
295 rev->always_show_header = 0;
297 if (source || w.source) {
298 init_revision_sources(&revision_sources);
299 rev->sources = &revision_sources;
302 if (mailmap) {
303 rev->mailmap = xmalloc(sizeof(struct string_list));
304 string_list_init_nodup(rev->mailmap);
305 read_mailmap(rev->mailmap);
308 if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
310 * "log --pretty=raw" is special; ignore UI oriented
311 * configuration variables such as decoration.
313 if (!decoration_given)
314 decoration_style = 0;
315 if (!rev->abbrev_commit_given)
316 rev->abbrev_commit = 0;
319 if (rev->commit_format == CMIT_FMT_USERFORMAT) {
320 if (!w.decorate) {
322 * Disable decoration loading if the format will not
323 * show them anyway.
325 decoration_style = 0;
326 } else if (!decoration_style) {
328 * If we are going to show them, make sure we do load
329 * them here, but taking care not to override a
330 * specific style set by config or --decorate.
332 decoration_style = DECORATE_SHORT_REFS;
336 if (decoration_style || rev->simplify_by_decoration) {
337 set_default_decoration_filter(&decoration_filter);
339 if (decoration_style)
340 rev->show_decorations = 1;
342 load_ref_decorations(&decoration_filter, decoration_style);
345 if (rev->line_level_traverse)
346 line_log_init(rev, line_cb.prefix, &line_cb.args);
348 setup_pager();
351 static void cmd_log_init(int argc, const char **argv, const char *prefix,
352 struct rev_info *rev, struct setup_revision_opt *opt)
354 cmd_log_init_defaults(rev);
355 cmd_log_init_finish(argc, argv, prefix, rev, opt);
358 static int cmd_log_deinit(int ret, struct rev_info *rev)
360 release_revisions(rev);
361 return ret;
365 * This gives a rough estimate for how many commits we
366 * will print out in the list.
368 static int estimate_commit_count(struct commit_list *list)
370 int n = 0;
372 while (list) {
373 struct commit *commit = list->item;
374 unsigned int flags = commit->object.flags;
375 list = list->next;
376 if (!(flags & (TREESAME | UNINTERESTING)))
377 n++;
379 return n;
382 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
384 if (rev->shown_one) {
385 rev->shown_one = 0;
386 if (rev->commit_format != CMIT_FMT_ONELINE)
387 putchar(rev->diffopt.line_termination);
389 fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
392 static struct itimerval early_output_timer;
394 static void log_show_early(struct rev_info *revs, struct commit_list *list)
396 int i = revs->early_output;
397 int show_header = 1;
398 int no_free = revs->diffopt.no_free;
400 revs->diffopt.no_free = 0;
401 sort_in_topological_order(&list, revs->sort_order);
402 while (list && i) {
403 struct commit *commit = list->item;
404 switch (simplify_commit(revs, commit)) {
405 case commit_show:
406 if (show_header) {
407 int n = estimate_commit_count(list);
408 show_early_header(revs, "incomplete", n);
409 show_header = 0;
411 log_tree_commit(revs, commit);
412 i--;
413 break;
414 case commit_ignore:
415 break;
416 case commit_error:
417 revs->diffopt.no_free = no_free;
418 diff_free(&revs->diffopt);
419 return;
421 list = list->next;
424 /* Did we already get enough commits for the early output? */
425 if (!i) {
426 revs->diffopt.no_free = 0;
427 diff_free(&revs->diffopt);
428 return;
432 * ..if no, then repeat it twice a second until we
433 * do.
435 * NOTE! We don't use "it_interval", because if the
436 * reader isn't listening, we want our output to be
437 * throttled by the writing, and not have the timer
438 * trigger every second even if we're blocked on a
439 * reader!
441 early_output_timer.it_value.tv_sec = 0;
442 early_output_timer.it_value.tv_usec = 500000;
443 setitimer(ITIMER_REAL, &early_output_timer, NULL);
446 static void early_output(int signal UNUSED)
448 show_early_output = log_show_early;
451 static void setup_early_output(void)
453 struct sigaction sa;
456 * Set up the signal handler, minimally intrusively:
457 * we only set a single volatile integer word (not
458 * using sigatomic_t - trying to avoid unnecessary
459 * system dependencies and headers), and using
460 * SA_RESTART.
462 memset(&sa, 0, sizeof(sa));
463 sa.sa_handler = early_output;
464 sigemptyset(&sa.sa_mask);
465 sa.sa_flags = SA_RESTART;
466 sigaction(SIGALRM, &sa, NULL);
469 * If we can get the whole output in less than a
470 * tenth of a second, don't even bother doing the
471 * early-output thing..
473 * This is a one-time-only trigger.
475 early_output_timer.it_value.tv_sec = 0;
476 early_output_timer.it_value.tv_usec = 100000;
477 setitimer(ITIMER_REAL, &early_output_timer, NULL);
480 static void finish_early_output(struct rev_info *rev)
482 int n = estimate_commit_count(rev->commits);
483 signal(SIGALRM, SIG_IGN);
484 show_early_header(rev, "done", n);
487 static int cmd_log_walk_no_free(struct rev_info *rev)
489 struct commit *commit;
490 int saved_nrl = 0;
491 int saved_dcctc = 0;
493 if (rev->remerge_diff) {
494 rev->remerge_objdir = tmp_objdir_create("remerge-diff");
495 if (!rev->remerge_objdir)
496 die(_("unable to create temporary object directory"));
497 tmp_objdir_replace_primary_odb(rev->remerge_objdir, 1);
500 if (rev->early_output)
501 setup_early_output();
503 if (prepare_revision_walk(rev))
504 die(_("revision walk setup failed"));
506 if (rev->early_output)
507 finish_early_output(rev);
510 * For --check and --exit-code, the exit code is based on CHECK_FAILED
511 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
512 * retain that state information if replacing rev->diffopt in this loop
514 while ((commit = get_revision(rev)) != NULL) {
515 if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
517 * We decremented max_count in get_revision,
518 * but we didn't actually show the commit.
520 rev->max_count++;
521 if (!rev->reflog_info) {
523 * We may show a given commit multiple times when
524 * walking the reflogs.
526 free_commit_buffer(the_repository->parsed_objects,
527 commit);
528 free_commit_list(commit->parents);
529 commit->parents = NULL;
531 if (saved_nrl < rev->diffopt.needed_rename_limit)
532 saved_nrl = rev->diffopt.needed_rename_limit;
533 if (rev->diffopt.degraded_cc_to_c)
534 saved_dcctc = 1;
536 rev->diffopt.degraded_cc_to_c = saved_dcctc;
537 rev->diffopt.needed_rename_limit = saved_nrl;
539 if (rev->remerge_diff) {
540 tmp_objdir_destroy(rev->remerge_objdir);
541 rev->remerge_objdir = NULL;
544 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
545 rev->diffopt.flags.check_failed) {
546 return 02;
548 return diff_result_code(&rev->diffopt, 0);
551 static int cmd_log_walk(struct rev_info *rev)
553 int retval;
555 rev->diffopt.no_free = 1;
556 retval = cmd_log_walk_no_free(rev);
557 rev->diffopt.no_free = 0;
558 diff_free(&rev->diffopt);
559 return retval;
562 static int git_log_config(const char *var, const char *value, void *cb)
564 const char *slot_name;
566 if (!strcmp(var, "format.pretty"))
567 return git_config_string(&fmt_pretty, var, value);
568 if (!strcmp(var, "format.subjectprefix"))
569 return git_config_string(&fmt_patch_subject_prefix, var, value);
570 if (!strcmp(var, "format.filenamemaxlength")) {
571 fmt_patch_name_max = git_config_int(var, value);
572 return 0;
574 if (!strcmp(var, "format.encodeemailheaders")) {
575 default_encode_email_headers = git_config_bool(var, value);
576 return 0;
578 if (!strcmp(var, "log.abbrevcommit")) {
579 default_abbrev_commit = git_config_bool(var, value);
580 return 0;
582 if (!strcmp(var, "log.date"))
583 return git_config_string(&default_date_mode, var, value);
584 if (!strcmp(var, "log.decorate")) {
585 decoration_style = parse_decoration_style(value);
586 if (decoration_style < 0)
587 decoration_style = 0; /* maybe warn? */
588 return 0;
590 if (!strcmp(var, "log.diffmerges"))
591 return diff_merges_config(value);
592 if (!strcmp(var, "log.showroot")) {
593 default_show_root = git_config_bool(var, value);
594 return 0;
596 if (!strcmp(var, "log.follow")) {
597 default_follow = git_config_bool(var, value);
598 return 0;
600 if (skip_prefix(var, "color.decorate.", &slot_name))
601 return parse_decorate_color_config(var, slot_name, value);
602 if (!strcmp(var, "log.mailmap")) {
603 use_mailmap_config = git_config_bool(var, value);
604 return 0;
606 if (!strcmp(var, "log.showsignature")) {
607 default_show_signature = git_config_bool(var, value);
608 return 0;
611 return git_diff_ui_config(var, value, cb);
614 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
616 struct rev_info rev;
617 struct setup_revision_opt opt;
619 init_log_defaults();
620 git_config(git_log_config, NULL);
622 repo_init_revisions(the_repository, &rev, prefix);
623 git_config(grep_config, &rev.grep_filter);
625 rev.diff = 1;
626 rev.simplify_history = 0;
627 memset(&opt, 0, sizeof(opt));
628 opt.def = "HEAD";
629 opt.revarg_opt = REVARG_COMMITTISH;
630 cmd_log_init(argc, argv, prefix, &rev, &opt);
631 if (!rev.diffopt.output_format)
632 rev.diffopt.output_format = DIFF_FORMAT_RAW;
633 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
636 static void show_tagger(const char *buf, struct rev_info *rev)
638 struct strbuf out = STRBUF_INIT;
639 struct pretty_print_context pp = {0};
641 pp.fmt = rev->commit_format;
642 pp.date_mode = rev->date_mode;
643 pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
644 fprintf(rev->diffopt.file, "%s", out.buf);
645 strbuf_release(&out);
648 static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
650 struct object_id oidc;
651 struct object_context obj_context;
652 char *buf;
653 unsigned long size;
655 fflush(rev->diffopt.file);
656 if (!rev->diffopt.flags.textconv_set_via_cmdline ||
657 !rev->diffopt.flags.allow_textconv)
658 return stream_blob_to_fd(1, oid, NULL, 0);
660 if (get_oid_with_context(the_repository, obj_name,
661 GET_OID_RECORD_PATH,
662 &oidc, &obj_context))
663 die(_("not a valid object name %s"), obj_name);
664 if (!obj_context.path ||
665 !textconv_object(the_repository, obj_context.path,
666 obj_context.mode, &oidc, 1, &buf, &size)) {
667 free(obj_context.path);
668 return stream_blob_to_fd(1, oid, NULL, 0);
671 if (!buf)
672 die(_("git show %s: bad file"), obj_name);
674 write_or_die(1, buf, size);
675 free(obj_context.path);
676 return 0;
679 static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
681 unsigned long size;
682 enum object_type type;
683 char *buf = repo_read_object_file(the_repository, oid, &type, &size);
684 int offset = 0;
686 if (!buf)
687 return error(_("could not read object %s"), oid_to_hex(oid));
689 assert(type == OBJ_TAG);
690 while (offset < size && buf[offset] != '\n') {
691 int new_offset = offset + 1;
692 const char *ident;
693 while (new_offset < size && buf[new_offset++] != '\n')
694 ; /* do nothing */
695 if (skip_prefix(buf + offset, "tagger ", &ident))
696 show_tagger(ident, rev);
697 offset = new_offset;
700 if (offset < size)
701 fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
702 free(buf);
703 return 0;
706 static int show_tree_object(const struct object_id *oid UNUSED,
707 struct strbuf *base UNUSED,
708 const char *pathname, unsigned mode,
709 void *context)
711 FILE *file = context;
712 fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
713 return 0;
716 static void show_setup_revisions_tweak(struct rev_info *rev,
717 struct setup_revision_opt *opt)
719 if (rev->first_parent_only)
720 diff_merges_default_to_first_parent(rev);
721 else
722 diff_merges_default_to_dense_combined(rev);
723 if (!rev->diffopt.output_format)
724 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
727 int cmd_show(int argc, const char **argv, const char *prefix)
729 struct rev_info rev;
730 unsigned int i;
731 struct setup_revision_opt opt;
732 struct pathspec match_all;
733 int ret = 0;
735 init_log_defaults();
736 git_config(git_log_config, NULL);
738 if (the_repository->gitdir) {
739 prepare_repo_settings(the_repository);
740 the_repository->settings.command_requires_full_index = 0;
743 memset(&match_all, 0, sizeof(match_all));
744 repo_init_revisions(the_repository, &rev, prefix);
745 git_config(grep_config, &rev.grep_filter);
747 rev.diff = 1;
748 rev.always_show_header = 1;
749 rev.no_walk = 1;
750 rev.diffopt.stat_width = -1; /* Scale to real terminal size */
752 memset(&opt, 0, sizeof(opt));
753 opt.def = "HEAD";
754 opt.tweak = show_setup_revisions_tweak;
755 cmd_log_init(argc, argv, prefix, &rev, &opt);
757 if (!rev.no_walk)
758 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
760 rev.diffopt.no_free = 1;
761 for (i = 0; i < rev.pending.nr && !ret; i++) {
762 struct object *o = rev.pending.objects[i].item;
763 const char *name = rev.pending.objects[i].name;
764 switch (o->type) {
765 case OBJ_BLOB:
766 ret = show_blob_object(&o->oid, &rev, name);
767 break;
768 case OBJ_TAG: {
769 struct tag *t = (struct tag *)o;
770 struct object_id *oid = get_tagged_oid(t);
772 if (rev.shown_one)
773 putchar('\n');
774 fprintf(rev.diffopt.file, "%stag %s%s\n",
775 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
776 t->tag,
777 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
778 ret = show_tag_object(&o->oid, &rev);
779 rev.shown_one = 1;
780 if (ret)
781 break;
782 o = parse_object(the_repository, oid);
783 if (!o)
784 ret = error(_("could not read object %s"),
785 oid_to_hex(oid));
786 rev.pending.objects[i].item = o;
787 i--;
788 break;
790 case OBJ_TREE:
791 if (rev.shown_one)
792 putchar('\n');
793 fprintf(rev.diffopt.file, "%stree %s%s\n\n",
794 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
795 name,
796 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
797 read_tree(the_repository, (struct tree *)o,
798 &match_all, show_tree_object,
799 rev.diffopt.file);
800 rev.shown_one = 1;
801 break;
802 case OBJ_COMMIT:
804 struct object_array old;
805 struct object_array blank = OBJECT_ARRAY_INIT;
807 memcpy(&old, &rev.pending, sizeof(old));
808 memcpy(&rev.pending, &blank, sizeof(rev.pending));
810 add_object_array(o, name, &rev.pending);
811 ret = cmd_log_walk_no_free(&rev);
814 * No need for
815 * object_array_clear(&pending). It was
816 * cleared already in prepare_revision_walk()
818 memcpy(&rev.pending, &old, sizeof(rev.pending));
819 break;
821 default:
822 ret = error(_("unknown type: %d"), o->type);
826 rev.diffopt.no_free = 0;
827 diff_free(&rev.diffopt);
829 return cmd_log_deinit(ret, &rev);
833 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
835 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
837 struct rev_info rev;
838 struct setup_revision_opt opt;
840 init_log_defaults();
841 git_config(git_log_config, NULL);
843 repo_init_revisions(the_repository, &rev, prefix);
844 init_reflog_walk(&rev.reflog_info);
845 git_config(grep_config, &rev.grep_filter);
847 rev.verbose_header = 1;
848 memset(&opt, 0, sizeof(opt));
849 opt.def = "HEAD";
850 cmd_log_init_defaults(&rev);
851 rev.abbrev_commit = 1;
852 rev.commit_format = CMIT_FMT_ONELINE;
853 rev.use_terminator = 1;
854 rev.always_show_header = 1;
855 cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
857 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
860 static void log_setup_revisions_tweak(struct rev_info *rev,
861 struct setup_revision_opt *opt)
863 if (rev->diffopt.flags.default_follow_renames &&
864 rev->prune_data.nr == 1)
865 rev->diffopt.flags.follow_renames = 1;
867 if (rev->first_parent_only)
868 diff_merges_default_to_first_parent(rev);
871 int cmd_log(int argc, const char **argv, const char *prefix)
873 struct rev_info rev;
874 struct setup_revision_opt opt;
876 init_log_defaults();
877 git_config(git_log_config, NULL);
879 repo_init_revisions(the_repository, &rev, prefix);
880 git_config(grep_config, &rev.grep_filter);
882 rev.always_show_header = 1;
883 memset(&opt, 0, sizeof(opt));
884 opt.def = "HEAD";
885 opt.revarg_opt = REVARG_COMMITTISH;
886 opt.tweak = log_setup_revisions_tweak;
887 cmd_log_init(argc, argv, prefix, &rev, &opt);
888 return cmd_log_deinit(cmd_log_walk(&rev), &rev);
891 /* format-patch */
893 static const char *fmt_patch_suffix = ".patch";
894 static int numbered = 0;
895 static int auto_number = 1;
897 static char *default_attach = NULL;
899 static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
900 static struct string_list extra_to = STRING_LIST_INIT_NODUP;
901 static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
903 static void add_header(const char *value)
905 struct string_list_item *item;
906 int len = strlen(value);
907 while (len && value[len - 1] == '\n')
908 len--;
910 if (!strncasecmp(value, "to: ", 4)) {
911 item = string_list_append(&extra_to, value + 4);
912 len -= 4;
913 } else if (!strncasecmp(value, "cc: ", 4)) {
914 item = string_list_append(&extra_cc, value + 4);
915 len -= 4;
916 } else {
917 item = string_list_append(&extra_hdr, value);
920 item->string[len] = '\0';
923 enum cover_setting {
924 COVER_UNSET,
925 COVER_OFF,
926 COVER_ON,
927 COVER_AUTO
930 enum thread_level {
931 THREAD_UNSET,
932 THREAD_SHALLOW,
933 THREAD_DEEP
936 enum cover_from_description {
937 COVER_FROM_NONE,
938 COVER_FROM_MESSAGE,
939 COVER_FROM_SUBJECT,
940 COVER_FROM_AUTO
943 enum auto_base_setting {
944 AUTO_BASE_NEVER,
945 AUTO_BASE_ALWAYS,
946 AUTO_BASE_WHEN_ABLE
949 static enum thread_level thread;
950 static int do_signoff;
951 static enum auto_base_setting auto_base;
952 static char *from;
953 static const char *signature = git_version_string;
954 static const char *signature_file;
955 static enum cover_setting config_cover_letter;
956 static const char *config_output_directory;
957 static enum cover_from_description cover_from_description_mode = COVER_FROM_MESSAGE;
958 static int show_notes;
959 static struct display_notes_opt notes_opt;
961 static enum cover_from_description parse_cover_from_description(const char *arg)
963 if (!arg || !strcmp(arg, "default"))
964 return COVER_FROM_MESSAGE;
965 else if (!strcmp(arg, "none"))
966 return COVER_FROM_NONE;
967 else if (!strcmp(arg, "message"))
968 return COVER_FROM_MESSAGE;
969 else if (!strcmp(arg, "subject"))
970 return COVER_FROM_SUBJECT;
971 else if (!strcmp(arg, "auto"))
972 return COVER_FROM_AUTO;
973 else
974 die(_("%s: invalid cover from description mode"), arg);
977 static int git_format_config(const char *var, const char *value, void *cb)
979 if (!strcmp(var, "format.headers")) {
980 if (!value)
981 die(_("format.headers without value"));
982 add_header(value);
983 return 0;
985 if (!strcmp(var, "format.suffix"))
986 return git_config_string(&fmt_patch_suffix, var, value);
987 if (!strcmp(var, "format.to")) {
988 if (!value)
989 return config_error_nonbool(var);
990 string_list_append(&extra_to, value);
991 return 0;
993 if (!strcmp(var, "format.cc")) {
994 if (!value)
995 return config_error_nonbool(var);
996 string_list_append(&extra_cc, value);
997 return 0;
999 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
1000 !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
1001 return 0;
1003 if (!strcmp(var, "format.numbered")) {
1004 if (value && !strcasecmp(value, "auto")) {
1005 auto_number = 1;
1006 return 0;
1008 numbered = git_config_bool(var, value);
1009 auto_number = auto_number && numbered;
1010 return 0;
1012 if (!strcmp(var, "format.attach")) {
1013 if (value && *value)
1014 default_attach = xstrdup(value);
1015 else if (value && !*value)
1016 FREE_AND_NULL(default_attach);
1017 else
1018 default_attach = xstrdup(git_version_string);
1019 return 0;
1021 if (!strcmp(var, "format.thread")) {
1022 if (value && !strcasecmp(value, "deep")) {
1023 thread = THREAD_DEEP;
1024 return 0;
1026 if (value && !strcasecmp(value, "shallow")) {
1027 thread = THREAD_SHALLOW;
1028 return 0;
1030 thread = git_config_bool(var, value) ? THREAD_SHALLOW : THREAD_UNSET;
1031 return 0;
1033 if (!strcmp(var, "format.signoff")) {
1034 do_signoff = git_config_bool(var, value);
1035 return 0;
1037 if (!strcmp(var, "format.signature"))
1038 return git_config_string(&signature, var, value);
1039 if (!strcmp(var, "format.signaturefile"))
1040 return git_config_pathname(&signature_file, var, value);
1041 if (!strcmp(var, "format.coverletter")) {
1042 if (value && !strcasecmp(value, "auto")) {
1043 config_cover_letter = COVER_AUTO;
1044 return 0;
1046 config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
1047 return 0;
1049 if (!strcmp(var, "format.outputdirectory"))
1050 return git_config_string(&config_output_directory, var, value);
1051 if (!strcmp(var, "format.useautobase")) {
1052 if (value && !strcasecmp(value, "whenAble")) {
1053 auto_base = AUTO_BASE_WHEN_ABLE;
1054 return 0;
1056 auto_base = git_config_bool(var, value) ? AUTO_BASE_ALWAYS : AUTO_BASE_NEVER;
1057 return 0;
1059 if (!strcmp(var, "format.from")) {
1060 int b = git_parse_maybe_bool(value);
1061 free(from);
1062 if (b < 0)
1063 from = xstrdup(value);
1064 else if (b)
1065 from = xstrdup(git_committer_info(IDENT_NO_DATE));
1066 else
1067 from = NULL;
1068 return 0;
1070 if (!strcmp(var, "format.forceinbodyfrom")) {
1071 force_in_body_from = git_config_bool(var, value);
1072 return 0;
1074 if (!strcmp(var, "format.notes")) {
1075 int b = git_parse_maybe_bool(value);
1076 if (b < 0)
1077 enable_ref_display_notes(&notes_opt, &show_notes, value);
1078 else if (b)
1079 enable_default_display_notes(&notes_opt, &show_notes);
1080 else
1081 disable_display_notes(&notes_opt, &show_notes);
1082 return 0;
1084 if (!strcmp(var, "format.coverfromdescription")) {
1085 cover_from_description_mode = parse_cover_from_description(value);
1086 return 0;
1088 if (!strcmp(var, "format.mboxrd")) {
1089 stdout_mboxrd = git_config_bool(var, value);
1090 return 0;
1092 if (!strcmp(var, "format.noprefix")) {
1093 format_no_prefix = 1;
1094 return 0;
1098 * ignore some porcelain config which would otherwise be parsed by
1099 * git_diff_ui_config(), via git_log_config(); we can't just avoid
1100 * diff_ui_config completely, because we do care about some ui options
1101 * like color.
1103 if (!strcmp(var, "diff.noprefix"))
1104 return 0;
1106 return git_log_config(var, value, cb);
1109 static const char *output_directory = NULL;
1110 static int outdir_offset;
1112 static int open_next_file(struct commit *commit, const char *subject,
1113 struct rev_info *rev, int quiet)
1115 struct strbuf filename = STRBUF_INIT;
1117 if (output_directory) {
1118 strbuf_addstr(&filename, output_directory);
1119 strbuf_complete(&filename, '/');
1122 if (rev->numbered_files)
1123 strbuf_addf(&filename, "%d", rev->nr);
1124 else if (commit)
1125 fmt_output_commit(&filename, commit, rev);
1126 else
1127 fmt_output_subject(&filename, subject, rev);
1129 if (!quiet)
1130 printf("%s\n", filename.buf + outdir_offset);
1132 if (!(rev->diffopt.file = fopen(filename.buf, "w"))) {
1133 error_errno(_("cannot open patch file %s"), filename.buf);
1134 strbuf_release(&filename);
1135 return -1;
1138 strbuf_release(&filename);
1139 return 0;
1142 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
1144 struct rev_info check_rev;
1145 struct commit *commit, *c1, *c2;
1146 struct object *o1, *o2;
1147 unsigned flags1, flags2;
1149 if (rev->pending.nr != 2)
1150 die(_("need exactly one range"));
1152 o1 = rev->pending.objects[0].item;
1153 o2 = rev->pending.objects[1].item;
1154 flags1 = o1->flags;
1155 flags2 = o2->flags;
1156 c1 = lookup_commit_reference(the_repository, &o1->oid);
1157 c2 = lookup_commit_reference(the_repository, &o2->oid);
1159 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
1160 die(_("not a range"));
1162 init_patch_ids(the_repository, ids);
1164 /* given a range a..b get all patch ids for b..a */
1165 repo_init_revisions(the_repository, &check_rev, rev->prefix);
1166 check_rev.max_parents = 1;
1167 o1->flags ^= UNINTERESTING;
1168 o2->flags ^= UNINTERESTING;
1169 add_pending_object(&check_rev, o1, "o1");
1170 add_pending_object(&check_rev, o2, "o2");
1171 if (prepare_revision_walk(&check_rev))
1172 die(_("revision walk setup failed"));
1174 while ((commit = get_revision(&check_rev)) != NULL) {
1175 add_commit_patch_id(commit, ids);
1178 /* reset for next revision walk */
1179 clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
1180 clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
1181 o1->flags = flags1;
1182 o2->flags = flags2;
1185 static void gen_message_id(struct rev_info *info, char *base)
1187 struct strbuf buf = STRBUF_INIT;
1188 strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
1189 (timestamp_t) time(NULL),
1190 git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
1191 info->message_id = strbuf_detach(&buf, NULL);
1194 static void print_signature(FILE *file)
1196 if (!signature || !*signature)
1197 return;
1199 fprintf(file, "-- \n%s", signature);
1200 if (signature[strlen(signature)-1] != '\n')
1201 putc('\n', file);
1202 putc('\n', file);
1205 static char *find_branch_name(struct rev_info *rev)
1207 int i, positive = -1;
1208 struct object_id branch_oid;
1209 const struct object_id *tip_oid;
1210 const char *ref, *v;
1211 char *full_ref, *branch = NULL;
1213 for (i = 0; i < rev->cmdline.nr; i++) {
1214 if (rev->cmdline.rev[i].flags & UNINTERESTING)
1215 continue;
1216 if (positive < 0)
1217 positive = i;
1218 else
1219 return NULL;
1221 if (positive < 0)
1222 return NULL;
1223 ref = rev->cmdline.rev[positive].name;
1224 tip_oid = &rev->cmdline.rev[positive].item->oid;
1225 if (repo_dwim_ref(the_repository, ref, strlen(ref), &branch_oid,
1226 &full_ref, 0) &&
1227 skip_prefix(full_ref, "refs/heads/", &v) &&
1228 oideq(tip_oid, &branch_oid))
1229 branch = xstrdup(v);
1230 free(full_ref);
1231 return branch;
1234 static void show_diffstat(struct rev_info *rev,
1235 struct commit *origin, struct commit *head)
1237 struct diff_options opts;
1239 memcpy(&opts, &rev->diffopt, sizeof(opts));
1240 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1241 diff_setup_done(&opts);
1243 diff_tree_oid(get_commit_tree_oid(origin),
1244 get_commit_tree_oid(head),
1245 "", &opts);
1246 diffcore_std(&opts);
1247 diff_flush(&opts);
1249 fprintf(rev->diffopt.file, "\n");
1252 static void prepare_cover_text(struct pretty_print_context *pp,
1253 const char *branch_name,
1254 struct strbuf *sb,
1255 const char *encoding,
1256 int need_8bit_cte)
1258 const char *subject = "*** SUBJECT HERE ***";
1259 const char *body = "*** BLURB HERE ***";
1260 struct strbuf description_sb = STRBUF_INIT;
1261 struct strbuf subject_sb = STRBUF_INIT;
1263 if (cover_from_description_mode == COVER_FROM_NONE)
1264 goto do_pp;
1266 if (branch_name && *branch_name)
1267 read_branch_desc(&description_sb, branch_name);
1268 if (!description_sb.len)
1269 goto do_pp;
1271 if (cover_from_description_mode == COVER_FROM_SUBJECT ||
1272 cover_from_description_mode == COVER_FROM_AUTO)
1273 body = format_subject(&subject_sb, description_sb.buf, " ");
1275 if (cover_from_description_mode == COVER_FROM_MESSAGE ||
1276 (cover_from_description_mode == COVER_FROM_AUTO &&
1277 subject_sb.len > COVER_FROM_AUTO_MAX_SUBJECT_LEN))
1278 body = description_sb.buf;
1279 else
1280 subject = subject_sb.buf;
1282 do_pp:
1283 pp_title_line(pp, &subject, sb, encoding, need_8bit_cte);
1284 pp_remainder(pp, &body, sb, 0);
1286 strbuf_release(&description_sb);
1287 strbuf_release(&subject_sb);
1290 static int get_notes_refs(struct string_list_item *item, void *arg)
1292 strvec_pushf(arg, "--notes=%s", item->string);
1293 return 0;
1296 static void get_notes_args(struct strvec *arg, struct rev_info *rev)
1298 if (!rev->show_notes) {
1299 strvec_push(arg, "--no-notes");
1300 } else if (rev->notes_opt.use_default_notes > 0 ||
1301 (rev->notes_opt.use_default_notes == -1 &&
1302 !rev->notes_opt.extra_notes_refs.nr)) {
1303 strvec_push(arg, "--notes");
1304 } else {
1305 for_each_string_list(&rev->notes_opt.extra_notes_refs, get_notes_refs, arg);
1309 static void make_cover_letter(struct rev_info *rev, int use_separate_file,
1310 struct commit *origin,
1311 int nr, struct commit **list,
1312 const char *branch_name,
1313 int quiet)
1315 const char *committer;
1316 struct shortlog log;
1317 struct strbuf sb = STRBUF_INIT;
1318 int i;
1319 const char *encoding = "UTF-8";
1320 int need_8bit_cte = 0;
1321 struct pretty_print_context pp = {0};
1322 struct commit *head = list[0];
1324 if (!cmit_fmt_is_mail(rev->commit_format))
1325 die(_("cover letter needs email format"));
1327 committer = git_committer_info(0);
1329 if (use_separate_file &&
1330 open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1331 die(_("failed to create cover-letter file"));
1333 log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1335 for (i = 0; !need_8bit_cte && i < nr; i++) {
1336 const char *buf = repo_get_commit_buffer(the_repository,
1337 list[i], NULL);
1338 if (has_non_ascii(buf))
1339 need_8bit_cte = 1;
1340 repo_unuse_commit_buffer(the_repository, list[i], buf);
1343 if (!branch_name)
1344 branch_name = find_branch_name(rev);
1346 pp.fmt = CMIT_FMT_EMAIL;
1347 pp.date_mode.type = DATE_RFC2822;
1348 pp.rev = rev;
1349 pp.print_email_subject = 1;
1350 pp_user_info(&pp, NULL, &sb, committer, encoding);
1351 prepare_cover_text(&pp, branch_name, &sb, encoding, need_8bit_cte);
1352 fprintf(rev->diffopt.file, "%s\n", sb.buf);
1354 strbuf_release(&sb);
1356 shortlog_init(&log);
1357 log.wrap_lines = 1;
1358 log.wrap = MAIL_DEFAULT_WRAP;
1359 log.in1 = 2;
1360 log.in2 = 4;
1361 log.file = rev->diffopt.file;
1362 log.groups = SHORTLOG_GROUP_AUTHOR;
1363 shortlog_finish_setup(&log);
1364 for (i = 0; i < nr; i++)
1365 shortlog_add_commit(&log, list[i]);
1367 shortlog_output(&log);
1369 /* We can only do diffstat with a unique reference point */
1370 if (origin)
1371 show_diffstat(rev, origin, head);
1373 if (rev->idiff_oid1) {
1374 fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1375 show_interdiff(rev->idiff_oid1, rev->idiff_oid2, 0,
1376 &rev->diffopt);
1379 if (rev->rdiff1) {
1381 * Pass minimum required diff-options to range-diff; others
1382 * can be added later if deemed desirable.
1384 struct diff_options opts;
1385 struct strvec other_arg = STRVEC_INIT;
1386 struct range_diff_options range_diff_opts = {
1387 .creation_factor = rev->creation_factor,
1388 .dual_color = 1,
1389 .diffopt = &opts,
1390 .other_arg = &other_arg
1393 repo_diff_setup(the_repository, &opts);
1394 opts.file = rev->diffopt.file;
1395 opts.use_color = rev->diffopt.use_color;
1396 diff_setup_done(&opts);
1397 fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1398 get_notes_args(&other_arg, rev);
1399 show_range_diff(rev->rdiff1, rev->rdiff2, &range_diff_opts);
1400 strvec_clear(&other_arg);
1404 static const char *clean_message_id(const char *msg_id)
1406 char ch;
1407 const char *a, *z, *m;
1409 m = msg_id;
1410 while ((ch = *m) && (isspace(ch) || (ch == '<')))
1411 m++;
1412 a = m;
1413 z = NULL;
1414 while ((ch = *m)) {
1415 if (!isspace(ch) && (ch != '>'))
1416 z = m;
1417 m++;
1419 if (!z)
1420 die(_("insane in-reply-to: %s"), msg_id);
1421 if (++z == m)
1422 return a;
1423 return xmemdupz(a, z - a);
1426 static const char *set_outdir(const char *prefix, const char *output_directory)
1428 if (output_directory && is_absolute_path(output_directory))
1429 return output_directory;
1431 if (!prefix || !*prefix) {
1432 if (output_directory)
1433 return output_directory;
1434 /* The user did not explicitly ask for "./" */
1435 outdir_offset = 2;
1436 return "./";
1439 outdir_offset = strlen(prefix);
1440 if (!output_directory)
1441 return prefix;
1443 return prefix_filename(prefix, output_directory);
1446 static const char * const builtin_format_patch_usage[] = {
1447 N_("git format-patch [<options>] [<since> | <revision-range>]"),
1448 NULL
1451 static int keep_subject = 0;
1453 static int keep_callback(const struct option *opt, const char *arg, int unset)
1455 BUG_ON_OPT_NEG(unset);
1456 BUG_ON_OPT_ARG(arg);
1457 ((struct rev_info *)opt->value)->total = -1;
1458 keep_subject = 1;
1459 return 0;
1462 static int subject_prefix = 0;
1464 static int subject_prefix_callback(const struct option *opt, const char *arg,
1465 int unset)
1467 BUG_ON_OPT_NEG(unset);
1468 subject_prefix = 1;
1469 ((struct rev_info *)opt->value)->subject_prefix = arg;
1470 return 0;
1473 static int rfc_callback(const struct option *opt, const char *arg, int unset)
1475 BUG_ON_OPT_NEG(unset);
1476 BUG_ON_OPT_ARG(arg);
1477 return subject_prefix_callback(opt, "RFC PATCH", unset);
1480 static int numbered_cmdline_opt = 0;
1482 static int numbered_callback(const struct option *opt, const char *arg,
1483 int unset)
1485 BUG_ON_OPT_ARG(arg);
1486 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1487 if (unset)
1488 auto_number = 0;
1489 return 0;
1492 static int no_numbered_callback(const struct option *opt, const char *arg,
1493 int unset)
1495 BUG_ON_OPT_NEG(unset);
1496 return numbered_callback(opt, arg, 1);
1499 static int output_directory_callback(const struct option *opt, const char *arg,
1500 int unset)
1502 const char **dir = (const char **)opt->value;
1503 BUG_ON_OPT_NEG(unset);
1504 if (*dir)
1505 die(_("two output directories?"));
1506 *dir = arg;
1507 return 0;
1510 static int thread_callback(const struct option *opt, const char *arg, int unset)
1512 enum thread_level *thread = (enum thread_level *)opt->value;
1513 if (unset)
1514 *thread = THREAD_UNSET;
1515 else if (!arg || !strcmp(arg, "shallow"))
1516 *thread = THREAD_SHALLOW;
1517 else if (!strcmp(arg, "deep"))
1518 *thread = THREAD_DEEP;
1520 * Please update _git_formatpatch() in git-completion.bash
1521 * when you add new options.
1523 else
1524 return 1;
1525 return 0;
1528 static int attach_callback(const struct option *opt, const char *arg, int unset)
1530 struct rev_info *rev = (struct rev_info *)opt->value;
1531 if (unset)
1532 rev->mime_boundary = NULL;
1533 else if (arg)
1534 rev->mime_boundary = arg;
1535 else
1536 rev->mime_boundary = git_version_string;
1537 rev->no_inline = unset ? 0 : 1;
1538 return 0;
1541 static int inline_callback(const struct option *opt, const char *arg, int unset)
1543 struct rev_info *rev = (struct rev_info *)opt->value;
1544 if (unset)
1545 rev->mime_boundary = NULL;
1546 else if (arg)
1547 rev->mime_boundary = arg;
1548 else
1549 rev->mime_boundary = git_version_string;
1550 rev->no_inline = 0;
1551 return 0;
1554 static int header_callback(const struct option *opt, const char *arg, int unset)
1556 if (unset) {
1557 string_list_clear(&extra_hdr, 0);
1558 string_list_clear(&extra_to, 0);
1559 string_list_clear(&extra_cc, 0);
1560 } else {
1561 add_header(arg);
1563 return 0;
1566 static int to_callback(const struct option *opt, const char *arg, int unset)
1568 if (unset)
1569 string_list_clear(&extra_to, 0);
1570 else
1571 string_list_append(&extra_to, arg);
1572 return 0;
1575 static int cc_callback(const struct option *opt, const char *arg, int unset)
1577 if (unset)
1578 string_list_clear(&extra_cc, 0);
1579 else
1580 string_list_append(&extra_cc, arg);
1581 return 0;
1584 static int from_callback(const struct option *opt, const char *arg, int unset)
1586 char **from = opt->value;
1588 free(*from);
1590 if (unset)
1591 *from = NULL;
1592 else if (arg)
1593 *from = xstrdup(arg);
1594 else
1595 *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1596 return 0;
1599 static int base_callback(const struct option *opt, const char *arg, int unset)
1601 const char **base_commit = opt->value;
1603 if (unset) {
1604 auto_base = AUTO_BASE_NEVER;
1605 *base_commit = NULL;
1606 } else if (!strcmp(arg, "auto")) {
1607 auto_base = AUTO_BASE_ALWAYS;
1608 *base_commit = NULL;
1609 } else {
1610 auto_base = AUTO_BASE_NEVER;
1611 *base_commit = arg;
1613 return 0;
1616 struct base_tree_info {
1617 struct object_id base_commit;
1618 int nr_patch_id, alloc_patch_id;
1619 struct object_id *patch_id;
1622 static struct commit *get_base_commit(const char *base_commit,
1623 struct commit **list,
1624 int total)
1626 struct commit *base = NULL;
1627 struct commit **rev;
1628 int i = 0, rev_nr = 0, auto_select, die_on_failure;
1630 switch (auto_base) {
1631 case AUTO_BASE_NEVER:
1632 if (base_commit) {
1633 auto_select = 0;
1634 die_on_failure = 1;
1635 } else {
1636 /* no base information is requested */
1637 return NULL;
1639 break;
1640 case AUTO_BASE_ALWAYS:
1641 case AUTO_BASE_WHEN_ABLE:
1642 if (base_commit) {
1643 BUG("requested automatic base selection but a commit was provided");
1644 } else {
1645 auto_select = 1;
1646 die_on_failure = auto_base == AUTO_BASE_ALWAYS;
1648 break;
1649 default:
1650 BUG("unexpected automatic base selection method");
1653 if (!auto_select) {
1654 base = lookup_commit_reference_by_name(base_commit);
1655 if (!base)
1656 die(_("unknown commit %s"), base_commit);
1657 } else {
1658 struct branch *curr_branch = branch_get(NULL);
1659 const char *upstream = branch_get_upstream(curr_branch, NULL);
1660 if (upstream) {
1661 struct commit_list *base_list;
1662 struct commit *commit;
1663 struct object_id oid;
1665 if (repo_get_oid(the_repository, upstream, &oid)) {
1666 if (die_on_failure)
1667 die(_("failed to resolve '%s' as a valid ref"), upstream);
1668 else
1669 return NULL;
1671 commit = lookup_commit_or_die(&oid, "upstream base");
1672 base_list = repo_get_merge_bases_many(the_repository,
1673 commit, total,
1674 list);
1675 /* There should be one and only one merge base. */
1676 if (!base_list || base_list->next) {
1677 if (die_on_failure) {
1678 die(_("could not find exact merge base"));
1679 } else {
1680 free_commit_list(base_list);
1681 return NULL;
1684 base = base_list->item;
1685 free_commit_list(base_list);
1686 } else {
1687 if (die_on_failure)
1688 die(_("failed to get upstream, if you want to record base commit automatically,\n"
1689 "please use git branch --set-upstream-to to track a remote branch.\n"
1690 "Or you could specify base commit by --base=<base-commit-id> manually"));
1691 else
1692 return NULL;
1696 ALLOC_ARRAY(rev, total);
1697 for (i = 0; i < total; i++)
1698 rev[i] = list[i];
1700 rev_nr = total;
1702 * Get merge base through pair-wise computations
1703 * and store it in rev[0].
1705 while (rev_nr > 1) {
1706 for (i = 0; i < rev_nr / 2; i++) {
1707 struct commit_list *merge_base;
1708 merge_base = repo_get_merge_bases(the_repository,
1709 rev[2 * i],
1710 rev[2 * i + 1]);
1711 if (!merge_base || merge_base->next) {
1712 if (die_on_failure) {
1713 die(_("failed to find exact merge base"));
1714 } else {
1715 free(rev);
1716 return NULL;
1720 rev[i] = merge_base->item;
1723 if (rev_nr % 2)
1724 rev[i] = rev[2 * i];
1725 rev_nr = DIV_ROUND_UP(rev_nr, 2);
1728 if (!repo_in_merge_bases(the_repository, base, rev[0])) {
1729 if (die_on_failure) {
1730 die(_("base commit should be the ancestor of revision list"));
1731 } else {
1732 free(rev);
1733 return NULL;
1737 for (i = 0; i < total; i++) {
1738 if (base == list[i]) {
1739 if (die_on_failure) {
1740 die(_("base commit shouldn't be in revision list"));
1741 } else {
1742 free(rev);
1743 return NULL;
1748 free(rev);
1749 return base;
1752 define_commit_slab(commit_base, int);
1754 static void prepare_bases(struct base_tree_info *bases,
1755 struct commit *base,
1756 struct commit **list,
1757 int total)
1759 struct commit *commit;
1760 struct rev_info revs;
1761 struct diff_options diffopt;
1762 struct commit_base commit_base;
1763 int i;
1765 if (!base)
1766 return;
1768 init_commit_base(&commit_base);
1769 repo_diff_setup(the_repository, &diffopt);
1770 diffopt.flags.recursive = 1;
1771 diff_setup_done(&diffopt);
1773 oidcpy(&bases->base_commit, &base->object.oid);
1775 repo_init_revisions(the_repository, &revs, NULL);
1776 revs.max_parents = 1;
1777 revs.topo_order = 1;
1778 for (i = 0; i < total; i++) {
1779 list[i]->object.flags &= ~UNINTERESTING;
1780 add_pending_object(&revs, &list[i]->object, "rev_list");
1781 *commit_base_at(&commit_base, list[i]) = 1;
1783 base->object.flags |= UNINTERESTING;
1784 add_pending_object(&revs, &base->object, "base");
1786 if (prepare_revision_walk(&revs))
1787 die(_("revision walk setup failed"));
1789 * Traverse the commits list, get prerequisite patch ids
1790 * and stuff them in bases structure.
1792 while ((commit = get_revision(&revs)) != NULL) {
1793 struct object_id oid;
1794 struct object_id *patch_id;
1795 if (*commit_base_at(&commit_base, commit))
1796 continue;
1797 if (commit_patch_id(commit, &diffopt, &oid, 0))
1798 die(_("cannot get patch id"));
1799 ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1800 patch_id = bases->patch_id + bases->nr_patch_id;
1801 oidcpy(patch_id, &oid);
1802 bases->nr_patch_id++;
1804 clear_commit_base(&commit_base);
1807 static void print_bases(struct base_tree_info *bases, FILE *file)
1809 int i;
1811 /* Only do this once, either for the cover or for the first one */
1812 if (is_null_oid(&bases->base_commit))
1813 return;
1815 /* Show the base commit */
1816 fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1818 /* Show the prerequisite patches */
1819 for (i = bases->nr_patch_id - 1; i >= 0; i--)
1820 fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1822 free(bases->patch_id);
1823 bases->nr_patch_id = 0;
1824 bases->alloc_patch_id = 0;
1825 oidclr(&bases->base_commit);
1828 static const char *diff_title(struct strbuf *sb,
1829 const char *reroll_count,
1830 const char *generic,
1831 const char *rerolled)
1833 int v;
1835 /* RFC may be v0, so allow -v1 to diff against v0 */
1836 if (reroll_count && !strtol_i(reroll_count, 10, &v) &&
1837 v >= 1)
1838 strbuf_addf(sb, rerolled, v - 1);
1839 else
1840 strbuf_addstr(sb, generic);
1841 return sb->buf;
1844 static void infer_range_diff_ranges(struct strbuf *r1,
1845 struct strbuf *r2,
1846 const char *prev,
1847 struct commit *origin,
1848 struct commit *head)
1850 const char *head_oid = oid_to_hex(&head->object.oid);
1851 int prev_is_range = is_range_diff_range(prev);
1853 if (prev_is_range)
1854 strbuf_addstr(r1, prev);
1855 else
1856 strbuf_addf(r1, "%s..%s", head_oid, prev);
1858 if (origin)
1859 strbuf_addf(r2, "%s..%s", oid_to_hex(&origin->object.oid), head_oid);
1860 else if (prev_is_range)
1861 die(_("failed to infer range-diff origin of current series"));
1862 else {
1863 warning(_("using '%s' as range-diff origin of current series"), prev);
1864 strbuf_addf(r2, "%s..%s", prev, head_oid);
1868 int cmd_format_patch(int argc, const char **argv, const char *prefix)
1870 struct commit *commit;
1871 struct commit **list = NULL;
1872 struct rev_info rev;
1873 char *to_free = NULL;
1874 struct setup_revision_opt s_r_opt;
1875 int nr = 0, total, i;
1876 int use_stdout = 0;
1877 int start_number = -1;
1878 int just_numbers = 0;
1879 int ignore_if_in_upstream = 0;
1880 int cover_letter = -1;
1881 int boundary_count = 0;
1882 int no_binary_diff = 0;
1883 int zero_commit = 0;
1884 struct commit *origin = NULL;
1885 const char *in_reply_to = NULL;
1886 struct patch_ids ids;
1887 struct strbuf buf = STRBUF_INIT;
1888 int use_patch_format = 0;
1889 int quiet = 0;
1890 const char *reroll_count = NULL;
1891 char *cover_from_description_arg = NULL;
1892 char *branch_name = NULL;
1893 char *base_commit = NULL;
1894 struct base_tree_info bases;
1895 struct commit *base;
1896 int show_progress = 0;
1897 struct progress *progress = NULL;
1898 struct oid_array idiff_prev = OID_ARRAY_INIT;
1899 struct strbuf idiff_title = STRBUF_INIT;
1900 const char *rdiff_prev = NULL;
1901 struct strbuf rdiff1 = STRBUF_INIT;
1902 struct strbuf rdiff2 = STRBUF_INIT;
1903 struct strbuf rdiff_title = STRBUF_INIT;
1904 struct strbuf sprefix = STRBUF_INIT;
1905 int creation_factor = -1;
1907 const struct option builtin_format_patch_options[] = {
1908 OPT_CALLBACK_F('n', "numbered", &numbered, NULL,
1909 N_("use [PATCH n/m] even with a single patch"),
1910 PARSE_OPT_NOARG, numbered_callback),
1911 OPT_CALLBACK_F('N', "no-numbered", &numbered, NULL,
1912 N_("use [PATCH] even with multiple patches"),
1913 PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback),
1914 OPT_BOOL('s', "signoff", &do_signoff, N_("add a Signed-off-by trailer")),
1915 OPT_BOOL(0, "stdout", &use_stdout,
1916 N_("print patches to standard out")),
1917 OPT_BOOL(0, "cover-letter", &cover_letter,
1918 N_("generate a cover letter")),
1919 OPT_BOOL(0, "numbered-files", &just_numbers,
1920 N_("use simple number sequence for output file names")),
1921 OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
1922 N_("use <sfx> instead of '.patch'")),
1923 OPT_INTEGER(0, "start-number", &start_number,
1924 N_("start numbering patches at <n> instead of 1")),
1925 OPT_STRING('v', "reroll-count", &reroll_count, N_("reroll-count"),
1926 N_("mark the series as Nth re-roll")),
1927 OPT_INTEGER(0, "filename-max-length", &fmt_patch_name_max,
1928 N_("max length of output filename")),
1929 OPT_CALLBACK_F(0, "rfc", &rev, NULL,
1930 N_("use [RFC PATCH] instead of [PATCH]"),
1931 PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback),
1932 OPT_STRING(0, "cover-from-description", &cover_from_description_arg,
1933 N_("cover-from-description-mode"),
1934 N_("generate parts of a cover letter based on a branch's description")),
1935 OPT_CALLBACK_F(0, "subject-prefix", &rev, N_("prefix"),
1936 N_("use [<prefix>] instead of [PATCH]"),
1937 PARSE_OPT_NONEG, subject_prefix_callback),
1938 OPT_CALLBACK_F('o', "output-directory", &output_directory,
1939 N_("dir"), N_("store resulting files in <dir>"),
1940 PARSE_OPT_NONEG, output_directory_callback),
1941 OPT_CALLBACK_F('k', "keep-subject", &rev, NULL,
1942 N_("don't strip/add [PATCH]"),
1943 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback),
1944 OPT_BOOL(0, "no-binary", &no_binary_diff,
1945 N_("don't output binary diffs")),
1946 OPT_BOOL(0, "zero-commit", &zero_commit,
1947 N_("output all-zero hash in From header")),
1948 OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1949 N_("don't include a patch matching a commit upstream")),
1950 OPT_SET_INT_F('p', "no-stat", &use_patch_format,
1951 N_("show patch format instead of default (patch + stat)"),
1952 1, PARSE_OPT_NONEG),
1953 OPT_GROUP(N_("Messaging")),
1954 OPT_CALLBACK(0, "add-header", NULL, N_("header"),
1955 N_("add email header"), header_callback),
1956 OPT_CALLBACK(0, "to", NULL, N_("email"), N_("add To: header"), to_callback),
1957 OPT_CALLBACK(0, "cc", NULL, N_("email"), N_("add Cc: header"), cc_callback),
1958 OPT_CALLBACK_F(0, "from", &from, N_("ident"),
1959 N_("set From address to <ident> (or committer ident if absent)"),
1960 PARSE_OPT_OPTARG, from_callback),
1961 OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
1962 N_("make first mail a reply to <message-id>")),
1963 OPT_CALLBACK_F(0, "attach", &rev, N_("boundary"),
1964 N_("attach the patch"), PARSE_OPT_OPTARG,
1965 attach_callback),
1966 OPT_CALLBACK_F(0, "inline", &rev, N_("boundary"),
1967 N_("inline the patch"),
1968 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1969 inline_callback),
1970 OPT_CALLBACK_F(0, "thread", &thread, N_("style"),
1971 N_("enable message threading, styles: shallow, deep"),
1972 PARSE_OPT_OPTARG, thread_callback),
1973 OPT_STRING(0, "signature", &signature, N_("signature"),
1974 N_("add a signature")),
1975 OPT_CALLBACK_F(0, "base", &base_commit, N_("base-commit"),
1976 N_("add prerequisite tree info to the patch series"),
1977 0, base_callback),
1978 OPT_FILENAME(0, "signature-file", &signature_file,
1979 N_("add a signature from a file")),
1980 OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1981 OPT_BOOL(0, "progress", &show_progress,
1982 N_("show progress while generating patches")),
1983 OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
1984 N_("show changes against <rev> in cover letter or single patch"),
1985 parse_opt_object_name),
1986 OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
1987 N_("show changes against <refspec> in cover letter or single patch")),
1988 OPT_INTEGER(0, "creation-factor", &creation_factor,
1989 N_("percentage by which creation is weighted")),
1990 OPT_BOOL(0, "force-in-body-from", &force_in_body_from,
1991 N_("show in-body From: even if identical to the e-mail header")),
1992 OPT_END()
1995 extra_hdr.strdup_strings = 1;
1996 extra_to.strdup_strings = 1;
1997 extra_cc.strdup_strings = 1;
1999 init_log_defaults();
2000 init_display_notes(&notes_opt);
2001 git_config(git_format_config, NULL);
2002 repo_init_revisions(the_repository, &rev, prefix);
2003 git_config(grep_config, &rev.grep_filter);
2005 rev.show_notes = show_notes;
2006 memcpy(&rev.notes_opt, &notes_opt, sizeof(notes_opt));
2007 rev.commit_format = CMIT_FMT_EMAIL;
2008 rev.encode_email_headers = default_encode_email_headers;
2009 rev.expand_tabs_in_log_default = 0;
2010 rev.verbose_header = 1;
2011 rev.diff = 1;
2012 rev.max_parents = 1;
2013 rev.diffopt.flags.recursive = 1;
2014 rev.diffopt.no_free = 1;
2015 rev.subject_prefix = fmt_patch_subject_prefix;
2016 memset(&s_r_opt, 0, sizeof(s_r_opt));
2017 s_r_opt.def = "HEAD";
2018 s_r_opt.revarg_opt = REVARG_COMMITTISH;
2020 if (format_no_prefix)
2021 diff_set_noprefix(&rev.diffopt);
2023 if (default_attach) {
2024 rev.mime_boundary = default_attach;
2025 rev.no_inline = 1;
2029 * Parse the arguments before setup_revisions(), or something
2030 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
2031 * possibly a valid SHA1.
2033 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
2034 builtin_format_patch_usage,
2035 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
2036 PARSE_OPT_KEEP_DASHDASH);
2038 rev.force_in_body_from = force_in_body_from;
2040 /* Make sure "0000-$sub.patch" gives non-negative length for $sub */
2041 if (fmt_patch_name_max <= strlen("0000-") + strlen(fmt_patch_suffix))
2042 fmt_patch_name_max = strlen("0000-") + strlen(fmt_patch_suffix);
2044 if (cover_from_description_arg)
2045 cover_from_description_mode = parse_cover_from_description(cover_from_description_arg);
2047 if (reroll_count) {
2048 strbuf_addf(&sprefix, "%s v%s",
2049 rev.subject_prefix, reroll_count);
2050 rev.reroll_count = reroll_count;
2051 rev.subject_prefix = sprefix.buf;
2054 for (i = 0; i < extra_hdr.nr; i++) {
2055 strbuf_addstr(&buf, extra_hdr.items[i].string);
2056 strbuf_addch(&buf, '\n');
2059 if (extra_to.nr)
2060 strbuf_addstr(&buf, "To: ");
2061 for (i = 0; i < extra_to.nr; i++) {
2062 if (i)
2063 strbuf_addstr(&buf, " ");
2064 strbuf_addstr(&buf, extra_to.items[i].string);
2065 if (i + 1 < extra_to.nr)
2066 strbuf_addch(&buf, ',');
2067 strbuf_addch(&buf, '\n');
2070 if (extra_cc.nr)
2071 strbuf_addstr(&buf, "Cc: ");
2072 for (i = 0; i < extra_cc.nr; i++) {
2073 if (i)
2074 strbuf_addstr(&buf, " ");
2075 strbuf_addstr(&buf, extra_cc.items[i].string);
2076 if (i + 1 < extra_cc.nr)
2077 strbuf_addch(&buf, ',');
2078 strbuf_addch(&buf, '\n');
2081 rev.extra_headers = to_free = strbuf_detach(&buf, NULL);
2083 if (from) {
2084 if (split_ident_line(&rev.from_ident, from, strlen(from)))
2085 die(_("invalid ident line: %s"), from);
2088 if (start_number < 0)
2089 start_number = 1;
2092 * If numbered is set solely due to format.numbered in config,
2093 * and it would conflict with --keep-subject (-k) from the
2094 * command line, reset "numbered".
2096 if (numbered && keep_subject && !numbered_cmdline_opt)
2097 numbered = 0;
2099 if (numbered && keep_subject)
2100 die(_("options '%s' and '%s' cannot be used together"), "-n", "-k");
2101 if (keep_subject && subject_prefix)
2102 die(_("options '%s' and '%s' cannot be used together"), "--subject-prefix/--rfc", "-k");
2103 rev.preserve_subject = keep_subject;
2105 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
2106 if (argc > 1)
2107 die(_("unrecognized argument: %s"), argv[1]);
2109 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
2110 die(_("--name-only does not make sense"));
2111 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
2112 die(_("--name-status does not make sense"));
2113 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
2114 die(_("--check does not make sense"));
2115 if (rev.remerge_diff)
2116 die(_("--remerge-diff does not make sense"));
2118 if (!use_patch_format &&
2119 (!rev.diffopt.output_format ||
2120 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
2121 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
2122 if (!rev.diffopt.stat_width)
2123 rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
2125 /* Always generate a patch */
2126 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
2127 rev.always_show_header = 1;
2129 rev.zero_commit = zero_commit;
2130 rev.patch_name_max = fmt_patch_name_max;
2132 if (!rev.diffopt.flags.text && !no_binary_diff)
2133 rev.diffopt.flags.binary = 1;
2135 if (rev.show_notes)
2136 load_display_notes(&rev.notes_opt);
2138 die_for_incompatible_opt3(use_stdout, "--stdout",
2139 rev.diffopt.close_file, "--output",
2140 !!output_directory, "--output-directory");
2142 if (use_stdout && stdout_mboxrd)
2143 rev.commit_format = CMIT_FMT_MBOXRD;
2145 if (use_stdout) {
2146 setup_pager();
2147 } else if (!rev.diffopt.close_file) {
2148 int saved;
2150 if (!output_directory)
2151 output_directory = config_output_directory;
2152 output_directory = set_outdir(prefix, output_directory);
2154 if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
2155 rev.diffopt.use_color = GIT_COLOR_NEVER;
2157 * We consider <outdir> as 'outside of gitdir', therefore avoid
2158 * applying adjust_shared_perm in s-c-l-d.
2160 saved = get_shared_repository();
2161 set_shared_repository(0);
2162 switch (safe_create_leading_directories_const(output_directory)) {
2163 case SCLD_OK:
2164 case SCLD_EXISTS:
2165 break;
2166 default:
2167 die(_("could not create leading directories "
2168 "of '%s'"), output_directory);
2170 set_shared_repository(saved);
2171 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
2172 die_errno(_("could not create directory '%s'"),
2173 output_directory);
2176 if (rev.pending.nr == 1) {
2177 int check_head = 0;
2179 if (rev.max_count < 0 && !rev.show_root_diff) {
2181 * This is traditional behaviour of "git format-patch
2182 * origin" that prepares what the origin side still
2183 * does not have.
2185 rev.pending.objects[0].item->flags |= UNINTERESTING;
2186 add_head_to_pending(&rev);
2187 check_head = 1;
2190 * Otherwise, it is "format-patch -22 HEAD", and/or
2191 * "format-patch --root HEAD". The user wants
2192 * get_revision() to do the usual traversal.
2195 if (!strcmp(rev.pending.objects[0].name, "HEAD"))
2196 check_head = 1;
2198 if (check_head) {
2199 const char *ref, *v;
2200 ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2201 NULL, NULL);
2202 if (ref && skip_prefix(ref, "refs/heads/", &v))
2203 branch_name = xstrdup(v);
2204 else
2205 branch_name = xstrdup(""); /* no branch */
2210 * We cannot move this anywhere earlier because we do want to
2211 * know if --root was given explicitly from the command line.
2213 rev.show_root_diff = 1;
2215 if (ignore_if_in_upstream) {
2216 /* Don't say anything if head and upstream are the same. */
2217 if (rev.pending.nr == 2) {
2218 struct object_array_entry *o = rev.pending.objects;
2219 if (oideq(&o[0].item->oid, &o[1].item->oid))
2220 goto done;
2222 get_patch_ids(&rev, &ids);
2225 if (prepare_revision_walk(&rev))
2226 die(_("revision walk setup failed"));
2227 rev.boundary = 1;
2228 while ((commit = get_revision(&rev)) != NULL) {
2229 if (commit->object.flags & BOUNDARY) {
2230 boundary_count++;
2231 origin = (boundary_count == 1) ? commit : NULL;
2232 continue;
2235 if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
2236 continue;
2238 nr++;
2239 REALLOC_ARRAY(list, nr);
2240 list[nr - 1] = commit;
2242 if (nr == 0)
2243 /* nothing to do */
2244 goto done;
2245 total = nr;
2246 if (cover_letter == -1) {
2247 if (config_cover_letter == COVER_AUTO)
2248 cover_letter = (total > 1);
2249 else
2250 cover_letter = (config_cover_letter == COVER_ON);
2252 if (!keep_subject && auto_number && (total > 1 || cover_letter))
2253 numbered = 1;
2254 if (numbered)
2255 rev.total = total + start_number - 1;
2257 if (idiff_prev.nr) {
2258 if (!cover_letter && total != 1)
2259 die(_("--interdiff requires --cover-letter or single patch"));
2260 rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
2261 rev.idiff_oid2 = get_commit_tree_oid(list[0]);
2262 rev.idiff_title = diff_title(&idiff_title, reroll_count,
2263 _("Interdiff:"),
2264 _("Interdiff against v%d:"));
2267 if (creation_factor < 0)
2268 creation_factor = RANGE_DIFF_CREATION_FACTOR_DEFAULT;
2269 else if (!rdiff_prev)
2270 die(_("the option '%s' requires '%s'"), "--creation-factor", "--range-diff");
2272 if (rdiff_prev) {
2273 if (!cover_letter && total != 1)
2274 die(_("--range-diff requires --cover-letter or single patch"));
2276 infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
2277 origin, list[0]);
2278 rev.rdiff1 = rdiff1.buf;
2279 rev.rdiff2 = rdiff2.buf;
2280 rev.creation_factor = creation_factor;
2281 rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
2282 _("Range-diff:"),
2283 _("Range-diff against v%d:"));
2286 if (!signature) {
2287 ; /* --no-signature inhibits all signatures */
2288 } else if (signature && signature != git_version_string) {
2289 ; /* non-default signature already set */
2290 } else if (signature_file) {
2291 struct strbuf buf = STRBUF_INIT;
2293 if (strbuf_read_file(&buf, signature_file, 128) < 0)
2294 die_errno(_("unable to read signature file '%s'"), signature_file);
2295 signature = strbuf_detach(&buf, NULL);
2298 memset(&bases, 0, sizeof(bases));
2299 base = get_base_commit(base_commit, list, nr);
2300 if (base) {
2301 reset_revision_walk();
2302 clear_object_flags(UNINTERESTING);
2303 prepare_bases(&bases, base, list, nr);
2306 if (in_reply_to || thread || cover_letter) {
2307 rev.ref_message_ids = xmalloc(sizeof(*rev.ref_message_ids));
2308 string_list_init_nodup(rev.ref_message_ids);
2310 if (in_reply_to) {
2311 const char *msgid = clean_message_id(in_reply_to);
2312 string_list_append(rev.ref_message_ids, msgid);
2314 rev.numbered_files = just_numbers;
2315 rev.patch_suffix = fmt_patch_suffix;
2316 if (cover_letter) {
2317 if (thread)
2318 gen_message_id(&rev, "cover");
2319 make_cover_letter(&rev, !!output_directory,
2320 origin, nr, list, branch_name, quiet);
2321 print_bases(&bases, rev.diffopt.file);
2322 print_signature(rev.diffopt.file);
2323 total++;
2324 start_number--;
2325 /* interdiff/range-diff in cover-letter; omit from patches */
2326 rev.idiff_oid1 = NULL;
2327 rev.rdiff1 = NULL;
2329 rev.add_signoff = do_signoff;
2331 if (show_progress)
2332 progress = start_delayed_progress(_("Generating patches"), total);
2333 while (0 <= --nr) {
2334 int shown;
2335 display_progress(progress, total - nr);
2336 commit = list[nr];
2337 rev.nr = total - nr + (start_number - 1);
2338 /* Make the second and subsequent mails replies to the first */
2339 if (thread) {
2340 /* Have we already had a message ID? */
2341 if (rev.message_id) {
2343 * For deep threading: make every mail
2344 * a reply to the previous one, no
2345 * matter what other options are set.
2347 * For shallow threading:
2349 * Without --cover-letter and
2350 * --in-reply-to, make every mail a
2351 * reply to the one before.
2353 * With --in-reply-to but no
2354 * --cover-letter, make every mail a
2355 * reply to the <reply-to>.
2357 * With --cover-letter, make every
2358 * mail but the cover letter a reply
2359 * to the cover letter. The cover
2360 * letter is a reply to the
2361 * --in-reply-to, if specified.
2363 if (thread == THREAD_SHALLOW
2364 && rev.ref_message_ids->nr > 0
2365 && (!cover_letter || rev.nr > 1))
2366 free(rev.message_id);
2367 else
2368 string_list_append(rev.ref_message_ids,
2369 rev.message_id);
2371 gen_message_id(&rev, oid_to_hex(&commit->object.oid));
2374 if (output_directory &&
2375 open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
2376 die(_("failed to create output files"));
2377 shown = log_tree_commit(&rev, commit);
2378 free_commit_buffer(the_repository->parsed_objects,
2379 commit);
2381 /* We put one extra blank line between formatted
2382 * patches and this flag is used by log-tree code
2383 * to see if it needs to emit a LF before showing
2384 * the log; when using one file per patch, we do
2385 * not want the extra blank line.
2387 if (output_directory)
2388 rev.shown_one = 0;
2389 if (shown) {
2390 print_bases(&bases, rev.diffopt.file);
2391 if (rev.mime_boundary)
2392 fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
2393 mime_boundary_leader,
2394 rev.mime_boundary);
2395 else
2396 print_signature(rev.diffopt.file);
2398 if (output_directory)
2399 fclose(rev.diffopt.file);
2401 stop_progress(&progress);
2402 free(list);
2403 free(branch_name);
2404 string_list_clear(&extra_to, 0);
2405 string_list_clear(&extra_cc, 0);
2406 string_list_clear(&extra_hdr, 0);
2407 if (ignore_if_in_upstream)
2408 free_patch_ids(&ids);
2410 done:
2411 oid_array_clear(&idiff_prev);
2412 strbuf_release(&idiff_title);
2413 strbuf_release(&rdiff1);
2414 strbuf_release(&rdiff2);
2415 strbuf_release(&rdiff_title);
2416 strbuf_release(&sprefix);
2417 free(to_free);
2418 if (rev.ref_message_ids)
2419 string_list_clear(rev.ref_message_ids, 0);
2420 free(rev.ref_message_ids);
2421 return cmd_log_deinit(0, &rev);
2424 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
2426 struct object_id oid;
2427 if (repo_get_oid(the_repository, arg, &oid) == 0) {
2428 struct commit *commit = lookup_commit_reference(the_repository,
2429 &oid);
2430 if (commit) {
2431 commit->object.flags |= flags;
2432 add_pending_object(revs, &commit->object, arg);
2433 return 0;
2436 return -1;
2439 static const char * const cherry_usage[] = {
2440 N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
2441 NULL
2444 static void print_commit(char sign, struct commit *commit, int verbose,
2445 int abbrev, FILE *file)
2447 if (!verbose) {
2448 fprintf(file, "%c %s\n", sign,
2449 repo_find_unique_abbrev(the_repository, &commit->object.oid, abbrev));
2450 } else {
2451 struct strbuf buf = STRBUF_INIT;
2452 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2453 fprintf(file, "%c %s %s\n", sign,
2454 repo_find_unique_abbrev(the_repository, &commit->object.oid, abbrev),
2455 buf.buf);
2456 strbuf_release(&buf);
2460 int cmd_cherry(int argc, const char **argv, const char *prefix)
2462 struct rev_info revs;
2463 struct patch_ids ids;
2464 struct commit *commit;
2465 struct commit_list *list = NULL;
2466 struct branch *current_branch;
2467 const char *upstream;
2468 const char *head = "HEAD";
2469 const char *limit = NULL;
2470 int verbose = 0, abbrev = 0;
2472 struct option options[] = {
2473 OPT__ABBREV(&abbrev),
2474 OPT__VERBOSE(&verbose, N_("be verbose")),
2475 OPT_END()
2478 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
2480 switch (argc) {
2481 case 3:
2482 limit = argv[2];
2483 /* FALLTHROUGH */
2484 case 2:
2485 head = argv[1];
2486 /* FALLTHROUGH */
2487 case 1:
2488 upstream = argv[0];
2489 break;
2490 default:
2491 current_branch = branch_get(NULL);
2492 upstream = branch_get_upstream(current_branch, NULL);
2493 if (!upstream) {
2494 fprintf(stderr, _("Could not find a tracked"
2495 " remote branch, please"
2496 " specify <upstream> manually.\n"));
2497 usage_with_options(cherry_usage, options);
2501 repo_init_revisions(the_repository, &revs, prefix);
2502 revs.max_parents = 1;
2504 if (add_pending_commit(head, &revs, 0))
2505 die(_("unknown commit %s"), head);
2506 if (add_pending_commit(upstream, &revs, UNINTERESTING))
2507 die(_("unknown commit %s"), upstream);
2509 /* Don't say anything if head and upstream are the same. */
2510 if (revs.pending.nr == 2) {
2511 struct object_array_entry *o = revs.pending.objects;
2512 if (oideq(&o[0].item->oid, &o[1].item->oid))
2513 return 0;
2516 get_patch_ids(&revs, &ids);
2518 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2519 die(_("unknown commit %s"), limit);
2521 /* reverse the list of commits */
2522 if (prepare_revision_walk(&revs))
2523 die(_("revision walk setup failed"));
2524 while ((commit = get_revision(&revs)) != NULL) {
2525 commit_list_insert(commit, &list);
2528 while (list) {
2529 char sign = '+';
2531 commit = list->item;
2532 if (has_commit_patch_id(commit, &ids))
2533 sign = '-';
2534 print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2535 list = list->next;
2538 free_patch_ids(&ids);
2539 return 0;