ssh: 'auto' variant to select between 'ssh' and 'simple'
[alt-git.git] / builtin / log.c
blobf8cccbc96403a791ff9d4641bac1c30b621c0d5e
1 /*
2 * Builtin "git log" and related commands (show, whatchanged)
4 * (C) Copyright 2006 Linus Torvalds
5 * 2006 Junio Hamano
6 */
7 #include "cache.h"
8 #include "config.h"
9 #include "refs.h"
10 #include "color.h"
11 #include "commit.h"
12 #include "diff.h"
13 #include "revision.h"
14 #include "log-tree.h"
15 #include "builtin.h"
16 #include "tag.h"
17 #include "reflog-walk.h"
18 #include "patch-ids.h"
19 #include "run-command.h"
20 #include "shortlog.h"
21 #include "remote.h"
22 #include "string-list.h"
23 #include "parse-options.h"
24 #include "line-log.h"
25 #include "branch.h"
26 #include "streaming.h"
27 #include "version.h"
28 #include "mailmap.h"
29 #include "gpg-interface.h"
30 #include "progress.h"
32 /* Set a default date-time format for git log ("log.date" config variable) */
33 static const char *default_date_mode = NULL;
35 static int default_abbrev_commit;
36 static int default_show_root = 1;
37 static int default_follow;
38 static int default_show_signature;
39 static int decoration_style;
40 static int decoration_given;
41 static int use_mailmap_config;
42 static const char *fmt_patch_subject_prefix = "PATCH";
43 static const char *fmt_pretty;
45 static const char * const builtin_log_usage[] = {
46 N_("git log [<options>] [<revision-range>] [[--] <path>...]"),
47 N_("git show [<options>] <object>..."),
48 NULL
51 struct line_opt_callback_data {
52 struct rev_info *rev;
53 const char *prefix;
54 struct string_list args;
57 static int auto_decoration_style(void)
59 return (isatty(1) || pager_in_use()) ? DECORATE_SHORT_REFS : 0;
62 static int parse_decoration_style(const char *value)
64 switch (git_parse_maybe_bool(value)) {
65 case 1:
66 return DECORATE_SHORT_REFS;
67 case 0:
68 return 0;
69 default:
70 break;
72 if (!strcmp(value, "full"))
73 return DECORATE_FULL_REFS;
74 else if (!strcmp(value, "short"))
75 return DECORATE_SHORT_REFS;
76 else if (!strcmp(value, "auto"))
77 return auto_decoration_style();
78 return -1;
81 static int decorate_callback(const struct option *opt, const char *arg, int unset)
83 if (unset)
84 decoration_style = 0;
85 else if (arg)
86 decoration_style = parse_decoration_style(arg);
87 else
88 decoration_style = DECORATE_SHORT_REFS;
90 if (decoration_style < 0)
91 die(_("invalid --decorate option: %s"), arg);
93 decoration_given = 1;
95 return 0;
98 static int log_line_range_callback(const struct option *option, const char *arg, int unset)
100 struct line_opt_callback_data *data = option->value;
102 if (!arg)
103 return -1;
105 data->rev->line_level_traverse = 1;
106 string_list_append(&data->args, arg);
108 return 0;
111 static void init_log_defaults(void)
113 init_grep_defaults();
114 init_diff_ui_defaults();
116 decoration_style = auto_decoration_style();
119 static void cmd_log_init_defaults(struct rev_info *rev)
121 if (fmt_pretty)
122 get_commit_format(fmt_pretty, rev);
123 if (default_follow)
124 DIFF_OPT_SET(&rev->diffopt, DEFAULT_FOLLOW_RENAMES);
125 rev->verbose_header = 1;
126 DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
127 rev->diffopt.stat_width = -1; /* use full terminal width */
128 rev->diffopt.stat_graph_width = -1; /* respect statGraphWidth config */
129 rev->abbrev_commit = default_abbrev_commit;
130 rev->show_root_diff = default_show_root;
131 rev->subject_prefix = fmt_patch_subject_prefix;
132 rev->show_signature = default_show_signature;
133 DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
135 if (default_date_mode)
136 parse_date_format(default_date_mode, &rev->date_mode);
137 rev->diffopt.touched_flags = 0;
140 static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
141 struct rev_info *rev, struct setup_revision_opt *opt)
143 struct userformat_want w;
144 int quiet = 0, source = 0, mailmap = 0;
145 static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
147 const struct option builtin_log_options[] = {
148 OPT__QUIET(&quiet, N_("suppress diff output")),
149 OPT_BOOL(0, "source", &source, N_("show source")),
150 OPT_BOOL(0, "use-mailmap", &mailmap, N_("Use mail map file")),
151 { OPTION_CALLBACK, 0, "decorate", NULL, NULL, N_("decorate options"),
152 PARSE_OPT_OPTARG, decorate_callback},
153 OPT_CALLBACK('L', NULL, &line_cb, "n,m:file",
154 N_("Process line range n,m in file, counting from 1"),
155 log_line_range_callback),
156 OPT_END()
159 line_cb.rev = rev;
160 line_cb.prefix = prefix;
162 mailmap = use_mailmap_config;
163 argc = parse_options(argc, argv, prefix,
164 builtin_log_options, builtin_log_usage,
165 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
166 PARSE_OPT_KEEP_DASHDASH);
168 if (quiet)
169 rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
170 argc = setup_revisions(argc, argv, rev, opt);
172 /* Any arguments at this point are not recognized */
173 if (argc > 1)
174 die(_("unrecognized argument: %s"), argv[1]);
176 memset(&w, 0, sizeof(w));
177 userformat_find_requirements(NULL, &w);
179 if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
180 rev->show_notes = 1;
181 if (rev->show_notes)
182 init_display_notes(&rev->notes_opt);
184 if (rev->diffopt.pickaxe || rev->diffopt.filter ||
185 DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES))
186 rev->always_show_header = 0;
188 if (source)
189 rev->show_source = 1;
191 if (mailmap) {
192 rev->mailmap = xcalloc(1, sizeof(struct string_list));
193 read_mailmap(rev->mailmap, NULL);
196 if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
198 * "log --pretty=raw" is special; ignore UI oriented
199 * configuration variables such as decoration.
201 if (!decoration_given)
202 decoration_style = 0;
203 if (!rev->abbrev_commit_given)
204 rev->abbrev_commit = 0;
207 if (decoration_style) {
208 rev->show_decorations = 1;
209 load_ref_decorations(decoration_style);
212 if (rev->line_level_traverse)
213 line_log_init(rev, line_cb.prefix, &line_cb.args);
215 setup_pager();
218 static void cmd_log_init(int argc, const char **argv, const char *prefix,
219 struct rev_info *rev, struct setup_revision_opt *opt)
221 cmd_log_init_defaults(rev);
222 cmd_log_init_finish(argc, argv, prefix, rev, opt);
226 * This gives a rough estimate for how many commits we
227 * will print out in the list.
229 static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
231 int n = 0;
233 while (list) {
234 struct commit *commit = list->item;
235 unsigned int flags = commit->object.flags;
236 list = list->next;
237 if (!(flags & (TREESAME | UNINTERESTING)))
238 n++;
240 return n;
243 static void show_early_header(struct rev_info *rev, const char *stage, int nr)
245 if (rev->shown_one) {
246 rev->shown_one = 0;
247 if (rev->commit_format != CMIT_FMT_ONELINE)
248 putchar(rev->diffopt.line_termination);
250 fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
253 static struct itimerval early_output_timer;
255 static void log_show_early(struct rev_info *revs, struct commit_list *list)
257 int i = revs->early_output, close_file = revs->diffopt.close_file;
258 int show_header = 1;
260 revs->diffopt.close_file = 0;
261 sort_in_topological_order(&list, revs->sort_order);
262 while (list && i) {
263 struct commit *commit = list->item;
264 switch (simplify_commit(revs, commit)) {
265 case commit_show:
266 if (show_header) {
267 int n = estimate_commit_count(revs, list);
268 show_early_header(revs, "incomplete", n);
269 show_header = 0;
271 log_tree_commit(revs, commit);
272 i--;
273 break;
274 case commit_ignore:
275 break;
276 case commit_error:
277 if (close_file)
278 fclose(revs->diffopt.file);
279 return;
281 list = list->next;
284 /* Did we already get enough commits for the early output? */
285 if (!i) {
286 if (close_file)
287 fclose(revs->diffopt.file);
288 return;
292 * ..if no, then repeat it twice a second until we
293 * do.
295 * NOTE! We don't use "it_interval", because if the
296 * reader isn't listening, we want our output to be
297 * throttled by the writing, and not have the timer
298 * trigger every second even if we're blocked on a
299 * reader!
301 early_output_timer.it_value.tv_sec = 0;
302 early_output_timer.it_value.tv_usec = 500000;
303 setitimer(ITIMER_REAL, &early_output_timer, NULL);
306 static void early_output(int signal)
308 show_early_output = log_show_early;
311 static void setup_early_output(struct rev_info *rev)
313 struct sigaction sa;
316 * Set up the signal handler, minimally intrusively:
317 * we only set a single volatile integer word (not
318 * using sigatomic_t - trying to avoid unnecessary
319 * system dependencies and headers), and using
320 * SA_RESTART.
322 memset(&sa, 0, sizeof(sa));
323 sa.sa_handler = early_output;
324 sigemptyset(&sa.sa_mask);
325 sa.sa_flags = SA_RESTART;
326 sigaction(SIGALRM, &sa, NULL);
329 * If we can get the whole output in less than a
330 * tenth of a second, don't even bother doing the
331 * early-output thing..
333 * This is a one-time-only trigger.
335 early_output_timer.it_value.tv_sec = 0;
336 early_output_timer.it_value.tv_usec = 100000;
337 setitimer(ITIMER_REAL, &early_output_timer, NULL);
340 static void finish_early_output(struct rev_info *rev)
342 int n = estimate_commit_count(rev, rev->commits);
343 signal(SIGALRM, SIG_IGN);
344 show_early_header(rev, "done", n);
347 static int cmd_log_walk(struct rev_info *rev)
349 struct commit *commit;
350 int saved_nrl = 0;
351 int saved_dcctc = 0, close_file = rev->diffopt.close_file;
353 if (rev->early_output)
354 setup_early_output(rev);
356 if (prepare_revision_walk(rev))
357 die(_("revision walk setup failed"));
359 if (rev->early_output)
360 finish_early_output(rev);
363 * For --check and --exit-code, the exit code is based on CHECK_FAILED
364 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
365 * retain that state information if replacing rev->diffopt in this loop
367 rev->diffopt.close_file = 0;
368 while ((commit = get_revision(rev)) != NULL) {
369 if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
371 * We decremented max_count in get_revision,
372 * but we didn't actually show the commit.
374 rev->max_count++;
375 if (!rev->reflog_info) {
377 * We may show a given commit multiple times when
378 * walking the reflogs.
380 free_commit_buffer(commit);
381 free_commit_list(commit->parents);
382 commit->parents = NULL;
384 if (saved_nrl < rev->diffopt.needed_rename_limit)
385 saved_nrl = rev->diffopt.needed_rename_limit;
386 if (rev->diffopt.degraded_cc_to_c)
387 saved_dcctc = 1;
389 rev->diffopt.degraded_cc_to_c = saved_dcctc;
390 rev->diffopt.needed_rename_limit = saved_nrl;
391 if (close_file)
392 fclose(rev->diffopt.file);
394 if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
395 DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
396 return 02;
398 return diff_result_code(&rev->diffopt, 0);
401 static int git_log_config(const char *var, const char *value, void *cb)
403 const char *slot_name;
405 if (!strcmp(var, "format.pretty"))
406 return git_config_string(&fmt_pretty, var, value);
407 if (!strcmp(var, "format.subjectprefix"))
408 return git_config_string(&fmt_patch_subject_prefix, var, value);
409 if (!strcmp(var, "log.abbrevcommit")) {
410 default_abbrev_commit = git_config_bool(var, value);
411 return 0;
413 if (!strcmp(var, "log.date"))
414 return git_config_string(&default_date_mode, var, value);
415 if (!strcmp(var, "log.decorate")) {
416 decoration_style = parse_decoration_style(value);
417 if (decoration_style < 0)
418 decoration_style = 0; /* maybe warn? */
419 return 0;
421 if (!strcmp(var, "log.showroot")) {
422 default_show_root = git_config_bool(var, value);
423 return 0;
425 if (!strcmp(var, "log.follow")) {
426 default_follow = git_config_bool(var, value);
427 return 0;
429 if (skip_prefix(var, "color.decorate.", &slot_name))
430 return parse_decorate_color_config(var, slot_name, value);
431 if (!strcmp(var, "log.mailmap")) {
432 use_mailmap_config = git_config_bool(var, value);
433 return 0;
435 if (!strcmp(var, "log.showsignature")) {
436 default_show_signature = git_config_bool(var, value);
437 return 0;
440 if (grep_config(var, value, cb) < 0)
441 return -1;
442 if (git_gpg_config(var, value, cb) < 0)
443 return -1;
444 return git_diff_ui_config(var, value, cb);
447 int cmd_whatchanged(int argc, const char **argv, const char *prefix)
449 struct rev_info rev;
450 struct setup_revision_opt opt;
452 init_log_defaults();
453 git_config(git_log_config, NULL);
455 init_revisions(&rev, prefix);
456 rev.diff = 1;
457 rev.simplify_history = 0;
458 memset(&opt, 0, sizeof(opt));
459 opt.def = "HEAD";
460 opt.revarg_opt = REVARG_COMMITTISH;
461 cmd_log_init(argc, argv, prefix, &rev, &opt);
462 if (!rev.diffopt.output_format)
463 rev.diffopt.output_format = DIFF_FORMAT_RAW;
464 return cmd_log_walk(&rev);
467 static void show_tagger(char *buf, int len, struct rev_info *rev)
469 struct strbuf out = STRBUF_INIT;
470 struct pretty_print_context pp = {0};
472 pp.fmt = rev->commit_format;
473 pp.date_mode = rev->date_mode;
474 pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
475 fprintf(rev->diffopt.file, "%s", out.buf);
476 strbuf_release(&out);
479 static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
481 struct object_id oidc;
482 struct object_context obj_context;
483 char *buf;
484 unsigned long size;
486 fflush(rev->diffopt.file);
487 if (!DIFF_OPT_TOUCHED(&rev->diffopt, ALLOW_TEXTCONV) ||
488 !DIFF_OPT_TST(&rev->diffopt, ALLOW_TEXTCONV))
489 return stream_blob_to_fd(1, oid, NULL, 0);
491 if (get_oid_with_context(obj_name, GET_OID_RECORD_PATH,
492 &oidc, &obj_context))
493 die(_("Not a valid object name %s"), obj_name);
494 if (!obj_context.path ||
495 !textconv_object(obj_context.path, obj_context.mode, &oidc, 1, &buf, &size)) {
496 free(obj_context.path);
497 return stream_blob_to_fd(1, oid, NULL, 0);
500 if (!buf)
501 die(_("git show %s: bad file"), obj_name);
503 write_or_die(1, buf, size);
504 free(obj_context.path);
505 return 0;
508 static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
510 unsigned long size;
511 enum object_type type;
512 char *buf = read_sha1_file(oid->hash, &type, &size);
513 int offset = 0;
515 if (!buf)
516 return error(_("Could not read object %s"), oid_to_hex(oid));
518 assert(type == OBJ_TAG);
519 while (offset < size && buf[offset] != '\n') {
520 int new_offset = offset + 1;
521 while (new_offset < size && buf[new_offset++] != '\n')
522 ; /* do nothing */
523 if (starts_with(buf + offset, "tagger "))
524 show_tagger(buf + offset + 7,
525 new_offset - offset - 7, rev);
526 offset = new_offset;
529 if (offset < size)
530 fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
531 free(buf);
532 return 0;
535 static int show_tree_object(const unsigned char *sha1,
536 struct strbuf *base,
537 const char *pathname, unsigned mode, int stage, void *context)
539 FILE *file = context;
540 fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
541 return 0;
544 static void show_setup_revisions_tweak(struct rev_info *rev,
545 struct setup_revision_opt *opt)
547 if (rev->ignore_merges) {
548 /* There was no "-m" on the command line */
549 rev->ignore_merges = 0;
550 if (!rev->first_parent_only && !rev->combine_merges) {
551 /* No "--first-parent", "-c", or "--cc" */
552 rev->combine_merges = 1;
553 rev->dense_combined_merges = 1;
556 if (!rev->diffopt.output_format)
557 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
560 int cmd_show(int argc, const char **argv, const char *prefix)
562 struct rev_info rev;
563 struct object_array_entry *objects;
564 struct setup_revision_opt opt;
565 struct pathspec match_all;
566 int i, count, ret = 0;
568 init_log_defaults();
569 git_config(git_log_config, NULL);
571 memset(&match_all, 0, sizeof(match_all));
572 init_revisions(&rev, prefix);
573 rev.diff = 1;
574 rev.always_show_header = 1;
575 rev.no_walk = REVISION_WALK_NO_WALK_SORTED;
576 rev.diffopt.stat_width = -1; /* Scale to real terminal size */
578 memset(&opt, 0, sizeof(opt));
579 opt.def = "HEAD";
580 opt.tweak = show_setup_revisions_tweak;
581 cmd_log_init(argc, argv, prefix, &rev, &opt);
583 if (!rev.no_walk)
584 return cmd_log_walk(&rev);
586 count = rev.pending.nr;
587 objects = rev.pending.objects;
588 for (i = 0; i < count && !ret; i++) {
589 struct object *o = objects[i].item;
590 const char *name = objects[i].name;
591 switch (o->type) {
592 case OBJ_BLOB:
593 ret = show_blob_object(&o->oid, &rev, name);
594 break;
595 case OBJ_TAG: {
596 struct tag *t = (struct tag *)o;
598 if (rev.shown_one)
599 putchar('\n');
600 fprintf(rev.diffopt.file, "%stag %s%s\n",
601 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
602 t->tag,
603 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
604 ret = show_tag_object(&o->oid, &rev);
605 rev.shown_one = 1;
606 if (ret)
607 break;
608 o = parse_object(&t->tagged->oid);
609 if (!o)
610 ret = error(_("Could not read object %s"),
611 oid_to_hex(&t->tagged->oid));
612 objects[i].item = o;
613 i--;
614 break;
616 case OBJ_TREE:
617 if (rev.shown_one)
618 putchar('\n');
619 fprintf(rev.diffopt.file, "%stree %s%s\n\n",
620 diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
621 name,
622 diff_get_color_opt(&rev.diffopt, DIFF_RESET));
623 read_tree_recursive((struct tree *)o, "", 0, 0, &match_all,
624 show_tree_object, rev.diffopt.file);
625 rev.shown_one = 1;
626 break;
627 case OBJ_COMMIT:
628 rev.pending.nr = rev.pending.alloc = 0;
629 rev.pending.objects = NULL;
630 add_object_array(o, name, &rev.pending);
631 ret = cmd_log_walk(&rev);
632 break;
633 default:
634 ret = error(_("Unknown type: %d"), o->type);
637 free(objects);
638 return ret;
642 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
644 int cmd_log_reflog(int argc, const char **argv, const char *prefix)
646 struct rev_info rev;
647 struct setup_revision_opt opt;
649 init_log_defaults();
650 git_config(git_log_config, NULL);
652 init_revisions(&rev, prefix);
653 init_reflog_walk(&rev.reflog_info);
654 rev.verbose_header = 1;
655 memset(&opt, 0, sizeof(opt));
656 opt.def = "HEAD";
657 cmd_log_init_defaults(&rev);
658 rev.abbrev_commit = 1;
659 rev.commit_format = CMIT_FMT_ONELINE;
660 rev.use_terminator = 1;
661 rev.always_show_header = 1;
662 cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
664 return cmd_log_walk(&rev);
667 static void log_setup_revisions_tweak(struct rev_info *rev,
668 struct setup_revision_opt *opt)
670 if (DIFF_OPT_TST(&rev->diffopt, DEFAULT_FOLLOW_RENAMES) &&
671 rev->prune_data.nr == 1)
672 DIFF_OPT_SET(&rev->diffopt, FOLLOW_RENAMES);
674 /* Turn --cc/-c into -p --cc/-c when -p was not given */
675 if (!rev->diffopt.output_format && rev->combine_merges)
676 rev->diffopt.output_format = DIFF_FORMAT_PATCH;
678 /* Turn -m on when --cc/-c was given */
679 if (rev->combine_merges)
680 rev->ignore_merges = 0;
683 int cmd_log(int argc, const char **argv, const char *prefix)
685 struct rev_info rev;
686 struct setup_revision_opt opt;
688 init_log_defaults();
689 git_config(git_log_config, NULL);
691 init_revisions(&rev, prefix);
692 rev.always_show_header = 1;
693 memset(&opt, 0, sizeof(opt));
694 opt.def = "HEAD";
695 opt.revarg_opt = REVARG_COMMITTISH;
696 opt.tweak = log_setup_revisions_tweak;
697 cmd_log_init(argc, argv, prefix, &rev, &opt);
698 return cmd_log_walk(&rev);
701 /* format-patch */
703 static const char *fmt_patch_suffix = ".patch";
704 static int numbered = 0;
705 static int auto_number = 1;
707 static char *default_attach = NULL;
709 static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
710 static struct string_list extra_to = STRING_LIST_INIT_NODUP;
711 static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
713 static void add_header(const char *value)
715 struct string_list_item *item;
716 int len = strlen(value);
717 while (len && value[len - 1] == '\n')
718 len--;
720 if (!strncasecmp(value, "to: ", 4)) {
721 item = string_list_append(&extra_to, value + 4);
722 len -= 4;
723 } else if (!strncasecmp(value, "cc: ", 4)) {
724 item = string_list_append(&extra_cc, value + 4);
725 len -= 4;
726 } else {
727 item = string_list_append(&extra_hdr, value);
730 item->string[len] = '\0';
733 #define THREAD_SHALLOW 1
734 #define THREAD_DEEP 2
735 static int thread;
736 static int do_signoff;
737 static int base_auto;
738 static char *from;
739 static const char *signature = git_version_string;
740 static const char *signature_file;
741 static int config_cover_letter;
742 static const char *config_output_directory;
744 enum {
745 COVER_UNSET,
746 COVER_OFF,
747 COVER_ON,
748 COVER_AUTO
751 static int git_format_config(const char *var, const char *value, void *cb)
753 if (!strcmp(var, "format.headers")) {
754 if (!value)
755 die(_("format.headers without value"));
756 add_header(value);
757 return 0;
759 if (!strcmp(var, "format.suffix"))
760 return git_config_string(&fmt_patch_suffix, var, value);
761 if (!strcmp(var, "format.to")) {
762 if (!value)
763 return config_error_nonbool(var);
764 string_list_append(&extra_to, value);
765 return 0;
767 if (!strcmp(var, "format.cc")) {
768 if (!value)
769 return config_error_nonbool(var);
770 string_list_append(&extra_cc, value);
771 return 0;
773 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
774 !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
775 return 0;
777 if (!strcmp(var, "format.numbered")) {
778 if (value && !strcasecmp(value, "auto")) {
779 auto_number = 1;
780 return 0;
782 numbered = git_config_bool(var, value);
783 auto_number = auto_number && numbered;
784 return 0;
786 if (!strcmp(var, "format.attach")) {
787 if (value && *value)
788 default_attach = xstrdup(value);
789 else
790 default_attach = xstrdup(git_version_string);
791 return 0;
793 if (!strcmp(var, "format.thread")) {
794 if (value && !strcasecmp(value, "deep")) {
795 thread = THREAD_DEEP;
796 return 0;
798 if (value && !strcasecmp(value, "shallow")) {
799 thread = THREAD_SHALLOW;
800 return 0;
802 thread = git_config_bool(var, value) && THREAD_SHALLOW;
803 return 0;
805 if (!strcmp(var, "format.signoff")) {
806 do_signoff = git_config_bool(var, value);
807 return 0;
809 if (!strcmp(var, "format.signature"))
810 return git_config_string(&signature, var, value);
811 if (!strcmp(var, "format.signaturefile"))
812 return git_config_pathname(&signature_file, var, value);
813 if (!strcmp(var, "format.coverletter")) {
814 if (value && !strcasecmp(value, "auto")) {
815 config_cover_letter = COVER_AUTO;
816 return 0;
818 config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
819 return 0;
821 if (!strcmp(var, "format.outputdirectory"))
822 return git_config_string(&config_output_directory, var, value);
823 if (!strcmp(var, "format.useautobase")) {
824 base_auto = git_config_bool(var, value);
825 return 0;
827 if (!strcmp(var, "format.from")) {
828 int b = git_parse_maybe_bool(value);
829 free(from);
830 if (b < 0)
831 from = xstrdup(value);
832 else if (b)
833 from = xstrdup(git_committer_info(IDENT_NO_DATE));
834 else
835 from = NULL;
836 return 0;
839 return git_log_config(var, value, cb);
842 static const char *output_directory = NULL;
843 static int outdir_offset;
845 static int open_next_file(struct commit *commit, const char *subject,
846 struct rev_info *rev, int quiet)
848 struct strbuf filename = STRBUF_INIT;
849 int suffix_len = strlen(rev->patch_suffix) + 1;
851 if (output_directory) {
852 strbuf_addstr(&filename, output_directory);
853 if (filename.len >=
854 PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len) {
855 strbuf_release(&filename);
856 return error(_("name of output directory is too long"));
858 strbuf_complete(&filename, '/');
861 if (rev->numbered_files)
862 strbuf_addf(&filename, "%d", rev->nr);
863 else if (commit)
864 fmt_output_commit(&filename, commit, rev);
865 else
866 fmt_output_subject(&filename, subject, rev);
868 if (!quiet)
869 printf("%s\n", filename.buf + outdir_offset);
871 if ((rev->diffopt.file = fopen(filename.buf, "w")) == NULL) {
872 error_errno(_("Cannot open patch file %s"), filename.buf);
873 strbuf_release(&filename);
874 return -1;
877 strbuf_release(&filename);
878 return 0;
881 static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
883 struct rev_info check_rev;
884 struct commit *commit, *c1, *c2;
885 struct object *o1, *o2;
886 unsigned flags1, flags2;
888 if (rev->pending.nr != 2)
889 die(_("Need exactly one range."));
891 o1 = rev->pending.objects[0].item;
892 o2 = rev->pending.objects[1].item;
893 flags1 = o1->flags;
894 flags2 = o2->flags;
895 c1 = lookup_commit_reference(&o1->oid);
896 c2 = lookup_commit_reference(&o2->oid);
898 if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
899 die(_("Not a range."));
901 init_patch_ids(ids);
903 /* given a range a..b get all patch ids for b..a */
904 init_revisions(&check_rev, rev->prefix);
905 check_rev.max_parents = 1;
906 o1->flags ^= UNINTERESTING;
907 o2->flags ^= UNINTERESTING;
908 add_pending_object(&check_rev, o1, "o1");
909 add_pending_object(&check_rev, o2, "o2");
910 if (prepare_revision_walk(&check_rev))
911 die(_("revision walk setup failed"));
913 while ((commit = get_revision(&check_rev)) != NULL) {
914 add_commit_patch_id(commit, ids);
917 /* reset for next revision walk */
918 clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
919 clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
920 o1->flags = flags1;
921 o2->flags = flags2;
924 static void gen_message_id(struct rev_info *info, char *base)
926 struct strbuf buf = STRBUF_INIT;
927 strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
928 (timestamp_t) time(NULL),
929 git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
930 info->message_id = strbuf_detach(&buf, NULL);
933 static void print_signature(FILE *file)
935 if (!signature || !*signature)
936 return;
938 fprintf(file, "-- \n%s", signature);
939 if (signature[strlen(signature)-1] != '\n')
940 putc('\n', file);
941 putc('\n', file);
944 static void add_branch_description(struct strbuf *buf, const char *branch_name)
946 struct strbuf desc = STRBUF_INIT;
947 if (!branch_name || !*branch_name)
948 return;
949 read_branch_desc(&desc, branch_name);
950 if (desc.len) {
951 strbuf_addch(buf, '\n');
952 strbuf_addbuf(buf, &desc);
953 strbuf_addch(buf, '\n');
955 strbuf_release(&desc);
958 static char *find_branch_name(struct rev_info *rev)
960 int i, positive = -1;
961 struct object_id branch_oid;
962 const struct object_id *tip_oid;
963 const char *ref, *v;
964 char *full_ref, *branch = NULL;
966 for (i = 0; i < rev->cmdline.nr; i++) {
967 if (rev->cmdline.rev[i].flags & UNINTERESTING)
968 continue;
969 if (positive < 0)
970 positive = i;
971 else
972 return NULL;
974 if (positive < 0)
975 return NULL;
976 ref = rev->cmdline.rev[positive].name;
977 tip_oid = &rev->cmdline.rev[positive].item->oid;
978 if (dwim_ref(ref, strlen(ref), branch_oid.hash, &full_ref) &&
979 skip_prefix(full_ref, "refs/heads/", &v) &&
980 !oidcmp(tip_oid, &branch_oid))
981 branch = xstrdup(v);
982 free(full_ref);
983 return branch;
986 static void make_cover_letter(struct rev_info *rev, int use_stdout,
987 struct commit *origin,
988 int nr, struct commit **list,
989 const char *branch_name,
990 int quiet)
992 const char *committer;
993 const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
994 const char *msg;
995 struct shortlog log;
996 struct strbuf sb = STRBUF_INIT;
997 int i;
998 const char *encoding = "UTF-8";
999 struct diff_options opts;
1000 int need_8bit_cte = 0;
1001 struct pretty_print_context pp = {0};
1002 struct commit *head = list[0];
1004 if (!cmit_fmt_is_mail(rev->commit_format))
1005 die(_("Cover letter needs email format"));
1007 committer = git_committer_info(0);
1009 if (!use_stdout &&
1010 open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1011 return;
1013 log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte);
1015 for (i = 0; !need_8bit_cte && i < nr; i++) {
1016 const char *buf = get_commit_buffer(list[i], NULL);
1017 if (has_non_ascii(buf))
1018 need_8bit_cte = 1;
1019 unuse_commit_buffer(list[i], buf);
1022 if (!branch_name)
1023 branch_name = find_branch_name(rev);
1025 msg = body;
1026 pp.fmt = CMIT_FMT_EMAIL;
1027 pp.date_mode.type = DATE_RFC2822;
1028 pp.rev = rev;
1029 pp.print_email_subject = 1;
1030 pp_user_info(&pp, NULL, &sb, committer, encoding);
1031 pp_title_line(&pp, &msg, &sb, encoding, need_8bit_cte);
1032 pp_remainder(&pp, &msg, &sb, 0);
1033 add_branch_description(&sb, branch_name);
1034 fprintf(rev->diffopt.file, "%s\n", sb.buf);
1036 strbuf_release(&sb);
1038 shortlog_init(&log);
1039 log.wrap_lines = 1;
1040 log.wrap = 72;
1041 log.in1 = 2;
1042 log.in2 = 4;
1043 log.file = rev->diffopt.file;
1044 for (i = 0; i < nr; i++)
1045 shortlog_add_commit(&log, list[i]);
1047 shortlog_output(&log);
1050 * We can only do diffstat with a unique reference point
1052 if (!origin)
1053 return;
1055 memcpy(&opts, &rev->diffopt, sizeof(opts));
1056 opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1058 diff_setup_done(&opts);
1060 diff_tree_oid(&origin->tree->object.oid,
1061 &head->tree->object.oid,
1062 "", &opts);
1063 diffcore_std(&opts);
1064 diff_flush(&opts);
1066 fprintf(rev->diffopt.file, "\n");
1069 static const char *clean_message_id(const char *msg_id)
1071 char ch;
1072 const char *a, *z, *m;
1074 m = msg_id;
1075 while ((ch = *m) && (isspace(ch) || (ch == '<')))
1076 m++;
1077 a = m;
1078 z = NULL;
1079 while ((ch = *m)) {
1080 if (!isspace(ch) && (ch != '>'))
1081 z = m;
1082 m++;
1084 if (!z)
1085 die(_("insane in-reply-to: %s"), msg_id);
1086 if (++z == m)
1087 return a;
1088 return xmemdupz(a, z - a);
1091 static const char *set_outdir(const char *prefix, const char *output_directory)
1093 if (output_directory && is_absolute_path(output_directory))
1094 return output_directory;
1096 if (!prefix || !*prefix) {
1097 if (output_directory)
1098 return output_directory;
1099 /* The user did not explicitly ask for "./" */
1100 outdir_offset = 2;
1101 return "./";
1104 outdir_offset = strlen(prefix);
1105 if (!output_directory)
1106 return prefix;
1108 return prefix_filename(prefix, output_directory);
1111 static const char * const builtin_format_patch_usage[] = {
1112 N_("git format-patch [<options>] [<since> | <revision-range>]"),
1113 NULL
1116 static int keep_subject = 0;
1118 static int keep_callback(const struct option *opt, const char *arg, int unset)
1120 ((struct rev_info *)opt->value)->total = -1;
1121 keep_subject = 1;
1122 return 0;
1125 static int subject_prefix = 0;
1127 static int subject_prefix_callback(const struct option *opt, const char *arg,
1128 int unset)
1130 subject_prefix = 1;
1131 ((struct rev_info *)opt->value)->subject_prefix = arg;
1132 return 0;
1135 static int rfc_callback(const struct option *opt, const char *arg, int unset)
1137 return subject_prefix_callback(opt, "RFC PATCH", unset);
1140 static int numbered_cmdline_opt = 0;
1142 static int numbered_callback(const struct option *opt, const char *arg,
1143 int unset)
1145 *(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1146 if (unset)
1147 auto_number = 0;
1148 return 0;
1151 static int no_numbered_callback(const struct option *opt, const char *arg,
1152 int unset)
1154 return numbered_callback(opt, arg, 1);
1157 static int output_directory_callback(const struct option *opt, const char *arg,
1158 int unset)
1160 const char **dir = (const char **)opt->value;
1161 if (*dir)
1162 die(_("Two output directories?"));
1163 *dir = arg;
1164 return 0;
1167 static int thread_callback(const struct option *opt, const char *arg, int unset)
1169 int *thread = (int *)opt->value;
1170 if (unset)
1171 *thread = 0;
1172 else if (!arg || !strcmp(arg, "shallow"))
1173 *thread = THREAD_SHALLOW;
1174 else if (!strcmp(arg, "deep"))
1175 *thread = THREAD_DEEP;
1176 else
1177 return 1;
1178 return 0;
1181 static int attach_callback(const struct option *opt, const char *arg, int unset)
1183 struct rev_info *rev = (struct rev_info *)opt->value;
1184 if (unset)
1185 rev->mime_boundary = NULL;
1186 else if (arg)
1187 rev->mime_boundary = arg;
1188 else
1189 rev->mime_boundary = git_version_string;
1190 rev->no_inline = unset ? 0 : 1;
1191 return 0;
1194 static int inline_callback(const struct option *opt, const char *arg, int unset)
1196 struct rev_info *rev = (struct rev_info *)opt->value;
1197 if (unset)
1198 rev->mime_boundary = NULL;
1199 else if (arg)
1200 rev->mime_boundary = arg;
1201 else
1202 rev->mime_boundary = git_version_string;
1203 rev->no_inline = 0;
1204 return 0;
1207 static int header_callback(const struct option *opt, const char *arg, int unset)
1209 if (unset) {
1210 string_list_clear(&extra_hdr, 0);
1211 string_list_clear(&extra_to, 0);
1212 string_list_clear(&extra_cc, 0);
1213 } else {
1214 add_header(arg);
1216 return 0;
1219 static int to_callback(const struct option *opt, const char *arg, int unset)
1221 if (unset)
1222 string_list_clear(&extra_to, 0);
1223 else
1224 string_list_append(&extra_to, arg);
1225 return 0;
1228 static int cc_callback(const struct option *opt, const char *arg, int unset)
1230 if (unset)
1231 string_list_clear(&extra_cc, 0);
1232 else
1233 string_list_append(&extra_cc, arg);
1234 return 0;
1237 static int from_callback(const struct option *opt, const char *arg, int unset)
1239 char **from = opt->value;
1241 free(*from);
1243 if (unset)
1244 *from = NULL;
1245 else if (arg)
1246 *from = xstrdup(arg);
1247 else
1248 *from = xstrdup(git_committer_info(IDENT_NO_DATE));
1249 return 0;
1252 struct base_tree_info {
1253 struct object_id base_commit;
1254 int nr_patch_id, alloc_patch_id;
1255 struct object_id *patch_id;
1258 static struct commit *get_base_commit(const char *base_commit,
1259 struct commit **list,
1260 int total)
1262 struct commit *base = NULL;
1263 struct commit **rev;
1264 int i = 0, rev_nr = 0;
1266 if (base_commit && strcmp(base_commit, "auto")) {
1267 base = lookup_commit_reference_by_name(base_commit);
1268 if (!base)
1269 die(_("Unknown commit %s"), base_commit);
1270 } else if ((base_commit && !strcmp(base_commit, "auto")) || base_auto) {
1271 struct branch *curr_branch = branch_get(NULL);
1272 const char *upstream = branch_get_upstream(curr_branch, NULL);
1273 if (upstream) {
1274 struct commit_list *base_list;
1275 struct commit *commit;
1276 struct object_id oid;
1278 if (get_oid(upstream, &oid))
1279 die(_("Failed to resolve '%s' as a valid ref."), upstream);
1280 commit = lookup_commit_or_die(&oid, "upstream base");
1281 base_list = get_merge_bases_many(commit, total, list);
1282 /* There should be one and only one merge base. */
1283 if (!base_list || base_list->next)
1284 die(_("Could not find exact merge base."));
1285 base = base_list->item;
1286 free_commit_list(base_list);
1287 } else {
1288 die(_("Failed to get upstream, if you want to record base commit automatically,\n"
1289 "please use git branch --set-upstream-to to track a remote branch.\n"
1290 "Or you could specify base commit by --base=<base-commit-id> manually."));
1294 ALLOC_ARRAY(rev, total);
1295 for (i = 0; i < total; i++)
1296 rev[i] = list[i];
1298 rev_nr = total;
1300 * Get merge base through pair-wise computations
1301 * and store it in rev[0].
1303 while (rev_nr > 1) {
1304 for (i = 0; i < rev_nr / 2; i++) {
1305 struct commit_list *merge_base;
1306 merge_base = get_merge_bases(rev[2 * i], rev[2 * i + 1]);
1307 if (!merge_base || merge_base->next)
1308 die(_("Failed to find exact merge base"));
1310 rev[i] = merge_base->item;
1313 if (rev_nr % 2)
1314 rev[i] = rev[2 * i];
1315 rev_nr = DIV_ROUND_UP(rev_nr, 2);
1318 if (!in_merge_bases(base, rev[0]))
1319 die(_("base commit should be the ancestor of revision list"));
1321 for (i = 0; i < total; i++) {
1322 if (base == list[i])
1323 die(_("base commit shouldn't be in revision list"));
1326 free(rev);
1327 return base;
1330 static void prepare_bases(struct base_tree_info *bases,
1331 struct commit *base,
1332 struct commit **list,
1333 int total)
1335 struct commit *commit;
1336 struct rev_info revs;
1337 struct diff_options diffopt;
1338 int i;
1340 if (!base)
1341 return;
1343 diff_setup(&diffopt);
1344 DIFF_OPT_SET(&diffopt, RECURSIVE);
1345 diff_setup_done(&diffopt);
1347 oidcpy(&bases->base_commit, &base->object.oid);
1349 init_revisions(&revs, NULL);
1350 revs.max_parents = 1;
1351 revs.topo_order = 1;
1352 for (i = 0; i < total; i++) {
1353 list[i]->object.flags &= ~UNINTERESTING;
1354 add_pending_object(&revs, &list[i]->object, "rev_list");
1355 list[i]->util = (void *)1;
1357 base->object.flags |= UNINTERESTING;
1358 add_pending_object(&revs, &base->object, "base");
1360 if (prepare_revision_walk(&revs))
1361 die(_("revision walk setup failed"));
1363 * Traverse the commits list, get prerequisite patch ids
1364 * and stuff them in bases structure.
1366 while ((commit = get_revision(&revs)) != NULL) {
1367 struct object_id oid;
1368 struct object_id *patch_id;
1369 if (commit->util)
1370 continue;
1371 if (commit_patch_id(commit, &diffopt, &oid, 0))
1372 die(_("cannot get patch id"));
1373 ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1374 patch_id = bases->patch_id + bases->nr_patch_id;
1375 oidcpy(patch_id, &oid);
1376 bases->nr_patch_id++;
1380 static void print_bases(struct base_tree_info *bases, FILE *file)
1382 int i;
1384 /* Only do this once, either for the cover or for the first one */
1385 if (is_null_oid(&bases->base_commit))
1386 return;
1388 /* Show the base commit */
1389 fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1391 /* Show the prerequisite patches */
1392 for (i = bases->nr_patch_id - 1; i >= 0; i--)
1393 fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1395 free(bases->patch_id);
1396 bases->nr_patch_id = 0;
1397 bases->alloc_patch_id = 0;
1398 oidclr(&bases->base_commit);
1401 int cmd_format_patch(int argc, const char **argv, const char *prefix)
1403 struct commit *commit;
1404 struct commit **list = NULL;
1405 struct rev_info rev;
1406 struct setup_revision_opt s_r_opt;
1407 int nr = 0, total, i;
1408 int use_stdout = 0;
1409 int start_number = -1;
1410 int just_numbers = 0;
1411 int ignore_if_in_upstream = 0;
1412 int cover_letter = -1;
1413 int boundary_count = 0;
1414 int no_binary_diff = 0;
1415 int zero_commit = 0;
1416 struct commit *origin = NULL;
1417 const char *in_reply_to = NULL;
1418 struct patch_ids ids;
1419 struct strbuf buf = STRBUF_INIT;
1420 int use_patch_format = 0;
1421 int quiet = 0;
1422 int reroll_count = -1;
1423 char *branch_name = NULL;
1424 char *base_commit = NULL;
1425 struct base_tree_info bases;
1426 int show_progress = 0;
1427 struct progress *progress = NULL;
1429 const struct option builtin_format_patch_options[] = {
1430 { OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
1431 N_("use [PATCH n/m] even with a single patch"),
1432 PARSE_OPT_NOARG, numbered_callback },
1433 { OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
1434 N_("use [PATCH] even with multiple patches"),
1435 PARSE_OPT_NOARG, no_numbered_callback },
1436 OPT_BOOL('s', "signoff", &do_signoff, N_("add Signed-off-by:")),
1437 OPT_BOOL(0, "stdout", &use_stdout,
1438 N_("print patches to standard out")),
1439 OPT_BOOL(0, "cover-letter", &cover_letter,
1440 N_("generate a cover letter")),
1441 OPT_BOOL(0, "numbered-files", &just_numbers,
1442 N_("use simple number sequence for output file names")),
1443 OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
1444 N_("use <sfx> instead of '.patch'")),
1445 OPT_INTEGER(0, "start-number", &start_number,
1446 N_("start numbering patches at <n> instead of 1")),
1447 OPT_INTEGER('v', "reroll-count", &reroll_count,
1448 N_("mark the series as Nth re-roll")),
1449 { OPTION_CALLBACK, 0, "rfc", &rev, NULL,
1450 N_("Use [RFC PATCH] instead of [PATCH]"),
1451 PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback },
1452 { OPTION_CALLBACK, 0, "subject-prefix", &rev, N_("prefix"),
1453 N_("Use [<prefix>] instead of [PATCH]"),
1454 PARSE_OPT_NONEG, subject_prefix_callback },
1455 { OPTION_CALLBACK, 'o', "output-directory", &output_directory,
1456 N_("dir"), N_("store resulting files in <dir>"),
1457 PARSE_OPT_NONEG, output_directory_callback },
1458 { OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
1459 N_("don't strip/add [PATCH]"),
1460 PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
1461 OPT_BOOL(0, "no-binary", &no_binary_diff,
1462 N_("don't output binary diffs")),
1463 OPT_BOOL(0, "zero-commit", &zero_commit,
1464 N_("output all-zero hash in From header")),
1465 OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
1466 N_("don't include a patch matching a commit upstream")),
1467 { OPTION_SET_INT, 'p', "no-stat", &use_patch_format, NULL,
1468 N_("show patch format instead of default (patch + stat)"),
1469 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1},
1470 OPT_GROUP(N_("Messaging")),
1471 { OPTION_CALLBACK, 0, "add-header", NULL, N_("header"),
1472 N_("add email header"), 0, header_callback },
1473 { OPTION_CALLBACK, 0, "to", NULL, N_("email"), N_("add To: header"),
1474 0, to_callback },
1475 { OPTION_CALLBACK, 0, "cc", NULL, N_("email"), N_("add Cc: header"),
1476 0, cc_callback },
1477 { OPTION_CALLBACK, 0, "from", &from, N_("ident"),
1478 N_("set From address to <ident> (or committer ident if absent)"),
1479 PARSE_OPT_OPTARG, from_callback },
1480 OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
1481 N_("make first mail a reply to <message-id>")),
1482 { OPTION_CALLBACK, 0, "attach", &rev, N_("boundary"),
1483 N_("attach the patch"), PARSE_OPT_OPTARG,
1484 attach_callback },
1485 { OPTION_CALLBACK, 0, "inline", &rev, N_("boundary"),
1486 N_("inline the patch"),
1487 PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
1488 inline_callback },
1489 { OPTION_CALLBACK, 0, "thread", &thread, N_("style"),
1490 N_("enable message threading, styles: shallow, deep"),
1491 PARSE_OPT_OPTARG, thread_callback },
1492 OPT_STRING(0, "signature", &signature, N_("signature"),
1493 N_("add a signature")),
1494 OPT_STRING(0, "base", &base_commit, N_("base-commit"),
1495 N_("add prerequisite tree info to the patch series")),
1496 OPT_FILENAME(0, "signature-file", &signature_file,
1497 N_("add a signature from a file")),
1498 OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1499 OPT_BOOL(0, "progress", &show_progress,
1500 N_("show progress while generating patches")),
1501 OPT_END()
1504 extra_hdr.strdup_strings = 1;
1505 extra_to.strdup_strings = 1;
1506 extra_cc.strdup_strings = 1;
1507 init_log_defaults();
1508 git_config(git_format_config, NULL);
1509 init_revisions(&rev, prefix);
1510 rev.commit_format = CMIT_FMT_EMAIL;
1511 rev.expand_tabs_in_log_default = 0;
1512 rev.verbose_header = 1;
1513 rev.diff = 1;
1514 rev.max_parents = 1;
1515 DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
1516 rev.subject_prefix = fmt_patch_subject_prefix;
1517 memset(&s_r_opt, 0, sizeof(s_r_opt));
1518 s_r_opt.def = "HEAD";
1519 s_r_opt.revarg_opt = REVARG_COMMITTISH;
1521 if (default_attach) {
1522 rev.mime_boundary = default_attach;
1523 rev.no_inline = 1;
1527 * Parse the arguments before setup_revisions(), or something
1528 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1529 * possibly a valid SHA1.
1531 argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1532 builtin_format_patch_usage,
1533 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
1534 PARSE_OPT_KEEP_DASHDASH);
1536 if (0 < reroll_count) {
1537 struct strbuf sprefix = STRBUF_INIT;
1538 strbuf_addf(&sprefix, "%s v%d",
1539 rev.subject_prefix, reroll_count);
1540 rev.reroll_count = reroll_count;
1541 rev.subject_prefix = strbuf_detach(&sprefix, NULL);
1544 for (i = 0; i < extra_hdr.nr; i++) {
1545 strbuf_addstr(&buf, extra_hdr.items[i].string);
1546 strbuf_addch(&buf, '\n');
1549 if (extra_to.nr)
1550 strbuf_addstr(&buf, "To: ");
1551 for (i = 0; i < extra_to.nr; i++) {
1552 if (i)
1553 strbuf_addstr(&buf, " ");
1554 strbuf_addstr(&buf, extra_to.items[i].string);
1555 if (i + 1 < extra_to.nr)
1556 strbuf_addch(&buf, ',');
1557 strbuf_addch(&buf, '\n');
1560 if (extra_cc.nr)
1561 strbuf_addstr(&buf, "Cc: ");
1562 for (i = 0; i < extra_cc.nr; i++) {
1563 if (i)
1564 strbuf_addstr(&buf, " ");
1565 strbuf_addstr(&buf, extra_cc.items[i].string);
1566 if (i + 1 < extra_cc.nr)
1567 strbuf_addch(&buf, ',');
1568 strbuf_addch(&buf, '\n');
1571 rev.extra_headers = strbuf_detach(&buf, NULL);
1573 if (from) {
1574 if (split_ident_line(&rev.from_ident, from, strlen(from)))
1575 die(_("invalid ident line: %s"), from);
1578 if (start_number < 0)
1579 start_number = 1;
1582 * If numbered is set solely due to format.numbered in config,
1583 * and it would conflict with --keep-subject (-k) from the
1584 * command line, reset "numbered".
1586 if (numbered && keep_subject && !numbered_cmdline_opt)
1587 numbered = 0;
1589 if (numbered && keep_subject)
1590 die (_("-n and -k are mutually exclusive."));
1591 if (keep_subject && subject_prefix)
1592 die (_("--subject-prefix/--rfc and -k are mutually exclusive."));
1593 rev.preserve_subject = keep_subject;
1595 argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1596 if (argc > 1)
1597 die (_("unrecognized argument: %s"), argv[1]);
1599 if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1600 die(_("--name-only does not make sense"));
1601 if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1602 die(_("--name-status does not make sense"));
1603 if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1604 die(_("--check does not make sense"));
1606 if (!use_patch_format &&
1607 (!rev.diffopt.output_format ||
1608 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
1609 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
1611 /* Always generate a patch */
1612 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1614 rev.zero_commit = zero_commit;
1616 if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1617 DIFF_OPT_SET(&rev.diffopt, BINARY);
1619 if (rev.show_notes)
1620 init_display_notes(&rev.notes_opt);
1622 if (!output_directory && !use_stdout)
1623 output_directory = config_output_directory;
1625 if (!use_stdout)
1626 output_directory = set_outdir(prefix, output_directory);
1627 else
1628 setup_pager();
1630 if (output_directory) {
1631 if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
1632 rev.diffopt.use_color = GIT_COLOR_NEVER;
1633 if (use_stdout)
1634 die(_("standard output, or directory, which one?"));
1635 if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1636 die_errno(_("Could not create directory '%s'"),
1637 output_directory);
1640 if (rev.pending.nr == 1) {
1641 int check_head = 0;
1643 if (rev.max_count < 0 && !rev.show_root_diff) {
1645 * This is traditional behaviour of "git format-patch
1646 * origin" that prepares what the origin side still
1647 * does not have.
1649 rev.pending.objects[0].item->flags |= UNINTERESTING;
1650 add_head_to_pending(&rev);
1651 check_head = 1;
1654 * Otherwise, it is "format-patch -22 HEAD", and/or
1655 * "format-patch --root HEAD". The user wants
1656 * get_revision() to do the usual traversal.
1659 if (!strcmp(rev.pending.objects[0].name, "HEAD"))
1660 check_head = 1;
1662 if (check_head) {
1663 struct object_id oid;
1664 const char *ref, *v;
1665 ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1666 oid.hash, NULL);
1667 if (ref && skip_prefix(ref, "refs/heads/", &v))
1668 branch_name = xstrdup(v);
1669 else
1670 branch_name = xstrdup(""); /* no branch */
1675 * We cannot move this anywhere earlier because we do want to
1676 * know if --root was given explicitly from the command line.
1678 rev.show_root_diff = 1;
1680 if (ignore_if_in_upstream) {
1681 /* Don't say anything if head and upstream are the same. */
1682 if (rev.pending.nr == 2) {
1683 struct object_array_entry *o = rev.pending.objects;
1684 if (oidcmp(&o[0].item->oid, &o[1].item->oid) == 0)
1685 return 0;
1687 get_patch_ids(&rev, &ids);
1690 if (prepare_revision_walk(&rev))
1691 die(_("revision walk setup failed"));
1692 rev.boundary = 1;
1693 while ((commit = get_revision(&rev)) != NULL) {
1694 if (commit->object.flags & BOUNDARY) {
1695 boundary_count++;
1696 origin = (boundary_count == 1) ? commit : NULL;
1697 continue;
1700 if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
1701 continue;
1703 nr++;
1704 REALLOC_ARRAY(list, nr);
1705 list[nr - 1] = commit;
1707 if (nr == 0)
1708 /* nothing to do */
1709 return 0;
1710 total = nr;
1711 if (cover_letter == -1) {
1712 if (config_cover_letter == COVER_AUTO)
1713 cover_letter = (total > 1);
1714 else
1715 cover_letter = (config_cover_letter == COVER_ON);
1717 if (!keep_subject && auto_number && (total > 1 || cover_letter))
1718 numbered = 1;
1719 if (numbered)
1720 rev.total = total + start_number - 1;
1722 if (!signature) {
1723 ; /* --no-signature inhibits all signatures */
1724 } else if (signature && signature != git_version_string) {
1725 ; /* non-default signature already set */
1726 } else if (signature_file) {
1727 struct strbuf buf = STRBUF_INIT;
1729 if (strbuf_read_file(&buf, signature_file, 128) < 0)
1730 die_errno(_("unable to read signature file '%s'"), signature_file);
1731 signature = strbuf_detach(&buf, NULL);
1734 memset(&bases, 0, sizeof(bases));
1735 if (base_commit || base_auto) {
1736 struct commit *base = get_base_commit(base_commit, list, nr);
1737 reset_revision_walk();
1738 prepare_bases(&bases, base, list, nr);
1741 if (in_reply_to || thread || cover_letter)
1742 rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
1743 if (in_reply_to) {
1744 const char *msgid = clean_message_id(in_reply_to);
1745 string_list_append(rev.ref_message_ids, msgid);
1747 rev.numbered_files = just_numbers;
1748 rev.patch_suffix = fmt_patch_suffix;
1749 if (cover_letter) {
1750 if (thread)
1751 gen_message_id(&rev, "cover");
1752 make_cover_letter(&rev, use_stdout,
1753 origin, nr, list, branch_name, quiet);
1754 print_bases(&bases, rev.diffopt.file);
1755 print_signature(rev.diffopt.file);
1756 total++;
1757 start_number--;
1759 rev.add_signoff = do_signoff;
1761 if (show_progress)
1762 progress = start_delayed_progress(_("Generating patches"), total);
1763 while (0 <= --nr) {
1764 int shown;
1765 display_progress(progress, total - nr);
1766 commit = list[nr];
1767 rev.nr = total - nr + (start_number - 1);
1768 /* Make the second and subsequent mails replies to the first */
1769 if (thread) {
1770 /* Have we already had a message ID? */
1771 if (rev.message_id) {
1773 * For deep threading: make every mail
1774 * a reply to the previous one, no
1775 * matter what other options are set.
1777 * For shallow threading:
1779 * Without --cover-letter and
1780 * --in-reply-to, make every mail a
1781 * reply to the one before.
1783 * With --in-reply-to but no
1784 * --cover-letter, make every mail a
1785 * reply to the <reply-to>.
1787 * With --cover-letter, make every
1788 * mail but the cover letter a reply
1789 * to the cover letter. The cover
1790 * letter is a reply to the
1791 * --in-reply-to, if specified.
1793 if (thread == THREAD_SHALLOW
1794 && rev.ref_message_ids->nr > 0
1795 && (!cover_letter || rev.nr > 1))
1796 free(rev.message_id);
1797 else
1798 string_list_append(rev.ref_message_ids,
1799 rev.message_id);
1801 gen_message_id(&rev, oid_to_hex(&commit->object.oid));
1804 if (!use_stdout &&
1805 open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
1806 die(_("Failed to create output files"));
1807 shown = log_tree_commit(&rev, commit);
1808 free_commit_buffer(commit);
1810 /* We put one extra blank line between formatted
1811 * patches and this flag is used by log-tree code
1812 * to see if it needs to emit a LF before showing
1813 * the log; when using one file per patch, we do
1814 * not want the extra blank line.
1816 if (!use_stdout)
1817 rev.shown_one = 0;
1818 if (shown) {
1819 print_bases(&bases, rev.diffopt.file);
1820 if (rev.mime_boundary)
1821 fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
1822 mime_boundary_leader,
1823 rev.mime_boundary);
1824 else
1825 print_signature(rev.diffopt.file);
1827 if (!use_stdout)
1828 fclose(rev.diffopt.file);
1830 stop_progress(&progress);
1831 free(list);
1832 free(branch_name);
1833 string_list_clear(&extra_to, 0);
1834 string_list_clear(&extra_cc, 0);
1835 string_list_clear(&extra_hdr, 0);
1836 if (ignore_if_in_upstream)
1837 free_patch_ids(&ids);
1838 return 0;
1841 static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
1843 struct object_id oid;
1844 if (get_oid(arg, &oid) == 0) {
1845 struct commit *commit = lookup_commit_reference(&oid);
1846 if (commit) {
1847 commit->object.flags |= flags;
1848 add_pending_object(revs, &commit->object, arg);
1849 return 0;
1852 return -1;
1855 static const char * const cherry_usage[] = {
1856 N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
1857 NULL
1860 static void print_commit(char sign, struct commit *commit, int verbose,
1861 int abbrev, FILE *file)
1863 if (!verbose) {
1864 fprintf(file, "%c %s\n", sign,
1865 find_unique_abbrev(commit->object.oid.hash, abbrev));
1866 } else {
1867 struct strbuf buf = STRBUF_INIT;
1868 pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
1869 fprintf(file, "%c %s %s\n", sign,
1870 find_unique_abbrev(commit->object.oid.hash, abbrev),
1871 buf.buf);
1872 strbuf_release(&buf);
1876 int cmd_cherry(int argc, const char **argv, const char *prefix)
1878 struct rev_info revs;
1879 struct patch_ids ids;
1880 struct commit *commit;
1881 struct commit_list *list = NULL;
1882 struct branch *current_branch;
1883 const char *upstream;
1884 const char *head = "HEAD";
1885 const char *limit = NULL;
1886 int verbose = 0, abbrev = 0;
1888 struct option options[] = {
1889 OPT__ABBREV(&abbrev),
1890 OPT__VERBOSE(&verbose, N_("be verbose")),
1891 OPT_END()
1894 argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
1896 switch (argc) {
1897 case 3:
1898 limit = argv[2];
1899 /* FALLTHROUGH */
1900 case 2:
1901 head = argv[1];
1902 /* FALLTHROUGH */
1903 case 1:
1904 upstream = argv[0];
1905 break;
1906 default:
1907 current_branch = branch_get(NULL);
1908 upstream = branch_get_upstream(current_branch, NULL);
1909 if (!upstream) {
1910 fprintf(stderr, _("Could not find a tracked"
1911 " remote branch, please"
1912 " specify <upstream> manually.\n"));
1913 usage_with_options(cherry_usage, options);
1917 init_revisions(&revs, prefix);
1918 revs.max_parents = 1;
1920 if (add_pending_commit(head, &revs, 0))
1921 die(_("Unknown commit %s"), head);
1922 if (add_pending_commit(upstream, &revs, UNINTERESTING))
1923 die(_("Unknown commit %s"), upstream);
1925 /* Don't say anything if head and upstream are the same. */
1926 if (revs.pending.nr == 2) {
1927 struct object_array_entry *o = revs.pending.objects;
1928 if (oidcmp(&o[0].item->oid, &o[1].item->oid) == 0)
1929 return 0;
1932 get_patch_ids(&revs, &ids);
1934 if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1935 die(_("Unknown commit %s"), limit);
1937 /* reverse the list of commits */
1938 if (prepare_revision_walk(&revs))
1939 die(_("revision walk setup failed"));
1940 while ((commit = get_revision(&revs)) != NULL) {
1941 commit_list_insert(commit, &list);
1944 while (list) {
1945 char sign = '+';
1947 commit = list->item;
1948 if (has_commit_patch_id(commit, &ids))
1949 sign = '-';
1950 print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
1951 list = list->next;
1954 free_patch_ids(&ids);
1955 return 0;