t5619: GETTEXT_POISON fix
[git.git] / builtin / log.c
blobf23ccdbec3263dffe87666baed28c7f0cdb76047
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 "revision.h"
16 #include "log-tree.h"
17 #include "builtin.h"
18 #include "tag.h"
19 #include "reflog-walk.h"
20 #include "patch-ids.h"
21 #include "run-command.h"
22 #include "shortlog.h"
23 #include "remote.h"
24 #include "string-list.h"
25 #include "parse-options.h"
26 #include "line-log.h"
27 #include "branch.h"
28 #include "streaming.h"
29 #include "version.h"
30 #include "mailmap.h"
31 #include "gpg-interface.h"
32 #include "progress.h"
33 #include "commit-slab.h"
34 #include "repository.h"
35 #include "commit-reach.h"
36 #include "range-diff.h"
38 #define MAIL_DEFAULT_WRAP 72
39 #define COVER_FROM_AUTO_MAX_SUBJECT_LEN 100
40 #define FORMAT_PATCH_NAME_MAX_DEFAULT 64
42 /* Set a default date-time format for git log ("log.date" config variable) */
43 static const char *default_date_mode = NULL;
45 static int default_abbrev_commit;
46 static int default_show_root = 1;
47 static int default_follow;
48 static int default_show_signature;
49 static int default_encode_email_headers = 1;
50 static int decoration_style;
51 static int decoration_given;
52 static int use_mailmap_config = 1;
53 static const char *fmt_patch_subject_prefix = "PATCH";
54 static int fmt_patch_name_max = FORMAT_PATCH_NAME_MAX_DEFAULT;
55 static const char *fmt_pretty;
57 static const char * const builtin_log_usage[] = {
58 N_("git log [<options>] [<revision-range>] [[--] <path>...]"),
59 N_("git show [<options>] <object>..."),
60 NULL
63 struct line_opt_callback_data {
64 struct rev_info *rev;
65 const char *prefix;
66 struct string_list args;
69 static int session_is_interactive(void)
71 return isatty(1) || pager_in_use();
74 static int auto_decoration_style(void)
76 return session_is_interactive() ? DECORATE_SHORT_REFS : 0;
79 static int parse_decoration_style(const char *value)
81 switch (git_parse_maybe_bool(value)) {
82 case 1:
83 return DECORATE_SHORT_REFS;
84 case 0:
85 return 0;
86 default:
87 break;
89 if (!strcmp(value, "full"))
90 return DECORATE_FULL_REFS;
91 else if (!strcmp(value, "short"))
92 return DECORATE_SHORT_REFS;
93 else if (!strcmp(value, "auto"))
94 return auto_decoration_style();
96 * Please update _git_log() in git-completion.bash when you
97 * add new decoration styles.
99 return -1;
102 static int decorate_callback(const struct option *opt, const char *arg, int unset)
104 if (unset)
105 decoration_style = 0;
106 else if (arg)
107 decoration_style = parse_decoration_style(arg);
108 else
109 decoration_style = DECORATE_SHORT_REFS;
111 if (decoration_style < 0)
112 die(_("invalid --decorate option: %s"), arg);
114 decoration_given = 1;
116 return 0;
119 static int log_line_range_callback(const struct option *option, const char *arg, int unset)
121 struct line_opt_callback_data *data = option->value;
123 BUG_ON_OPT_NEG(unset);
125 if (!arg)
126 return -1;
128 data->rev->line_level_traverse = 1;
129 string_list_append(&data->args, arg);
131 return 0;
134 static void init_log_defaults(void)
136 init_diff_ui_defaults();
138 decoration_style = auto_decoration_style();
141 static void cmd_log_init_defaults(struct rev_info *rev)
143 if (fmt_pretty)
144 get_commit_format(fmt_pretty, rev);
145 if (default_follow)
146 rev->diffopt.flags.default_follow_renames = 1;
147 rev->verbose_header = 1;
148 rev->diffopt.flags.recursive = 1;
149 rev->diffopt.stat_width = -1; /* use full terminal width */
150 rev->diffopt.stat_graph_width = -1; /* respect statGraphWidth config */
151 rev->abbrev_commit = default_abbrev_commit;
152 rev->show_root_diff = default_show_root;
153 rev->subject_prefix = fmt_patch_subject_prefix;
154 rev->patch_name_max = fmt_patch_name_max;
155 rev->show_signature = default_show_signature;
156 rev->encode_email_headers = default_encode_email_headers;
157 rev->diffopt.flags.allow_textconv = 1;
159 if (default_date_mode)
160 parse_date_format(default_date_mode, &rev->date_mode);
163 static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
164 struct rev_info *rev, struct setup_revision_opt *opt)
166 struct userformat_want w;
167 int quiet = 0, source = 0, mailmap;
168 static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
169 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
170 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
171 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
172 struct decoration_filter decoration_filter = {&decorate_refs_include,
173 &decorate_refs_exclude,
174 &decorate_refs_exclude_config};
175 static struct revision_sources revision_sources;
177 const struct option builtin_log_options[] = {
178 OPT__QUIET(&quiet, N_("suppress diff output")),
179 OPT_BOOL(0, "source", &source, N_("show source")),
180 OPT_BOOL(0, "use-mailmap", &mailmap, N_("use mail map file")),
181 OPT_ALIAS(0, "mailmap", "use-mailmap"),
182 OPT_STRING_LIST(0, "decorate-refs", &decorate_refs_include,
183 N_("pattern"), N_("only decorate refs that match <pattern>")),
184 OPT_STRING_LIST(0, "decorate-refs-exclude", &decorate_refs_exclude,
185 N_("pattern"), N_("do not decorate refs that match <pattern>")),
186 OPT_CALLBACK_F(0, "decorate", NULL, NULL, N_("decorate options"),
187 PARSE_OPT_OPTARG, decorate_callback),
188 OPT_CALLBACK('L', NULL, &line_cb, "range:file",
189 N_("trace the evolution of line range <start>,<end> or function :<funcname> in <file>"),
190 log_line_range_callback),
191 OPT_END()
194 line_cb.rev = rev;
195 line_cb.prefix = prefix;
197 mailmap = use_mailmap_config;
198 argc = parse_options(argc, argv, prefix,
199 builtin_log_options, builtin_log_usage,
200 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
201 PARSE_OPT_KEEP_DASHDASH);
203 if (quiet)
204 rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
205 argc = setup_revisions(argc, argv, rev, opt);
207 /* Any arguments at this point are not recognized */
208 if (argc > 1)
209 die(_("unrecognized argument: %s"), argv[1]);
211 if (rev->line_level_traverse && rev->prune_data.nr)
212 die(_("-L<range>:<file> cannot be used with pathspec"));
214 memset(&w, 0, sizeof(w));
215 userformat_find_requirements(NULL, &w);
217 if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
218 rev->show_notes = 1;
219 if (rev->show_notes)
220 load_display_notes(&rev->notes_opt);
222 if ((rev->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
223 rev->diffopt.filter || rev->diffopt.flags.follow_renames)
224 rev->always_show_header = 0;
226 if (source || w.source) {
227 init_revision_sources(&revision_sources);
228 rev->sources = &revision_sources;
231 if (mailmap) {
232 rev->mailmap = xcalloc(1, sizeof(struct string_list));
233 read_mailmap(rev->mailmap, NULL);
236 if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
238 * "log --pretty=raw" is special; ignore UI oriented
239 * configuration variables such as decoration.
241 if (!decoration_given)
242 decoration_style = 0;
243 if (!rev->abbrev_commit_given)
244 rev->abbrev_commit = 0;
247 if (decoration_style) {
248 const struct string_list *config_exclude =
249 repo_config_get_value_multi(the_repository,
250 "log.excludeDecoration");
252 if (config_exclude) {
253 struct string_list_item *item;
254 for_each_string_list_item(item, config_exclude)
255 string_list_append(&decorate_refs_exclude_config,
256 item->string);
259 rev->show_decorations = 1;
261 load_ref_decorations(&decoration_filter, decoration_style);
264 if (rev->line_level_traverse)
265 line_log_init(rev, line_cb.prefix, &line_cb.args);
267 setup_pager();
270 static void cmd_log_init(int argc, const char **argv, const char *prefix,
271 struct rev_info *rev, struct setup_revision_opt *opt)
273 cmd_log_init_defaults(rev);
274 cmd_log_init_finish(argc, argv, prefix, rev, opt);
278 * This gives a rough estimate for how many commits we
279 * will print out in the list.
281 static int estimate_commit_count(struct commit_list *list)
283 int n = 0;
285 while (list) {
286 struct commit *commit = list->item;
287 unsigned int flags = commit->object.flags;
288 list = list->next;
289 if (!(flags & (TREESAME | UNINTERESTING)))
290 n++;
292 return n;
295 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
297 if (rev->shown_one) {
298 rev->shown_one = 0;
299 if (rev->commit_format != CMIT_FMT_ONELINE)
300 putchar(rev->diffopt.line_termination);
302 fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
305 static struct itimerval early_output_timer;
307 static void log_show_early(struct rev_info *revs, struct commit_list *list)
309 int i = revs->early_output, close_file = revs->diffopt.close_file;
310 int show_header = 1;
312 revs->diffopt.close_file = 0;
313 sort_in_topological_order(&list, revs->sort_order);
314 while (list && i) {
315 struct commit *commit = list->item;
316 switch (simplify_commit(revs, commit)) {
317 case commit_show:
318 if (show_header) {
319 int n = estimate_commit_count(list);
320 show_early_header(revs, "incomplete", n);
321 show_header = 0;
323 log_tree_commit(revs, commit);
324 i--;
325 break;
326 case commit_ignore:
327 break;
328 case commit_error:
329 if (close_file)
330 fclose(revs->diffopt.file);
331 return;
333 list = list->next;
336 /* Did we already get enough commits for the early output? */
337 if (!i) {
338 if (close_file)
339 fclose(revs->diffopt.file);
340 return;
344 * ..if no, then repeat it twice a second until we
345 * do.
347 * NOTE! We don't use "it_interval", because if the
348 * reader isn't listening, we want our output to be
349 * throttled by the writing, and not have the timer
350 * trigger every second even if we're blocked on a
351 * reader!
353 early_output_timer.it_value.tv_sec = 0;
354 early_output_timer.it_value.tv_usec = 500000;
355 setitimer(ITIMER_REAL, &early_output_timer, NULL);
358 static void early_output(int signal)
360 show_early_output = log_show_early;
363 static void setup_early_output(void)
365 struct sigaction sa;
368 * Set up the signal handler, minimally intrusively:
369 * we only set a single volatile integer word (not
370 * using sigatomic_t - trying to avoid unnecessary
371 * system dependencies and headers), and using
372 * SA_RESTART.
374 memset(&sa, 0, sizeof(sa));
375 sa.sa_handler = early_output;
376 sigemptyset(&sa.sa_mask);
377 sa.sa_flags = SA_RESTART;
378 sigaction(SIGALRM, &sa, NULL);
381 * If we can get the whole output in less than a
382 * tenth of a second, don't even bother doing the
383 * early-output thing..
385 * This is a one-time-only trigger.
387 early_output_timer.it_value.tv_sec = 0;
388 early_output_timer.it_value.tv_usec = 100000;
389 setitimer(ITIMER_REAL, &early_output_timer, NULL);
392 static void finish_early_output(struct rev_info *rev)
394 int n = estimate_commit_count(rev->commits);
395 signal(SIGALRM, SIG_IGN);
396 show_early_header(rev, "done", n);
399 static int cmd_log_walk(struct rev_info *rev)
401 struct commit *commit;
402 int saved_nrl = 0;
403 int saved_dcctc = 0, close_file = rev->diffopt.close_file;
405 if (rev->early_output)
406 setup_early_output();
408 if (prepare_revision_walk(rev))
409 die(_("revision walk setup failed"));
411 if (rev->early_output)
412 finish_early_output(rev);
415 * For --check and --exit-code, the exit code is based on CHECK_FAILED
416 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
417 * retain that state information if replacing rev->diffopt in this loop
419 rev->diffopt.close_file = 0;
420 while ((commit = get_revision(rev)) != NULL) {
421 if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
423 * We decremented max_count in get_revision,
424 * but we didn't actually show the commit.
426 rev->max_count++;
427 if (!rev->reflog_info) {
429 * We may show a given commit multiple times when
430 * walking the reflogs.
432 free_commit_buffer(the_repository->parsed_objects,
433 commit);
434 free_commit_list(commit->parents);
435 commit->parents = NULL;
437 if (saved_nrl < rev->diffopt.needed_rename_limit)
438 saved_nrl = rev->diffopt.needed_rename_limit;
439 if (rev->diffopt.degraded_cc_to_c)
440 saved_dcctc = 1;
442 rev->diffopt.degraded_cc_to_c = saved_dcctc;
443 rev->diffopt.needed_rename_limit = saved_nrl;
444 if (close_file)
445 fclose(rev->diffopt.file);
447 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
448 rev->diffopt.flags.check_failed) {
449 return 02;
451 return diff_result_code(&rev->diffopt, 0);
454 static int git_log_config(const char *var, const char *value, void *cb)
456 const char *slot_name;
458 if (!strcmp(var, "format.pretty"))
459 return git_config_string(&fmt_pretty, var, value);
460 if (!strcmp(var, "format.subjectprefix"))
461 return git_config_string(&fmt_patch_subject_prefix, var, value);
462 if (!strcmp(var, "format.filenamemaxlength")) {
463 fmt_patch_name_max = git_config_int(var, value);
464 return 0;
466 if (!strcmp(var, "format.encodeemailheaders")) {
467 default_encode_email_headers = git_config_bool(var, value);
468 return 0;
470 if (!strcmp(var, "log.abbrevcommit")) {
471 default_abbrev_commit = git_config_bool(var, value);
472 return 0;
474 if (!strcmp(var, "log.date"))
475 return git_config_string(&default_date_mode, var, value);
476 if (!strcmp(var, "log.decorate")) {
477 decoration_style = parse_decoration_style(value);
478 if (decoration_style < 0)
479 decoration_style = 0; /* maybe warn? */
480 return 0;
482 if (!strcmp(var, "log.showroot")) {
483 default_show_root = git_config_bool(var, value);
484 return 0;
486 if (!strcmp(var, "log.follow")) {
487 default_follow = git_config_bool(var, value);
488 return 0;
490 if (skip_prefix(var, "color.decorate.", &slot_name))
491 return parse_decorate_color_config(var, slot_name, value);
492 if (!strcmp(var, "log.mailmap")) {
493 use_mailmap_config = git_config_bool(var, value);
494 return 0;
496 if (!strcmp(var, "log.showsignature")) {
497 default_show_signature = git_config_bool(var, value);
498 return 0;
501 if (grep_config(var, value, cb) < 0)
502 return -1;
503 if (git_gpg_config(var, value, cb) < 0)
504 return -1;
505 return git_diff_ui_config(var, value, cb);
508 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
510 struct rev_info rev;
511 struct setup_revision_opt opt;
513 init_log_defaults();
514 git_config(git_log_config, NULL);
516 repo_init_revisions(the_repository, &rev, prefix);
517 rev.diff = 1;
518 rev.simplify_history = 0;
519 memset(&opt, 0, sizeof(opt));
520 opt.def = "HEAD";
521 opt.revarg_opt = REVARG_COMMITTISH;
522 cmd_log_init(argc, argv, prefix, &rev, &opt);
523 if (!rev.diffopt.output_format)
524 rev.diffopt.output_format = DIFF_FORMAT_RAW;
525 return cmd_log_walk(&rev);
528 static void show_tagger(const char *buf, struct rev_info *rev)
530 struct strbuf out = STRBUF_INIT;
531 struct pretty_print_context pp = {0};
533 pp.fmt = rev->commit_format;
534 pp.date_mode = rev->date_mode;
535 pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
536 fprintf(rev->diffopt.file, "%s", out.buf);
537 strbuf_release(&out);
540 static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
542 struct object_id oidc;
543 struct object_context obj_context;
544 char *buf;
545 unsigned long size;
547 fflush(rev->diffopt.file);
548 if (!rev->diffopt.flags.textconv_set_via_cmdline ||
549 !rev->diffopt.flags.allow_textconv)
550 return stream_blob_to_fd(1, oid, NULL, 0);
552 if (get_oid_with_context(the_repository, obj_name,
553 GET_OID_RECORD_PATH,
554 &oidc, &obj_context))
555 die(_("not a valid object name %s"), obj_name);
556 if (!obj_context.path ||
557 !textconv_object(the_repository, obj_context.path,
558 obj_context.mode, &oidc, 1, &buf, &size)) {
559 free(obj_context.path);
560 return stream_blob_to_fd(1, oid, NULL, 0);
563 if (!buf)
564 die(_("git show %s: bad file"), obj_name);
566 write_or_die(1, buf, size);
567 free(obj_context.path);
568 return 0;
571 static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
573 unsigned long size;
574 enum object_type type;
575 char *buf = read_object_file(oid, &type, &size);
576 int offset = 0;
578 if (!buf)
579 return error(_("could not read object %s"), oid_to_hex(oid));
581 assert(type == OBJ_TAG);
582 while (offset < size && buf[offset] != '\n') {
583 int new_offset = offset + 1;
584 const char *ident;
585 while (new_offset < size && buf[new_offset++] != '\n')
586 ; /* do nothing */
587 if (skip_prefix(buf + offset, "tagger ", &ident))
588 show_tagger(ident, rev);
589 offset = new_offset;
592 if (offset < size)
593 fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
594 free(buf);
595 return 0;
598 static int show_tree_object(const struct object_id *oid,
599 struct strbuf *base,
600 const char *pathname, unsigned mode, int stage, void *context)
602 FILE *file = context;
603 fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
604 return 0;
607 static void show_setup_revisions_tweak(struct rev_info *rev,
608 struct setup_revision_opt *opt)
610 if (rev->ignore_merges < 0) {
611 /* There was no "-m" variant on the command line */
612 rev->ignore_merges = 0;
613 if (!rev->first_parent_only && !rev->combine_merges) {
614 /* No "--first-parent", "-c", or "--cc" */
615 rev->combine_merges = 1;
616 rev->dense_combined_merges = 1;
619 if (!rev->diffopt.output_format)
620 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
623 int cmd_show(int argc, const char **argv, const char *prefix)
625 struct rev_info rev;
626 struct object_array_entry *objects;
627 struct setup_revision_opt opt;
628 struct pathspec match_all;
629 int i, count, ret = 0;
631 init_log_defaults();
632 git_config(git_log_config, NULL);
634 memset(&match_all, 0, sizeof(match_all));
635 repo_init_revisions(the_repository, &rev, prefix);
636 rev.diff = 1;
637 rev.always_show_header = 1;
638 rev.no_walk = REVISION_WALK_NO_WALK_SORTED;
639 rev.diffopt.stat_width = -1; /* Scale to real terminal size */
641 memset(&opt, 0, sizeof(opt));
642 opt.def = "HEAD";
643 opt.tweak = show_setup_revisions_tweak;
644 cmd_log_init(argc, argv, prefix, &rev, &opt);
646 if (!rev.no_walk)
647 return cmd_log_walk(&rev);
649 count = rev.pending.nr;
650 objects = rev.pending.objects;
651 for (i = 0; i < count && !ret; i++) {
652 struct object *o = objects[i].item;
653 const char *name = objects[i].name;
654 switch (o->type) {
655 case OBJ_BLOB:
656 ret = show_blob_object(&o->oid, &rev, name);
657 break;
658 case OBJ_TAG: {
659 struct tag *t = (struct tag *)o;
660 struct object_id *oid = get_tagged_oid(t);
662 if (rev.shown_one)
663 putchar('\n');
664 fprintf(rev.diffopt.file, "%stag %s%s\n",
665 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
666 t->tag,
667 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
668 ret = show_tag_object(&o->oid, &rev);
669 rev.shown_one = 1;
670 if (ret)
671 break;
672 o = parse_object(the_repository, oid);
673 if (!o)
674 ret = error(_("could not read object %s"),
675 oid_to_hex(oid));
676 objects[i].item = o;
677 i--;
678 break;
680 case OBJ_TREE:
681 if (rev.shown_one)
682 putchar('\n');
683 fprintf(rev.diffopt.file, "%stree %s%s\n\n",
684 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
685 name,
686 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
687 read_tree_recursive(the_repository, (struct tree *)o, "",
688 0, 0, &match_all, show_tree_object,
689 rev.diffopt.file);
690 rev.shown_one = 1;
691 break;
692 case OBJ_COMMIT:
693 rev.pending.nr = rev.pending.alloc = 0;
694 rev.pending.objects = NULL;
695 add_object_array(o, name, &rev.pending);
696 ret = cmd_log_walk(&rev);
697 break;
698 default:
699 ret = error(_("unknown type: %d"), o->type);
702 free(objects);
703 return ret;
707 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
709 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
711 struct rev_info rev;
712 struct setup_revision_opt opt;
714 init_log_defaults();
715 git_config(git_log_config, NULL);
717 repo_init_revisions(the_repository, &rev, prefix);
718 init_reflog_walk(&rev.reflog_info);
719 rev.verbose_header = 1;
720 memset(&opt, 0, sizeof(opt));
721 opt.def = "HEAD";
722 cmd_log_init_defaults(&rev);
723 rev.abbrev_commit = 1;
724 rev.commit_format = CMIT_FMT_ONELINE;
725 rev.use_terminator = 1;
726 rev.always_show_header = 1;
727 cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
729 return cmd_log_walk(&rev);
732 static void log_setup_revisions_tweak(struct rev_info *rev,
733 struct setup_revision_opt *opt)
735 if (rev->diffopt.flags.default_follow_renames &&
736 rev->prune_data.nr == 1)
737 rev->diffopt.flags.follow_renames = 1;
739 /* Turn --cc/-c into -p --cc/-c when -p was not given */
740 if (!rev->diffopt.output_format && rev->combine_merges)
741 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
743 if (rev->first_parent_only && rev->ignore_merges < 0)
744 rev->ignore_merges = 0;
747 int cmd_log(int argc, const char **argv, const char *prefix)
749 struct rev_info rev;
750 struct setup_revision_opt opt;
752 init_log_defaults();
753 git_config(git_log_config, NULL);
755 repo_init_revisions(the_repository, &rev, prefix);
756 rev.always_show_header = 1;
757 memset(&opt, 0, sizeof(opt));
758 opt.def = "HEAD";
759 opt.revarg_opt = REVARG_COMMITTISH;
760 opt.tweak = log_setup_revisions_tweak;
761 cmd_log_init(argc, argv, prefix, &rev, &opt);
762 return cmd_log_walk(&rev);
765 /* format-patch */
767 static const char *fmt_patch_suffix = ".patch";
768 static int numbered = 0;
769 static int auto_number = 1;
771 static char *default_attach = NULL;
773 static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
774 static struct string_list extra_to = STRING_LIST_INIT_NODUP;
775 static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
777 static void add_header(const char *value)
779 struct string_list_item *item;
780 int len = strlen(value);
781 while (len && value[len - 1] == '\n')
782 len--;
784 if (!strncasecmp(value, "to: ", 4)) {
785 item = string_list_append(&extra_to, value + 4);
786 len -= 4;
787 } else if (!strncasecmp(value, "cc: ", 4)) {
788 item = string_list_append(&extra_cc, value + 4);
789 len -= 4;
790 } else {
791 item = string_list_append(&extra_hdr, value);
794 item->string[len] = '\0';
797 enum cover_setting {
798 COVER_UNSET,
799 COVER_OFF,
800 COVER_ON,
801 COVER_AUTO
804 enum thread_level {
805 THREAD_UNSET,
806 THREAD_SHALLOW,
807 THREAD_DEEP
810 enum cover_from_description {
811 COVER_FROM_NONE,
812 COVER_FROM_MESSAGE,
813 COVER_FROM_SUBJECT,
814 COVER_FROM_AUTO
817 enum auto_base_setting {
818 AUTO_BASE_NEVER,
819 AUTO_BASE_ALWAYS,
820 AUTO_BASE_WHEN_ABLE
823 static enum thread_level thread;
824 static int do_signoff;
825 static enum auto_base_setting auto_base;
826 static char *from;
827 static const char *signature = git_version_string;
828 static const char *signature_file;
829 static enum cover_setting config_cover_letter;
830 static const char *config_output_directory;
831 static enum cover_from_description cover_from_description_mode = COVER_FROM_MESSAGE;
832 static int show_notes;
833 static struct display_notes_opt notes_opt;
835 static enum cover_from_description parse_cover_from_description(const char *arg)
837 if (!arg || !strcmp(arg, "default"))
838 return COVER_FROM_MESSAGE;
839 else if (!strcmp(arg, "none"))
840 return COVER_FROM_NONE;
841 else if (!strcmp(arg, "message"))
842 return COVER_FROM_MESSAGE;
843 else if (!strcmp(arg, "subject"))
844 return COVER_FROM_SUBJECT;
845 else if (!strcmp(arg, "auto"))
846 return COVER_FROM_AUTO;
847 else
848 die(_("%s: invalid cover from description mode"), arg);
851 static int git_format_config(const char *var, const char *value, void *cb)
853 if (!strcmp(var, "format.headers")) {
854 if (!value)
855 die(_("format.headers without value"));
856 add_header(value);
857 return 0;
859 if (!strcmp(var, "format.suffix"))
860 return git_config_string(&fmt_patch_suffix, var, value);
861 if (!strcmp(var, "format.to")) {
862 if (!value)
863 return config_error_nonbool(var);
864 string_list_append(&extra_to, value);
865 return 0;
867 if (!strcmp(var, "format.cc")) {
868 if (!value)
869 return config_error_nonbool(var);
870 string_list_append(&extra_cc, value);
871 return 0;
873 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
874 !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
875 return 0;
877 if (!strcmp(var, "format.numbered")) {
878 if (value && !strcasecmp(value, "auto")) {
879 auto_number = 1;
880 return 0;
882 numbered = git_config_bool(var, value);
883 auto_number = auto_number && numbered;
884 return 0;
886 if (!strcmp(var, "format.attach")) {
887 if (value && *value)
888 default_attach = xstrdup(value);
889 else
890 default_attach = xstrdup(git_version_string);
891 return 0;
893 if (!strcmp(var, "format.thread")) {
894 if (value && !strcasecmp(value, "deep")) {
895 thread = THREAD_DEEP;
896 return 0;
898 if (value && !strcasecmp(value, "shallow")) {
899 thread = THREAD_SHALLOW;
900 return 0;
902 thread = git_config_bool(var, value) ? THREAD_SHALLOW : THREAD_UNSET;
903 return 0;
905 if (!strcmp(var, "format.signoff")) {
906 do_signoff = git_config_bool(var, value);
907 return 0;
909 if (!strcmp(var, "format.signature"))
910 return git_config_string(&signature, var, value);
911 if (!strcmp(var, "format.signaturefile"))
912 return git_config_pathname(&signature_file, var, value);
913 if (!strcmp(var, "format.coverletter")) {
914 if (value && !strcasecmp(value, "auto")) {
915 config_cover_letter = COVER_AUTO;
916 return 0;
918 config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
919 return 0;
921 if (!strcmp(var, "format.outputdirectory"))
922 return git_config_string(&config_output_directory, var, value);
923 if (!strcmp(var, "format.useautobase")) {
924 if (value && !strcasecmp(value, "whenAble")) {
925 auto_base = AUTO_BASE_WHEN_ABLE;
926 return 0;
928 auto_base = git_config_bool(var, value) ? AUTO_BASE_ALWAYS : AUTO_BASE_NEVER;
929 return 0;
931 if (!strcmp(var, "format.from")) {
932 int b = git_parse_maybe_bool(value);
933 free(from);
934 if (b < 0)
935 from = xstrdup(value);
936 else if (b)
937 from = xstrdup(git_committer_info(IDENT_NO_DATE));
938 else
939 from = NULL;
940 return 0;
942 if (!strcmp(var, "format.notes")) {
943 int b = git_parse_maybe_bool(value);
944 if (b < 0)
945 enable_ref_display_notes(&notes_opt, &show_notes, value);
946 else if (b)
947 enable_default_display_notes(&notes_opt, &show_notes);
948 else
949 disable_display_notes(&notes_opt, &show_notes);
950 return 0;
952 if (!strcmp(var, "format.coverfromdescription")) {
953 cover_from_description_mode = parse_cover_from_description(value);
954 return 0;
957 return git_log_config(var, value, cb);
960 static const char *output_directory = NULL;
961 static int outdir_offset;
963 static int open_next_file(struct commit *commit, const char *subject,
964 struct rev_info *rev, int quiet)
966 struct strbuf filename = STRBUF_INIT;
968 if (output_directory) {
969 strbuf_addstr(&filename, output_directory);
970 strbuf_complete(&filename, '/');
973 if (rev->numbered_files)
974 strbuf_addf(&filename, "%d", rev->nr);
975 else if (commit)
976 fmt_output_commit(&filename, commit, rev);
977 else
978 fmt_output_subject(&filename, subject, rev);
980 if (!quiet)
981 printf("%s\n", filename.buf + outdir_offset);
983 if ((rev->diffopt.file = fopen(filename.buf, "w")) == NULL) {
984 error_errno(_("cannot open patch file %s"), filename.buf);
985 strbuf_release(&filename);
986 return -1;
989 strbuf_release(&filename);
990 return 0;
993 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
995 struct rev_info check_rev;
996 struct commit *commit, *c1, *c2;
997 struct object *o1, *o2;
998 unsigned flags1, flags2;
1000 if (rev->pending.nr != 2)
1001 die(_("need exactly one range"));
1003 o1 = rev->pending.objects[0].item;
1004 o2 = rev->pending.objects[1].item;
1005 flags1 = o1->flags;
1006 flags2 = o2->flags;
1007 c1 = lookup_commit_reference(the_repository, &o1->oid);
1008 c2 = lookup_commit_reference(the_repository, &o2->oid);
1010 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
1011 die(_("not a range"));
1013 init_patch_ids(the_repository, ids);
1015 /* given a range a..b get all patch ids for b..a */
1016 repo_init_revisions(the_repository, &check_rev, rev->prefix);
1017 check_rev.max_parents = 1;
1018 o1->flags ^= UNINTERESTING;
1019 o2->flags ^= UNINTERESTING;
1020 add_pending_object(&check_rev, o1, "o1");
1021 add_pending_object(&check_rev, o2, "o2");
1022 if (prepare_revision_walk(&check_rev))
1023 die(_("revision walk setup failed"));
1025 while ((commit = get_revision(&check_rev)) != NULL) {
1026 add_commit_patch_id(commit, ids);
1029 /* reset for next revision walk */
1030 clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
1031 clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
1032 o1->flags = flags1;
1033 o2->flags = flags2;
1036 static void gen_message_id(struct rev_info *info, char *base)
1038 struct strbuf buf = STRBUF_INIT;
1039 strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
1040 (timestamp_t) time(NULL),
1041 git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
1042 info->message_id = strbuf_detach(&buf, NULL);
1045 static void print_signature(FILE *file)
1047 if (!signature || !*signature)
1048 return;
1050 fprintf(file, "-- \n%s", signature);
1051 if (signature[strlen(signature)-1] != '\n')
1052 putc('\n', file);
1053 putc('\n', file);
1056 static char *find_branch_name(struct rev_info *rev)
1058 int i, positive = -1;
1059 struct object_id branch_oid;
1060 const struct object_id *tip_oid;
1061 const char *ref, *v;
1062 char *full_ref, *branch = NULL;
1064 for (i = 0; i < rev->cmdline.nr; i++) {
1065 if (rev->cmdline.rev[i].flags & UNINTERESTING)
1066 continue;
1067 if (positive < 0)
1068 positive = i;
1069 else
1070 return NULL;
1072 if (positive < 0)
1073 return NULL;
1074 ref = rev->cmdline.rev[positive].name;
1075 tip_oid = &rev->cmdline.rev[positive].item->oid;
1076 if (dwim_ref(ref, strlen(ref), &branch_oid, &full_ref, 0) &&
1077 skip_prefix(full_ref, "refs/heads/", &v) &&
1078 oideq(tip_oid, &branch_oid))
1079 branch = xstrdup(v);
1080 free(full_ref);
1081 return branch;
1084 static void show_diffstat(struct rev_info *rev,
1085 struct commit *origin, struct commit *head)
1087 struct diff_options opts;
1089 memcpy(&opts, &rev->diffopt, sizeof(opts));
1090 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1091 diff_setup_done(&opts);
1093 diff_tree_oid(get_commit_tree_oid(origin),
1094 get_commit_tree_oid(head),
1095 "", &opts);
1096 diffcore_std(&opts);
1097 diff_flush(&opts);
1099 fprintf(rev->diffopt.file, "\n");
1102 static void prepare_cover_text(struct pretty_print_context *pp,
1103 const char *branch_name,
1104 struct strbuf *sb,
1105 const char *encoding,
1106 int need_8bit_cte)
1108 const char *subject = "*** SUBJECT HERE ***";
1109 const char *body = "*** BLURB HERE ***";
1110 struct strbuf description_sb = STRBUF_INIT;
1111 struct strbuf subject_sb = STRBUF_INIT;
1113 if (cover_from_description_mode == COVER_FROM_NONE)
1114 goto do_pp;
1116 if (branch_name && *branch_name)
1117 read_branch_desc(&description_sb, branch_name);
1118 if (!description_sb.len)
1119 goto do_pp;
1121 if (cover_from_description_mode == COVER_FROM_SUBJECT ||
1122 cover_from_description_mode == COVER_FROM_AUTO)
1123 body = format_subject(&subject_sb, description_sb.buf, " ");
1125 if (cover_from_description_mode == COVER_FROM_MESSAGE ||
1126 (cover_from_description_mode == COVER_FROM_AUTO &&
1127 subject_sb.len > COVER_FROM_AUTO_MAX_SUBJECT_LEN))
1128 body = description_sb.buf;
1129 else
1130 subject = subject_sb.buf;
1132 do_pp:
1133 pp_title_line(pp, &subject, sb, encoding, need_8bit_cte);
1134 pp_remainder(pp, &body, sb, 0);
1136 strbuf_release(&description_sb);
1137 strbuf_release(&subject_sb);
1140 static int get_notes_refs(struct string_list_item *item, void *arg)
1142 strvec_pushf(arg, "--notes=%s", item->string);
1143 return 0;
1146 static void get_notes_args(struct strvec *arg, struct rev_info *rev)
1148 if (!rev->show_notes) {
1149 strvec_push(arg, "--no-notes");
1150 } else if (rev->notes_opt.use_default_notes > 0 ||
1151 (rev->notes_opt.use_default_notes == -1 &&
1152 !rev->notes_opt.extra_notes_refs.nr)) {
1153 strvec_push(arg, "--notes");
1154 } else {
1155 for_each_string_list(&rev->notes_opt.extra_notes_refs, get_notes_refs, arg);
1159 static void make_cover_letter(struct rev_info *rev, int use_separate_file,
1160 struct commit *origin,
1161 int nr, struct commit **list,
1162 const char *branch_name,
1163 int quiet)
1165 const char *committer;
1166 struct shortlog log;
1167 struct strbuf sb = STRBUF_INIT;
1168 int i;
1169 const char *encoding = "UTF-8";
1170 int need_8bit_cte = 0;
1171 struct pretty_print_context pp = {0};
1172 struct commit *head = list[0];
1174 if (!cmit_fmt_is_mail(rev->commit_format))
1175 die(_("cover letter needs email format"));
1177 committer = git_committer_info(0);
1179 if (use_separate_file &&
1180 open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1181 die(_("failed to create cover-letter file"));
1183 log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1185 for (i = 0; !need_8bit_cte && i < nr; i++) {
1186 const char *buf = get_commit_buffer(list[i], NULL);
1187 if (has_non_ascii(buf))
1188 need_8bit_cte = 1;
1189 unuse_commit_buffer(list[i], buf);
1192 if (!branch_name)
1193 branch_name = find_branch_name(rev);
1195 pp.fmt = CMIT_FMT_EMAIL;
1196 pp.date_mode.type = DATE_RFC2822;
1197 pp.rev = rev;
1198 pp.print_email_subject = 1;
1199 pp_user_info(&pp, NULL, &sb, committer, encoding);
1200 prepare_cover_text(&pp, branch_name, &sb, encoding, need_8bit_cte);
1201 fprintf(rev->diffopt.file, "%s\n", sb.buf);
1203 strbuf_release(&sb);
1205 shortlog_init(&log);
1206 log.wrap_lines = 1;
1207 log.wrap = MAIL_DEFAULT_WRAP;
1208 log.in1 = 2;
1209 log.in2 = 4;
1210 log.file = rev->diffopt.file;
1211 log.groups = SHORTLOG_GROUP_AUTHOR;
1212 for (i = 0; i < nr; i++)
1213 shortlog_add_commit(&log, list[i]);
1215 shortlog_output(&log);
1217 /* We can only do diffstat with a unique reference point */
1218 if (origin)
1219 show_diffstat(rev, origin, head);
1221 if (rev->idiff_oid1) {
1222 fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1223 show_interdiff(rev->idiff_oid1, rev->idiff_oid2, 0,
1224 &rev->diffopt);
1227 if (rev->rdiff1) {
1229 * Pass minimum required diff-options to range-diff; others
1230 * can be added later if deemed desirable.
1232 struct diff_options opts;
1233 struct strvec other_arg = STRVEC_INIT;
1234 diff_setup(&opts);
1235 opts.file = rev->diffopt.file;
1236 opts.use_color = rev->diffopt.use_color;
1237 diff_setup_done(&opts);
1238 fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1239 get_notes_args(&other_arg, rev);
1240 show_range_diff(rev->rdiff1, rev->rdiff2,
1241 rev->creation_factor, 1, &opts, &other_arg);
1242 strvec_clear(&other_arg);
1246 static const char *clean_message_id(const char *msg_id)
1248 char ch;
1249 const char *a, *z, *m;
1251 m = msg_id;
1252 while ((ch = *m) && (isspace(ch) || (ch == '<')))
1253 m++;
1254 a = m;
1255 z = NULL;
1256 while ((ch = *m)) {
1257 if (!isspace(ch) && (ch != '>'))
1258 z = m;
1259 m++;
1261 if (!z)
1262 die(_("insane in-reply-to: %s"), msg_id);
1263 if (++z == m)
1264 return a;
1265 return xmemdupz(a, z - a);
1268 static const char *set_outdir(const char *prefix, const char *output_directory)
1270 if (output_directory && is_absolute_path(output_directory))
1271 return output_directory;
1273 if (!prefix || !*prefix) {
1274 if (output_directory)
1275 return output_directory;
1276 /* The user did not explicitly ask for "./" */
1277 outdir_offset = 2;
1278 return "./";
1281 outdir_offset = strlen(prefix);
1282 if (!output_directory)
1283 return prefix;
1285 return prefix_filename(prefix, output_directory);
1288 static const char * const builtin_format_patch_usage[] = {
1289 N_("git format-patch [<options>] [<since> | <revision-range>]"),
1290 NULL
1293 static int keep_subject = 0;
1295 static int keep_callback(const struct option *opt, const char *arg, int unset)
1297 BUG_ON_OPT_NEG(unset);
1298 BUG_ON_OPT_ARG(arg);
1299 ((struct rev_info *)opt->value)->total = -1;
1300 keep_subject = 1;
1301 return 0;
1304 static int subject_prefix = 0;
1306 static int subject_prefix_callback(const struct option *opt, const char *arg,
1307 int unset)
1309 BUG_ON_OPT_NEG(unset);
1310 subject_prefix = 1;
1311 ((struct rev_info *)opt->value)->subject_prefix = arg;
1312 return 0;
1315 static int rfc_callback(const struct option *opt, const char *arg, int unset)
1317 BUG_ON_OPT_NEG(unset);
1318 BUG_ON_OPT_ARG(arg);
1319 return subject_prefix_callback(opt, "RFC PATCH", unset);
1322 static int numbered_cmdline_opt = 0;
1324 static int numbered_callback(const struct option *opt, const char *arg,
1325 int unset)
1327 BUG_ON_OPT_ARG(arg);
1328 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1329 if (unset)
1330 auto_number = 0;
1331 return 0;
1334 static int no_numbered_callback(const struct option *opt, const char *arg,
1335 int unset)
1337 BUG_ON_OPT_NEG(unset);
1338 return numbered_callback(opt, arg, 1);
1341 static int output_directory_callback(const struct option *opt, const char *arg,
1342 int unset)
1344 const char **dir = (const char **)opt->value;
1345 BUG_ON_OPT_NEG(unset);
1346 if (*dir)
1347 die(_("two output directories?"));
1348 *dir = arg;
1349 return 0;
1352 static int thread_callback(const struct option *opt, const char *arg, int unset)
1354 enum thread_level *thread = (enum thread_level *)opt->value;
1355 if (unset)
1356 *thread = THREAD_UNSET;
1357 else if (!arg || !strcmp(arg, "shallow"))
1358 *thread = THREAD_SHALLOW;
1359 else if (!strcmp(arg, "deep"))
1360 *thread = THREAD_DEEP;
1362 * Please update _git_formatpatch() in git-completion.bash
1363 * when you add new options.
1365 else
1366 return 1;
1367 return 0;
1370 static int attach_callback(const struct option *opt, const char *arg, int unset)
1372 struct rev_info *rev = (struct rev_info *)opt->value;
1373 if (unset)
1374 rev->mime_boundary = NULL;
1375 else if (arg)
1376 rev->mime_boundary = arg;
1377 else
1378 rev->mime_boundary = git_version_string;
1379 rev->no_inline = unset ? 0 : 1;
1380 return 0;
1383 static int inline_callback(const struct option *opt, const char *arg, int unset)
1385 struct rev_info *rev = (struct rev_info *)opt->value;
1386 if (unset)
1387 rev->mime_boundary = NULL;
1388 else if (arg)
1389 rev->mime_boundary = arg;
1390 else
1391 rev->mime_boundary = git_version_string;
1392 rev->no_inline = 0;
1393 return 0;
1396 static int header_callback(const struct option *opt, const char *arg, int unset)
1398 if (unset) {
1399 string_list_clear(&extra_hdr, 0);
1400 string_list_clear(&extra_to, 0);
1401 string_list_clear(&extra_cc, 0);
1402 } else {
1403 add_header(arg);
1405 return 0;
1408 static int to_callback(const struct option *opt, const char *arg, int unset)
1410 if (unset)
1411 string_list_clear(&extra_to, 0);
1412 else
1413 string_list_append(&extra_to, arg);
1414 return 0;
1417 static int cc_callback(const struct option *opt, const char *arg, int unset)
1419 if (unset)
1420 string_list_clear(&extra_cc, 0);
1421 else
1422 string_list_append(&extra_cc, arg);
1423 return 0;
1426 static int from_callback(const struct option *opt, const char *arg, int unset)
1428 char **from = opt->value;
1430 free(*from);
1432 if (unset)
1433 *from = NULL;
1434 else if (arg)
1435 *from = xstrdup(arg);
1436 else
1437 *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1438 return 0;
1441 static int base_callback(const struct option *opt, const char *arg, int unset)
1443 const char **base_commit = opt->value;
1445 if (unset) {
1446 auto_base = AUTO_BASE_NEVER;
1447 *base_commit = NULL;
1448 } else if (!strcmp(arg, "auto")) {
1449 auto_base = AUTO_BASE_ALWAYS;
1450 *base_commit = NULL;
1451 } else {
1452 auto_base = AUTO_BASE_NEVER;
1453 *base_commit = arg;
1455 return 0;
1458 struct base_tree_info {
1459 struct object_id base_commit;
1460 int nr_patch_id, alloc_patch_id;
1461 struct object_id *patch_id;
1464 static struct commit *get_base_commit(const char *base_commit,
1465 struct commit **list,
1466 int total)
1468 struct commit *base = NULL;
1469 struct commit **rev;
1470 int i = 0, rev_nr = 0, auto_select, die_on_failure;
1472 switch (auto_base) {
1473 case AUTO_BASE_NEVER:
1474 if (base_commit) {
1475 auto_select = 0;
1476 die_on_failure = 1;
1477 } else {
1478 /* no base information is requested */
1479 return NULL;
1481 break;
1482 case AUTO_BASE_ALWAYS:
1483 case AUTO_BASE_WHEN_ABLE:
1484 if (base_commit) {
1485 BUG("requested automatic base selection but a commit was provided");
1486 } else {
1487 auto_select = 1;
1488 die_on_failure = auto_base == AUTO_BASE_ALWAYS;
1490 break;
1491 default:
1492 BUG("unexpected automatic base selection method");
1495 if (!auto_select) {
1496 base = lookup_commit_reference_by_name(base_commit);
1497 if (!base)
1498 die(_("unknown commit %s"), base_commit);
1499 } else {
1500 struct branch *curr_branch = branch_get(NULL);
1501 const char *upstream = branch_get_upstream(curr_branch, NULL);
1502 if (upstream) {
1503 struct commit_list *base_list;
1504 struct commit *commit;
1505 struct object_id oid;
1507 if (get_oid(upstream, &oid)) {
1508 if (die_on_failure)
1509 die(_("failed to resolve '%s' as a valid ref"), upstream);
1510 else
1511 return NULL;
1513 commit = lookup_commit_or_die(&oid, "upstream base");
1514 base_list = get_merge_bases_many(commit, total, list);
1515 /* There should be one and only one merge base. */
1516 if (!base_list || base_list->next) {
1517 if (die_on_failure) {
1518 die(_("could not find exact merge base"));
1519 } else {
1520 free_commit_list(base_list);
1521 return NULL;
1524 base = base_list->item;
1525 free_commit_list(base_list);
1526 } else {
1527 if (die_on_failure)
1528 die(_("failed to get upstream, if you want to record base commit automatically,\n"
1529 "please use git branch --set-upstream-to to track a remote branch.\n"
1530 "Or you could specify base commit by --base=<base-commit-id> manually"));
1531 else
1532 return NULL;
1536 ALLOC_ARRAY(rev, total);
1537 for (i = 0; i < total; i++)
1538 rev[i] = list[i];
1540 rev_nr = total;
1542 * Get merge base through pair-wise computations
1543 * and store it in rev[0].
1545 while (rev_nr > 1) {
1546 for (i = 0; i < rev_nr / 2; i++) {
1547 struct commit_list *merge_base;
1548 merge_base = get_merge_bases(rev[2 * i], rev[2 * i + 1]);
1549 if (!merge_base || merge_base->next) {
1550 if (die_on_failure) {
1551 die(_("failed to find exact merge base"));
1552 } else {
1553 free(rev);
1554 return NULL;
1558 rev[i] = merge_base->item;
1561 if (rev_nr % 2)
1562 rev[i] = rev[2 * i];
1563 rev_nr = DIV_ROUND_UP(rev_nr, 2);
1566 if (!in_merge_bases(base, rev[0])) {
1567 if (die_on_failure) {
1568 die(_("base commit should be the ancestor of revision list"));
1569 } else {
1570 free(rev);
1571 return NULL;
1575 for (i = 0; i < total; i++) {
1576 if (base == list[i]) {
1577 if (die_on_failure) {
1578 die(_("base commit shouldn't be in revision list"));
1579 } else {
1580 free(rev);
1581 return NULL;
1586 free(rev);
1587 return base;
1590 define_commit_slab(commit_base, int);
1592 static void prepare_bases(struct base_tree_info *bases,
1593 struct commit *base,
1594 struct commit **list,
1595 int total)
1597 struct commit *commit;
1598 struct rev_info revs;
1599 struct diff_options diffopt;
1600 struct commit_base commit_base;
1601 int i;
1603 if (!base)
1604 return;
1606 init_commit_base(&commit_base);
1607 repo_diff_setup(the_repository, &diffopt);
1608 diffopt.flags.recursive = 1;
1609 diff_setup_done(&diffopt);
1611 oidcpy(&bases->base_commit, &base->object.oid);
1613 repo_init_revisions(the_repository, &revs, NULL);
1614 revs.max_parents = 1;
1615 revs.topo_order = 1;
1616 for (i = 0; i < total; i++) {
1617 list[i]->object.flags &= ~UNINTERESTING;
1618 add_pending_object(&revs, &list[i]->object, "rev_list");
1619 *commit_base_at(&commit_base, list[i]) = 1;
1621 base->object.flags |= UNINTERESTING;
1622 add_pending_object(&revs, &base->object, "base");
1624 if (prepare_revision_walk(&revs))
1625 die(_("revision walk setup failed"));
1627 * Traverse the commits list, get prerequisite patch ids
1628 * and stuff them in bases structure.
1630 while ((commit = get_revision(&revs)) != NULL) {
1631 struct object_id oid;
1632 struct object_id *patch_id;
1633 if (*commit_base_at(&commit_base, commit))
1634 continue;
1635 if (commit_patch_id(commit, &diffopt, &oid, 0, 1))
1636 die(_("cannot get patch id"));
1637 ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1638 patch_id = bases->patch_id + bases->nr_patch_id;
1639 oidcpy(patch_id, &oid);
1640 bases->nr_patch_id++;
1642 clear_commit_base(&commit_base);
1645 static void print_bases(struct base_tree_info *bases, FILE *file)
1647 int i;
1649 /* Only do this once, either for the cover or for the first one */
1650 if (is_null_oid(&bases->base_commit))
1651 return;
1653 /* Show the base commit */
1654 fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1656 /* Show the prerequisite patches */
1657 for (i = bases->nr_patch_id - 1; i >= 0; i--)
1658 fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1660 free(bases->patch_id);
1661 bases->nr_patch_id = 0;
1662 bases->alloc_patch_id = 0;
1663 oidclr(&bases->base_commit);
1666 static const char *diff_title(struct strbuf *sb, int reroll_count,
1667 const char *generic, const char *rerolled)
1669 if (reroll_count <= 0)
1670 strbuf_addstr(sb, generic);
1671 else /* RFC may be v0, so allow -v1 to diff against v0 */
1672 strbuf_addf(sb, rerolled, reroll_count - 1);
1673 return sb->buf;
1676 static void infer_range_diff_ranges(struct strbuf *r1,
1677 struct strbuf *r2,
1678 const char *prev,
1679 struct commit *origin,
1680 struct commit *head)
1682 const char *head_oid = oid_to_hex(&head->object.oid);
1683 int prev_is_range = !!strstr(prev, "..");
1685 if (prev_is_range)
1686 strbuf_addstr(r1, prev);
1687 else
1688 strbuf_addf(r1, "%s..%s", head_oid, prev);
1690 if (origin)
1691 strbuf_addf(r2, "%s..%s", oid_to_hex(&origin->object.oid), head_oid);
1692 else if (prev_is_range)
1693 die(_("failed to infer range-diff origin of current series"));
1694 else {
1695 warning(_("using '%s' as range-diff origin of current series"), prev);
1696 strbuf_addf(r2, "%s..%s", prev, head_oid);
1700 int cmd_format_patch(int argc, const char **argv, const char *prefix)
1702 struct commit *commit;
1703 struct commit **list = NULL;
1704 struct rev_info rev;
1705 struct setup_revision_opt s_r_opt;
1706 int nr = 0, total, i;
1707 int use_stdout = 0;
1708 int start_number = -1;
1709 int just_numbers = 0;
1710 int ignore_if_in_upstream = 0;
1711 int cover_letter = -1;
1712 int boundary_count = 0;
1713 int no_binary_diff = 0;
1714 int zero_commit = 0;
1715 struct commit *origin = NULL;
1716 const char *in_reply_to = NULL;
1717 struct patch_ids ids;
1718 struct strbuf buf = STRBUF_INIT;
1719 int use_patch_format = 0;
1720 int quiet = 0;
1721 int reroll_count = -1;
1722 char *cover_from_description_arg = NULL;
1723 char *branch_name = NULL;
1724 char *base_commit = NULL;
1725 struct base_tree_info bases;
1726 struct commit *base;
1727 int show_progress = 0;
1728 struct progress *progress = NULL;
1729 struct oid_array idiff_prev = OID_ARRAY_INIT;
1730 struct strbuf idiff_title = STRBUF_INIT;
1731 const char *rdiff_prev = NULL;
1732 struct strbuf rdiff1 = STRBUF_INIT;
1733 struct strbuf rdiff2 = STRBUF_INIT;
1734 struct strbuf rdiff_title = STRBUF_INIT;
1735 int creation_factor = -1;
1737 const struct option builtin_format_patch_options[] = {
1738 OPT_CALLBACK_F('n', "numbered", &numbered, NULL,
1739 N_("use [PATCH n/m] even with a single patch"),
1740 PARSE_OPT_NOARG, numbered_callback),
1741 OPT_CALLBACK_F('N', "no-numbered", &numbered, NULL,
1742 N_("use [PATCH] even with multiple patches"),
1743 PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback),
1744 OPT_BOOL('s', "signoff", &do_signoff, N_("add a Signed-off-by trailer")),
1745 OPT_BOOL(0, "stdout", &use_stdout,
1746 N_("print patches to standard out")),
1747 OPT_BOOL(0, "cover-letter", &cover_letter,
1748 N_("generate a cover letter")),
1749 OPT_BOOL(0, "numbered-files", &just_numbers,
1750 N_("use simple number sequence for output file names")),
1751 OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
1752 N_("use <sfx> instead of '.patch'")),
1753 OPT_INTEGER(0, "start-number", &start_number,
1754 N_("start numbering patches at <n> instead of 1")),
1755 OPT_INTEGER('v', "reroll-count", &reroll_count,
1756 N_("mark the series as Nth re-roll")),
1757 OPT_INTEGER(0, "filename-max-length", &fmt_patch_name_max,
1758 N_("max length of output filename")),
1759 OPT_CALLBACK_F(0, "rfc", &rev, NULL,
1760 N_("use [RFC PATCH] instead of [PATCH]"),
1761 PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback),
1762 OPT_STRING(0, "cover-from-description", &cover_from_description_arg,
1763 N_("cover-from-description-mode"),
1764 N_("generate parts of a cover letter based on a branch's description")),
1765 OPT_CALLBACK_F(0, "subject-prefix", &rev, N_("prefix"),
1766 N_("use [<prefix>] instead of [PATCH]"),
1767 PARSE_OPT_NONEG, subject_prefix_callback),
1768 OPT_CALLBACK_F('o', "output-directory", &output_directory,
1769 N_("dir"), N_("store resulting files in <dir>"),
1770 PARSE_OPT_NONEG, output_directory_callback),
1771 OPT_CALLBACK_F('k', "keep-subject", &rev, NULL,
1772 N_("don't strip/add [PATCH]"),
1773 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback),
1774 OPT_BOOL(0, "no-binary", &no_binary_diff,
1775 N_("don't output binary diffs")),
1776 OPT_BOOL(0, "zero-commit", &zero_commit,
1777 N_("output all-zero hash in From header")),
1778 OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1779 N_("don't include a patch matching a commit upstream")),
1780 OPT_SET_INT_F('p', "no-stat", &use_patch_format,
1781 N_("show patch format instead of default (patch + stat)"),
1782 1, PARSE_OPT_NONEG),
1783 OPT_GROUP(N_("Messaging")),
1784 OPT_CALLBACK(0, "add-header", NULL, N_("header"),
1785 N_("add email header"), header_callback),
1786 OPT_CALLBACK(0, "to", NULL, N_("email"), N_("add To: header"), to_callback),
1787 OPT_CALLBACK(0, "cc", NULL, N_("email"), N_("add Cc: header"), cc_callback),
1788 OPT_CALLBACK_F(0, "from", &from, N_("ident"),
1789 N_("set From address to <ident> (or committer ident if absent)"),
1790 PARSE_OPT_OPTARG, from_callback),
1791 OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
1792 N_("make first mail a reply to <message-id>")),
1793 OPT_CALLBACK_F(0, "attach", &rev, N_("boundary"),
1794 N_("attach the patch"), PARSE_OPT_OPTARG,
1795 attach_callback),
1796 OPT_CALLBACK_F(0, "inline", &rev, N_("boundary"),
1797 N_("inline the patch"),
1798 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1799 inline_callback),
1800 OPT_CALLBACK_F(0, "thread", &thread, N_("style"),
1801 N_("enable message threading, styles: shallow, deep"),
1802 PARSE_OPT_OPTARG, thread_callback),
1803 OPT_STRING(0, "signature", &signature, N_("signature"),
1804 N_("add a signature")),
1805 OPT_CALLBACK_F(0, "base", &base_commit, N_("base-commit"),
1806 N_("add prerequisite tree info to the patch series"),
1807 0, base_callback),
1808 OPT_FILENAME(0, "signature-file", &signature_file,
1809 N_("add a signature from a file")),
1810 OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1811 OPT_BOOL(0, "progress", &show_progress,
1812 N_("show progress while generating patches")),
1813 OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
1814 N_("show changes against <rev> in cover letter or single patch"),
1815 parse_opt_object_name),
1816 OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
1817 N_("show changes against <refspec> in cover letter or single patch")),
1818 OPT_INTEGER(0, "creation-factor", &creation_factor,
1819 N_("percentage by which creation is weighted")),
1820 OPT_END()
1823 extra_hdr.strdup_strings = 1;
1824 extra_to.strdup_strings = 1;
1825 extra_cc.strdup_strings = 1;
1826 init_log_defaults();
1827 init_display_notes(&notes_opt);
1828 git_config(git_format_config, NULL);
1829 repo_init_revisions(the_repository, &rev, prefix);
1830 rev.show_notes = show_notes;
1831 memcpy(&rev.notes_opt, &notes_opt, sizeof(notes_opt));
1832 rev.commit_format = CMIT_FMT_EMAIL;
1833 rev.encode_email_headers = default_encode_email_headers;
1834 rev.expand_tabs_in_log_default = 0;
1835 rev.verbose_header = 1;
1836 rev.diff = 1;
1837 rev.max_parents = 1;
1838 rev.diffopt.flags.recursive = 1;
1839 rev.subject_prefix = fmt_patch_subject_prefix;
1840 memset(&s_r_opt, 0, sizeof(s_r_opt));
1841 s_r_opt.def = "HEAD";
1842 s_r_opt.revarg_opt = REVARG_COMMITTISH;
1844 if (default_attach) {
1845 rev.mime_boundary = default_attach;
1846 rev.no_inline = 1;
1850 * Parse the arguments before setup_revisions(), or something
1851 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1852 * possibly a valid SHA1.
1854 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1855 builtin_format_patch_usage,
1856 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1857 PARSE_OPT_KEEP_DASHDASH);
1859 /* Make sure "0000-$sub.patch" gives non-negative length for $sub */
1860 if (fmt_patch_name_max <= strlen("0000-") + strlen(fmt_patch_suffix))
1861 fmt_patch_name_max = strlen("0000-") + strlen(fmt_patch_suffix);
1863 if (cover_from_description_arg)
1864 cover_from_description_mode = parse_cover_from_description(cover_from_description_arg);
1866 if (0 < reroll_count) {
1867 struct strbuf sprefix = STRBUF_INIT;
1868 strbuf_addf(&sprefix, "%s v%d",
1869 rev.subject_prefix, reroll_count);
1870 rev.reroll_count = reroll_count;
1871 rev.subject_prefix = strbuf_detach(&sprefix, NULL);
1874 for (i = 0; i < extra_hdr.nr; i++) {
1875 strbuf_addstr(&buf, extra_hdr.items[i].string);
1876 strbuf_addch(&buf, '\n');
1879 if (extra_to.nr)
1880 strbuf_addstr(&buf, "To: ");
1881 for (i = 0; i < extra_to.nr; i++) {
1882 if (i)
1883 strbuf_addstr(&buf, " ");
1884 strbuf_addstr(&buf, extra_to.items[i].string);
1885 if (i + 1 < extra_to.nr)
1886 strbuf_addch(&buf, ',');
1887 strbuf_addch(&buf, '\n');
1890 if (extra_cc.nr)
1891 strbuf_addstr(&buf, "Cc: ");
1892 for (i = 0; i < extra_cc.nr; i++) {
1893 if (i)
1894 strbuf_addstr(&buf, " ");
1895 strbuf_addstr(&buf, extra_cc.items[i].string);
1896 if (i + 1 < extra_cc.nr)
1897 strbuf_addch(&buf, ',');
1898 strbuf_addch(&buf, '\n');
1901 rev.extra_headers = strbuf_detach(&buf, NULL);
1903 if (from) {
1904 if (split_ident_line(&rev.from_ident, from, strlen(from)))
1905 die(_("invalid ident line: %s"), from);
1908 if (start_number < 0)
1909 start_number = 1;
1912 * If numbered is set solely due to format.numbered in config,
1913 * and it would conflict with --keep-subject (-k) from the
1914 * command line, reset "numbered".
1916 if (numbered && keep_subject && !numbered_cmdline_opt)
1917 numbered = 0;
1919 if (numbered && keep_subject)
1920 die(_("-n and -k are mutually exclusive"));
1921 if (keep_subject && subject_prefix)
1922 die(_("--subject-prefix/--rfc and -k are mutually exclusive"));
1923 rev.preserve_subject = keep_subject;
1925 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1926 if (argc > 1)
1927 die(_("unrecognized argument: %s"), argv[1]);
1929 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1930 die(_("--name-only does not make sense"));
1931 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1932 die(_("--name-status does not make sense"));
1933 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1934 die(_("--check does not make sense"));
1936 if (!use_patch_format &&
1937 (!rev.diffopt.output_format ||
1938 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1939 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1940 if (!rev.diffopt.stat_width)
1941 rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
1943 /* Always generate a patch */
1944 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1946 rev.zero_commit = zero_commit;
1947 rev.patch_name_max = fmt_patch_name_max;
1949 if (!rev.diffopt.flags.text && !no_binary_diff)
1950 rev.diffopt.flags.binary = 1;
1952 if (rev.show_notes)
1953 load_display_notes(&rev.notes_opt);
1955 if (use_stdout + rev.diffopt.close_file + !!output_directory > 1)
1956 die(_("--stdout, --output, and --output-directory are mutually exclusive"));
1958 if (use_stdout) {
1959 setup_pager();
1960 } else if (rev.diffopt.close_file) {
1962 * The diff code parsed --output; it has already opened the
1963 * file, but but we must instruct it not to close after each
1964 * diff.
1966 rev.diffopt.close_file = 0;
1967 } else {
1968 int saved;
1970 if (!output_directory)
1971 output_directory = config_output_directory;
1972 output_directory = set_outdir(prefix, output_directory);
1974 if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
1975 rev.diffopt.use_color = GIT_COLOR_NEVER;
1977 * We consider <outdir> as 'outside of gitdir', therefore avoid
1978 * applying adjust_shared_perm in s-c-l-d.
1980 saved = get_shared_repository();
1981 set_shared_repository(0);
1982 switch (safe_create_leading_directories_const(output_directory)) {
1983 case SCLD_OK:
1984 case SCLD_EXISTS:
1985 break;
1986 default:
1987 die(_("could not create leading directories "
1988 "of '%s'"), output_directory);
1990 set_shared_repository(saved);
1991 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1992 die_errno(_("could not create directory '%s'"),
1993 output_directory);
1996 if (rev.pending.nr == 1) {
1997 int check_head = 0;
1999 if (rev.max_count < 0 && !rev.show_root_diff) {
2001 * This is traditional behaviour of "git format-patch
2002 * origin" that prepares what the origin side still
2003 * does not have.
2005 rev.pending.objects[0].item->flags |= UNINTERESTING;
2006 add_head_to_pending(&rev);
2007 check_head = 1;
2010 * Otherwise, it is "format-patch -22 HEAD", and/or
2011 * "format-patch --root HEAD". The user wants
2012 * get_revision() to do the usual traversal.
2015 if (!strcmp(rev.pending.objects[0].name, "HEAD"))
2016 check_head = 1;
2018 if (check_head) {
2019 const char *ref, *v;
2020 ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2021 NULL, NULL);
2022 if (ref && skip_prefix(ref, "refs/heads/", &v))
2023 branch_name = xstrdup(v);
2024 else
2025 branch_name = xstrdup(""); /* no branch */
2030 * We cannot move this anywhere earlier because we do want to
2031 * know if --root was given explicitly from the command line.
2033 rev.show_root_diff = 1;
2035 if (ignore_if_in_upstream) {
2036 /* Don't say anything if head and upstream are the same. */
2037 if (rev.pending.nr == 2) {
2038 struct object_array_entry *o = rev.pending.objects;
2039 if (oideq(&o[0].item->oid, &o[1].item->oid))
2040 goto done;
2042 get_patch_ids(&rev, &ids);
2045 if (prepare_revision_walk(&rev))
2046 die(_("revision walk setup failed"));
2047 rev.boundary = 1;
2048 while ((commit = get_revision(&rev)) != NULL) {
2049 if (commit->object.flags & BOUNDARY) {
2050 boundary_count++;
2051 origin = (boundary_count == 1) ? commit : NULL;
2052 continue;
2055 if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
2056 continue;
2058 nr++;
2059 REALLOC_ARRAY(list, nr);
2060 list[nr - 1] = commit;
2062 if (nr == 0)
2063 /* nothing to do */
2064 goto done;
2065 total = nr;
2066 if (cover_letter == -1) {
2067 if (config_cover_letter == COVER_AUTO)
2068 cover_letter = (total > 1);
2069 else
2070 cover_letter = (config_cover_letter == COVER_ON);
2072 if (!keep_subject && auto_number && (total > 1 || cover_letter))
2073 numbered = 1;
2074 if (numbered)
2075 rev.total = total + start_number - 1;
2077 if (idiff_prev.nr) {
2078 if (!cover_letter && total != 1)
2079 die(_("--interdiff requires --cover-letter or single patch"));
2080 rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
2081 rev.idiff_oid2 = get_commit_tree_oid(list[0]);
2082 rev.idiff_title = diff_title(&idiff_title, reroll_count,
2083 _("Interdiff:"),
2084 _("Interdiff against v%d:"));
2087 if (creation_factor < 0)
2088 creation_factor = RANGE_DIFF_CREATION_FACTOR_DEFAULT;
2089 else if (!rdiff_prev)
2090 die(_("--creation-factor requires --range-diff"));
2092 if (rdiff_prev) {
2093 if (!cover_letter && total != 1)
2094 die(_("--range-diff requires --cover-letter or single patch"));
2096 infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
2097 origin, list[0]);
2098 rev.rdiff1 = rdiff1.buf;
2099 rev.rdiff2 = rdiff2.buf;
2100 rev.creation_factor = creation_factor;
2101 rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
2102 _("Range-diff:"),
2103 _("Range-diff against v%d:"));
2106 if (!signature) {
2107 ; /* --no-signature inhibits all signatures */
2108 } else if (signature && signature != git_version_string) {
2109 ; /* non-default signature already set */
2110 } else if (signature_file) {
2111 struct strbuf buf = STRBUF_INIT;
2113 if (strbuf_read_file(&buf, signature_file, 128) < 0)
2114 die_errno(_("unable to read signature file '%s'"), signature_file);
2115 signature = strbuf_detach(&buf, NULL);
2118 memset(&bases, 0, sizeof(bases));
2119 base = get_base_commit(base_commit, list, nr);
2120 if (base) {
2121 reset_revision_walk();
2122 clear_object_flags(UNINTERESTING);
2123 prepare_bases(&bases, base, list, nr);
2126 if (in_reply_to || thread || cover_letter)
2127 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
2128 if (in_reply_to) {
2129 const char *msgid = clean_message_id(in_reply_to);
2130 string_list_append(rev.ref_message_ids, msgid);
2132 rev.numbered_files = just_numbers;
2133 rev.patch_suffix = fmt_patch_suffix;
2134 if (cover_letter) {
2135 if (thread)
2136 gen_message_id(&rev, "cover");
2137 make_cover_letter(&rev, !!output_directory,
2138 origin, nr, list, branch_name, quiet);
2139 print_bases(&bases, rev.diffopt.file);
2140 print_signature(rev.diffopt.file);
2141 total++;
2142 start_number--;
2143 /* interdiff/range-diff in cover-letter; omit from patches */
2144 rev.idiff_oid1 = NULL;
2145 rev.rdiff1 = NULL;
2147 rev.add_signoff = do_signoff;
2149 if (show_progress)
2150 progress = start_delayed_progress(_("Generating patches"), total);
2151 while (0 <= --nr) {
2152 int shown;
2153 display_progress(progress, total - nr);
2154 commit = list[nr];
2155 rev.nr = total - nr + (start_number - 1);
2156 /* Make the second and subsequent mails replies to the first */
2157 if (thread) {
2158 /* Have we already had a message ID? */
2159 if (rev.message_id) {
2161 * For deep threading: make every mail
2162 * a reply to the previous one, no
2163 * matter what other options are set.
2165 * For shallow threading:
2167 * Without --cover-letter and
2168 * --in-reply-to, make every mail a
2169 * reply to the one before.
2171 * With --in-reply-to but no
2172 * --cover-letter, make every mail a
2173 * reply to the <reply-to>.
2175 * With --cover-letter, make every
2176 * mail but the cover letter a reply
2177 * to the cover letter. The cover
2178 * letter is a reply to the
2179 * --in-reply-to, if specified.
2181 if (thread == THREAD_SHALLOW
2182 && rev.ref_message_ids->nr > 0
2183 && (!cover_letter || rev.nr > 1))
2184 free(rev.message_id);
2185 else
2186 string_list_append(rev.ref_message_ids,
2187 rev.message_id);
2189 gen_message_id(&rev, oid_to_hex(&commit->object.oid));
2192 if (output_directory &&
2193 open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
2194 die(_("failed to create output files"));
2195 shown = log_tree_commit(&rev, commit);
2196 free_commit_buffer(the_repository->parsed_objects,
2197 commit);
2199 /* We put one extra blank line between formatted
2200 * patches and this flag is used by log-tree code
2201 * to see if it needs to emit a LF before showing
2202 * the log; when using one file per patch, we do
2203 * not want the extra blank line.
2205 if (output_directory)
2206 rev.shown_one = 0;
2207 if (shown) {
2208 print_bases(&bases, rev.diffopt.file);
2209 if (rev.mime_boundary)
2210 fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
2211 mime_boundary_leader,
2212 rev.mime_boundary);
2213 else
2214 print_signature(rev.diffopt.file);
2216 if (output_directory)
2217 fclose(rev.diffopt.file);
2219 stop_progress(&progress);
2220 free(list);
2221 free(branch_name);
2222 string_list_clear(&extra_to, 0);
2223 string_list_clear(&extra_cc, 0);
2224 string_list_clear(&extra_hdr, 0);
2225 if (ignore_if_in_upstream)
2226 free_patch_ids(&ids);
2228 done:
2229 oid_array_clear(&idiff_prev);
2230 strbuf_release(&idiff_title);
2231 strbuf_release(&rdiff1);
2232 strbuf_release(&rdiff2);
2233 strbuf_release(&rdiff_title);
2234 return 0;
2237 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
2239 struct object_id oid;
2240 if (get_oid(arg, &oid) == 0) {
2241 struct commit *commit = lookup_commit_reference(the_repository,
2242 &oid);
2243 if (commit) {
2244 commit->object.flags |= flags;
2245 add_pending_object(revs, &commit->object, arg);
2246 return 0;
2249 return -1;
2252 static const char * const cherry_usage[] = {
2253 N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
2254 NULL
2257 static void print_commit(char sign, struct commit *commit, int verbose,
2258 int abbrev, FILE *file)
2260 if (!verbose) {
2261 fprintf(file, "%c %s\n", sign,
2262 find_unique_abbrev(&commit->object.oid, abbrev));
2263 } else {
2264 struct strbuf buf = STRBUF_INIT;
2265 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2266 fprintf(file, "%c %s %s\n", sign,
2267 find_unique_abbrev(&commit->object.oid, abbrev),
2268 buf.buf);
2269 strbuf_release(&buf);
2273 int cmd_cherry(int argc, const char **argv, const char *prefix)
2275 struct rev_info revs;
2276 struct patch_ids ids;
2277 struct commit *commit;
2278 struct commit_list *list = NULL;
2279 struct branch *current_branch;
2280 const char *upstream;
2281 const char *head = "HEAD";
2282 const char *limit = NULL;
2283 int verbose = 0, abbrev = 0;
2285 struct option options[] = {
2286 OPT__ABBREV(&abbrev),
2287 OPT__VERBOSE(&verbose, N_("be verbose")),
2288 OPT_END()
2291 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
2293 switch (argc) {
2294 case 3:
2295 limit = argv[2];
2296 /* FALLTHROUGH */
2297 case 2:
2298 head = argv[1];
2299 /* FALLTHROUGH */
2300 case 1:
2301 upstream = argv[0];
2302 break;
2303 default:
2304 current_branch = branch_get(NULL);
2305 upstream = branch_get_upstream(current_branch, NULL);
2306 if (!upstream) {
2307 fprintf(stderr, _("Could not find a tracked"
2308 " remote branch, please"
2309 " specify <upstream> manually.\n"));
2310 usage_with_options(cherry_usage, options);
2314 repo_init_revisions(the_repository, &revs, prefix);
2315 revs.max_parents = 1;
2317 if (add_pending_commit(head, &revs, 0))
2318 die(_("unknown commit %s"), head);
2319 if (add_pending_commit(upstream, &revs, UNINTERESTING))
2320 die(_("unknown commit %s"), upstream);
2322 /* Don't say anything if head and upstream are the same. */
2323 if (revs.pending.nr == 2) {
2324 struct object_array_entry *o = revs.pending.objects;
2325 if (oideq(&o[0].item->oid, &o[1].item->oid))
2326 return 0;
2329 get_patch_ids(&revs, &ids);
2331 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2332 die(_("unknown commit %s"), limit);
2334 /* reverse the list of commits */
2335 if (prepare_revision_walk(&revs))
2336 die(_("revision walk setup failed"));
2337 while ((commit = get_revision(&revs)) != NULL) {
2338 commit_list_insert(commit, &list);
2341 while (list) {
2342 char sign = '+';
2344 commit = list->item;
2345 if (has_commit_patch_id(commit, &ids))
2346 sign = '-';
2347 print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2348 list = list->next;
2351 free_patch_ids(&ids);
2352 return 0;